Link to home
Start Free TrialLog in
Avatar of APD Toronto
APD TorontoFlag for Canada

asked on

How Do I Call PHP from JS/JQuery? AJAX?

Hi Experts,

How Do I Call PHP from JS/JQuery?  I'm thinking AJAX?

A common example is "Load More Results", where without refreshing the page, I use a jquery listener to call a PHP function (or, if I cannot be as specific, then a PHP page), that would return to the JS a JSON object.

In theory, this should  be  possible with AJAX, but how? as well, how wold I stop everything else from firing until this process is complete.

Thank  you!
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

AJAX calls a page and gets results in return.  Then what you do with them is up to you.  Here is an old demo page I wrote showing how to do that.  The links on the left pass a parameter to the PHP page to tell what text is requested.
http://www.dibsplace.com/webdev/ndxv1.php
Avatar of APD Toronto

ASKER

Hi Dave,

What would the returnfunc.php look like?

I mean, once you have the $results array, how do you pass it back to JS?
SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
AJAX makes a call to a script. How you structure that script is up to you - the script returns data and in the AJAX complete function you define what must be done with that data.

A simple example
<div id="content"></div>

<script>
$(function() {
   $('#content').load('yourscript.php');
});
</script>

Open in new window


This approach uses jQuery's load function which executes the script and loads the returned content into the specified element.

If you want more control
<script>
$(function() {
    $.post('yourscript.php',data, function(resp) {
         // do something with return
    });
});
</script>

Open in new window


For a JSON return
<script>
$(function() {
    $.post('yourscript.php',data, function(resp) {
         // do something with JSON return
    }, 'JSON');
});
</script>

Open in new window


Remember the A in AJAX is for asynchronous which means you do your processing of returned data in the completion function.

Now if you want to trigger the above on an event you simply link it to an event handler
This demonstrates executing the AJAX call on a click event - it also shows the $.ajax() function of which the $.post and $.load are aliases.

$(function() {
  $('.someclass').click(function(e) {
     e.preventDefault();
     $.ajax({
         url: 'yourscript.php',
         data: {val: 1, someothervalue: 'text'},
         type:'POST',
         dataType:'JSON'
     }).then(function(resp) {
       // completion processing here
     });
  });
});

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial