user1260310
user1260310

Reputation: 2227

php ajax within ajax

I have some ajax that loads php script output into a div. I would like the user then to be able to click on links in the output and rewrite the div without reloading the whole page. Is this possible in principle? Imagine code would look like:

html

<div id="displayhere"></div>

php1 output

echo '<a href="javascript:void(0);" onclick="reLoad(par1,par2,par3);">ChangeToNew</a>';

JS

function reLoad(par1,par2,par3) {
...
 document.getElementById("displayhere").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","php2.php?par1="+par1 etc.,true);
xmlhttp.send();

php2

$par1 = $_get['par1'];
change database
echo '<a href="javascript:void(0);" onclick="reLoad(par1,par2,par3);">'.$par1.'</a>';

Could this in principle work or is the approach flawed?

Thanks.

Upvotes: 2

Views: 131

Answers (2)

u7string
u7string

Reputation: 1

I'm used to using jQuery so will give examples using it.

If you create your links as

<a href="file_to_run.php?par1=1&par2=2&par3=3" id="do_this">Click Me</a>

You could then write your code as

<script>
  $("#do_this").live('click', function(){
    var link_url = $(this).attr('href');
    $.ajax({
      url: link_url,
      success: function(data) {
        $('#displayhere').html(data);
      }
   return false;
 };
</script>

If you use jQuery, make sure you use the .live('click', function(){}) method versus the .click(function(){}) method, otherwise it won't recognize dynamically created elements. Also make sure you do a return false.

Upvotes: 0

Mitya
Mitya

Reputation: 34556

What you describe is standard, everyday AJAX. The PHP is irrelevant to the equation; the JS will simply receive whatever the server sends it. It just happens that, in your case, the server response is being handled by PHP. The JS and PHP do not - cannot - have a direct relationship, however.

So the principle is fine. What you actually do with it, though, will of course impact on how well it works.

Things to consider:

  • what will the PHP be doing? This may affect the load times
  • what about caching responses, if this is applicable, so the PHP doesn't have to compute something it's previously generated?
  • the UI - will the user be made aware that content is being fetched?

Etc.

Upvotes: 6

Related Questions