Yan Morand Yan Morand - 1 month ago 5
Ajax Question

AJAX returning data from an older AJAX call

I have a page that is populated by dynamically loading data through AJAX calls.

Main page:

$( document ).ready(function() {
$( "#searchbar" ).load( "searchbar.php" );
});
$( document ).ajaxStart(function() {
$( "#loader" ).show();
});
$( document ).ajaxComplete(function() {
$( "#loader" ).hide();
});


searchbar.php:

$( "#search" ).submit(function( event ) {
event.preventDefault();
var name = encodeURIComponent($( "#name" ).val());
var srv = $( "input:radio[name=server]:checked" ).val();
$.ajax
({
cache: false,
type: "GET",
url: "playercard.php",
data: "name=" + name + "&server=" + srv,
success: function (msg)
{
$("#contentarea").html(msg).fadeIn('slow');
}
});
return false;
});


playercard.php (main content):

$( document ).on('click', '#refreshbutton', function() {
$.ajax
({
cache: false,
type: "GET",
url: "playercard.php",
data: "name=<?php echo $summoner; ?>&server=<?php echo $server; ?>",
success: function (msg)
{
$("#contentarea").html(msg).fadeIn('slow');
}
});
return false;
});


Everything works fine on the first search. (type in search, submit, content area gets populated with data from playercard.php) The refresh button on playercard.php also works fine.

But, if I make another search, the content area does get populated with new content. But when I click the refresh button, it reloads the data from the first search. (Even though caching is disabled and the get parameters seem to be right.)

Any idea of what could be causing this?

Answer

Try this ;)

This line is causing this unexpected behavior:

data: "name=<?php echo $summoner; ?>&server=<?php echo $server;     ?>",

Here you are setting values using PHP which are always same for each request you need to replace these values with JavaScript values same as you are doing in searchbar.php; So replace playercard.php with the following code:

$(document).on('click', '#refreshbutton', function(event){
  event.preventDefault();
  var name = encodeURIComponent($( "#name" ).val());
  var srv = $( "input:radio[name=server]:checked" ).val();
  $.ajax({
      cache: false,
      type: "GET",
      url: "playercard.php",
      data: "name=" + name + "&server=" + srv,
      success: function(msg)
      {
        $("#contentarea").html(msg).fadeIn('slow');
      }
    });
  return false;
});