2

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This definitely can work -- and I have a different method that I use in a system with a bit of traffic and it works like a charm.
by diferent method, do you mean something totally different or a variation of this..
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.