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!
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dave BaldwinFixer of ProblemsCommented:
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
0
APD TorontoSoftware DeveloperAuthor Commented:
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?
0
Dave BaldwinFixer of ProblemsCommented:
Take a look at 'showme.js' on that page.  It contains the AJAX routines and shows how the returned text is used.  'midfunc.php' which is called by 'fillme()' just returns whatever text you want to display like this:

<?php 
$qdat = $_GET["qdat"];
$fname = 'midtxt'.$qdat{0}.".inc";
$handle = @fopen($fname, "r");
if ($handle) {
   while (!feof($handle)) {
      $buffer = fgets($handle, 256);
		 	echo $buffer;
			}
	}
	else echo $qdat;
	fclose($handle);
?>

Open in new window

0
Julian HansenCommented:
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

0
Julian HansenCommented:
Simple PHP script to return JSON data to an AJAX call - obviously this would be fleshed out to check for parameters and customise output as required.
<?php
$data = array(
    array('name' => 'Bob', 'email' => 'bob@email.com'),
    array('name' => 'Jane', 'email' => 'jane@email.com'),
);
die(json_encode($data));

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.