Jump to content

Refresh part of a page upon successful ajax call


lordterrin
Go to solution Solved by kicken,

Recommended Posts

I have a page that functions like this:

 

The user begins by loading ajaxtest.php, then using a drop-down menu, selects a user, after which a DIV on ajaxtest.php is populated with the user's selction to getuser.php?q=John%Doe

 

Here's a visual representation of what is currently happening, along with the part I don't understand.

VbkMg8C.png

 

getuser.php consists largely of a a large HTML table which interacts through PHP with my SQL database.  Several of the fields in this table are editable, and after the user changes one of these fields, he can press an "update" button, which calls an AJAX script in update.js and runs update.php, which contains all my SQL queries to update the database, without the user being redirected to this update.php page. All of this is processing perfectly - the user makes some sort of edit, hits "update", and the database gets updated without any redirection or refresh.

 

Here's what I can't figure out though.  Once the user makes a change, and hits "update," the database updates, but the end user doesn't see those changes that he made.  I can't just do a simple page refresh, because the action is taking place on getuser.php, but getuser.php is loaded inside of a #DIV on ajaxtest.php.  If I use something like window.location.reload(), this just refreshes ajaxtest.php and puts the user back to the starting point of having to select a user.  This is not what I want.  I don't want to refresh ajaxtest.php, I want to "refresh" ajaxtest.php with getuser.php?q=John%Doe insidethe DIV on ajaxtest.php.

 

It seems like this is very common - several forums have this capability, where a user has a page loaded, adds a comment, and sees that comment immediately without a full page refresh.  I just don't know how to do it, and I've tried at lengths to search the web for an answer with no luck.

 

Can someone walk me through how to do this?

Link to comment
Share on other sites

You need to understand the difference between a common page refresh after a press on the submit button and what happens if javascript handles everything.

 

I assume that you know how a simple form works: User fills in some formfields and presses the submit button. Submitting a form is like a page refresh or a redirect with only that difference that some additional form-data has been sent with the request.

 

And now you are dealing with AJAX. Ajax is a feature in javascript. And before i forget to tell you: javascript runs in the browser from the user where PHP runs on the webserver. That is a HUGE difference.

Right we are talking about scripting in the browser. With javascript you can hide, show or change some elements on the page. With the help of AJAX you can also fire a new request to ANY server in the world.

That will happen completely on the background. The user will not mention that. The action that the server does can be anything: updating a record, deleting a record, what ever you want. After this action the server has to send a response to the client. This response can be anything as well. It can be an answer like "accepted"  or "Ok" but it can also be data. For example new data to fill a div with a new content. These days this data comes often in a format that we call JSON, But can be sent as plain text or xml as well. After that THE JAVASCRIPT in the browser received some data back from the AJAX call to the server there will be still nothing visible. The javascript must be extended with some functions that handle the data and update a part of the page content.

 

Before i start to write a complete tutrorial:

Google on basic AJAX examples and start to play with it.

After that google on JSON.

If you are common with JQuery than you could search on the JQuery website as well.

Link to comment
Share on other sites

Thank you - both of you - for taking the time to help me out.

 

@david- I believe I have somewhat tried what you're suggesting above...

// Submit the form using AJAX.
    $.ajax({
        type: 'POST',
        url: form.attr('action'),
        data: formData,
        success: function() {
          toastr.success('Update Successful',  '');
          $.get("getuser.php?q="+encodeURIComponent(pmName), function(data) {
            $('txtHint').html(data);        
        });
        }
    });

What I'm trying to say here is -

  • upon success of this AJAX function, the database will have updated, so:
  • get getuser.php?q=John%Doe, then: 
  • put that result back into the txtHint DIV.  

This doesn't work, and my understanding of why this doesn't work is because I don't know how to tell this function that 'txtHint' exists on ajaxtest.php  I've read through a few posts, but I can't figure out syntactically how this second part works.  I get that $('txtHint') is the name of the DIV that I want to put stuff into, but I don't understand what the .html does intrinsically, (e.g. - if this div exists on a php page, do I still use .html?)  I am assuming that (data) is a reference to the line above, where I'm taking the information from $.get() and putting it into a function called (data).  If my understanding of this is wrong, please tell me. 

 

I don't understand exactly what this line is doing, but I will attempt to explain my understanding of it:

document.getElementById('namehere').innerHTML = ajaxobject.responseText;

