tags:

views:

61

answers:

4

i am trying to use the Jquery ajax function to call a php page to run a query and return xm the only problem is i dont know how to read the Jquery API page

http://api.jquery.com/jQuery.ajax/

it gives this example

$.ajax({ url: "test.html", context: document.body, success: function(){
    $(this).addClass("done");
  }});

is there a better example to call a php page to run a sql query and return a json i can encode

A: 

You would just replace the "test.html" with a PHP script that does what you want to do - look up data in a database and return it in JSON.

This is almost a duplicate of a similar question I answered earlier that should explain how to work with PHP and JSON and such, but basically you build an array with the data you want and then run it through json_encode() and output it.

cincodenada
A: 

Take a look at this question: http://stackoverflow.com/questions/3629879/jquery-ajax-can-i-store-more-than-one-variable-on-success it has an example of sending json requests with jquery and encoding json at server-side.

aularon
+2  A: 

See http://api.jquery.com/jQuery.getJSON/ . For example...

The PHP...

<?php
// users.php
$some_users = array(
                   array('name' => 'Nobby Clark', 'email' => '[email protected]'),
                   array('name' => 'John Doe', 'email' => '[email protected]'),
              );
print json_encode($some_users);
?>

The Javascript...

$.getJSON('users.php', function(data) {
    var users = "";
    for ( var i = 0; i < data.length; i++ ) {
        users += "<p>" + data[i].name + " (" + data[i].email + ") </p>";
    }
    $('.userlist').html(users);
});
HarryF
Whoops, you beat me to the punch.
mattalexx
A: 

If you scroll down that page you will see a bunch of examples that should fill in the blanks for you.

As for the server side stuff, use the PHP file you call to:

  1. Connect to, then query the database for the data you want to return.
  2. Make sure the data you want to return to the client (JavaScript) is in a PHP array.
  3. Output the array using json_encode().
  4. Kill the script.

Something like this:

// Query DB into an array
$data = array(
   array('foo' => 'we got this from the DB'),
   array('bar' => 'new row')
   );

// Output as JSON
print json_encode($data);
die;
mattalexx