1

I have a jQuery AJAX function like this:

$.ajax({
    url: 'crud/clients.php',
    dataType: 'json',
    type: 'POST',
    data: { 
        id:rowID,
        clientID:$('#clientID').val(),
        clientName:$('#clientName').val()
    }
    success: function(data){ 
        alert(data); 
    }
});

I then setup my query in the clients.php file. Finally, I execute the query with this line:

mysql_query( $sql ) or die(mysql_error());

How do I return the results of that query in JSON format so that my AJAX function can catch whatever is returned?

2
  • 4
    As a side note, you should move away from the mysql_* functions in favor of prepared statements. Commented Jun 18, 2012 at 22:28
  • What's a "prepared statement"? Sorry, I'm new :) Commented Jun 18, 2012 at 22:29

1 Answer 1

6

try this :

$q = mysql_query( $sql ) or die(mysql_error());
$res = json_encode(mysql_fetch_assoc($q));
echo $res;

you can also take a look at : jQuery.getJSON & jQuery.parseJSON

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

3 Comments

Ok, I put these lines in my code and intentionally messed up the $sql query with a field name that doesn't exist in the table. When I do this, and step through the PHP, it just stops at the mysql_query( $sql ) or die(mysql_error()); line and doesn't proceed down to the json_encode line. Now, when there is no error, and the DB updates correctly, I can see that null is returned. Is that supposed to happen?
@FastTrack try echo $q; instead of echo $res; if update is ok you will get 1 else you will get 0
Ok, I'll try in a bit and post back with my results.

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.