2

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

1
  • Are you returning XML or JSON? You mention both. Commented Sep 2, 2010 at 21:18

4 Answers 4

3

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Whoops, you beat me to the punch.
0

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.

Comments

0

Take a look at this question: 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.

Comments

0

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;

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.