This code will go on my initial ajaxtest.php page.  When this page initially loads, this line of code will be read, but nothing will come of it, as at that exact moment there is no data inside (responseText).  Later, when I make a change and click the submit button, and my update.js file executes, and the ajax function runs, (responseText) is filled with data and is [somehow magically] returned to this document.getElementById call.

 

 

@Frank - I'm somewhat clear on the difference between server-side and client-side, and what's happening where.  This has only deepened my confusion though as I attempt to solve this.  I've read a bit on JSON, and its similarities to XML, but I don't really understand HOW that helps me in this situation.  I spent a few weeks working through this initial ajax query that I posted above, trying to understand how it works, but I am obviously still pretty new at this, and just trying to make logical sense of it.

Link to comment
Share on other sites

I have the same issue (while we're on it) with this second statement:

<form id="startPage" method="POST" action="getuser.php?q=<?php echo $q; ?>">
            Page <?= $_SESSION['page'] ?> of <?= $totalPages ?>  :   
            <input class="button" type="submit" name="previous" value="START" onclick="this.value=<?php echo $prevLimit; ?>">  
            <input class="button" type="submit" name="next" value="NEXT" onclick="this.value=<?php echo $nextLimit; ?>">      
            </form>

I created a few variables, $prevLimit, $nextLimit, and $totalPages - in order to split the results of what I pull in the SQL query that generates the table into manageable pieces.  Here's the button:

 

U8vtY6s.png

When the user loads the page at the start, this is set to "Page 1 of 7", meaning there are a total of 70 entries for this person, and since I'm only showing him 10 at a time, there are 7 pages. When the user clicks on START or NEXT, it WORKS - it increases the various php variables and re-populates the table with entries 10-19, then 20-29, etc.  This was the best way I knew to build this functionality into my project.  However, I'm suffering from the same thing as above - since getuser.php is loaded "inside" of ajaxtest.php, when they click the button, it reloads getuser.php and gets rid of the ajaxtest.php header bar that I have on the top of the page.

 

Here's what it looks like if it helps:  The top part of the image is what they see when they load ajaxtest.php, then when they select a user from the drop-down, the bottom part of the page is populated.

 

X698oIo.png

 

Of course, I understand why this is not working - because of this line of code 

<form id="startPage" method="POST" action="getuser.php?q=<?php echo $q; ?>">

I say - when this form is activated, action getuser.php?q=John%20Doe - I just don't know how to make this work.......

Link to comment
Share on other sites

  • Solution

This doesn't work, and my understanding of why this doesn't work is because I don't know how to tell this function that 'txtHint' exists on ajaxtest.php  I've read through a few posts, but I can't figure out syntactically how this second part works.  I get that $('txtHint') is the name of the DIV that I want to put stuff into, but I don't understand what the .html does intrinsically, (e.g. - if this div exists on a php page, do I still use .html?)  I am assuming that (data) is a reference to the line above, where I'm taking the information from $.get() and putting it into a function called (data).  If my understanding of this is wrong, please tell me.

Assuming txtHint is the ID of the div you want to put the content into, then you should be using $('#txtHint'). The # is neccessary. As for details about what .html() is and does, see the jQuery documentation on .html(). Basically it gets/sets the HTML content of the element.

 

I don't understand exactly what this line is doing, but I will attempt to explain my understanding of it:

document.getElementById('namehere').innerHTML = ajaxobject.responseText;

 

This is basically just the non-jquery way to do the same thing, set the HTML content of an element.

 

I have the same issue (while we're on it) with this second statement:

...

I say - when this form is activated, action getuser.php?q=John%20Doe - I just don't know how to make this work.......

Basically you need to convert the form to submit via ajax and load the results into your DIV.

 

<form id="startPage" method="POST" action="getuser.php?q=<?php echo $q; ?>">
   Page <?= $_SESSION['page'] ?> of <?= $totalPages ?>  :   
   <button class="button" type="submit" name="previous" value="<?php echo $prevLimit; ?>">START</button>
   <button class="button" type="submit" name="next" value="<?php echo $nextLimit; ?>">NEXT</button>
</form>
<script type="text/javascript">
$('#startPage').on('click', 'button', function(e){
   e.preventDefault(); //Cancel traditional submission
   var url = this.form.action; //'this' refers to the button which was clicked.  'this.form' is the form.
   var postData = {};
   postData[this.name] = this.value; //create post data for the PHP script.
   $.post(url, postData, function(html){
      $('#txtHint').html(html);
   }, 'html');
});
</script>
  • Like 1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.