2

Jquery Ajax Call inserts new record on DB. File been called (php) needs to return two values, the contents of the insert and it's id.

How should I send back these values (array, xml, echo) on php?

How will I separate these in the Jquery Ajax success (data)?

Currently the processing php file returns only one string being the inserted content with which I then update view. Need to return the record id so i can wire the element.

Please advice if this needs more clarification. Thank You

JQUERY

$.ajax({
                    type:'post',
                    url: 'posts_in.php',
                    data: $("#postentry").serialize(),
                    success:function(data){
                        var id='posts';
                        //split returned data here
                        $('<div></div>').attr('id',id).addClass('boxee').html(data).prependTo('#boxer');
                        $('#tittle_ent').val('').focus();
                    }

PHP

echo $value1,$value2;

print_r($arrayhere);

XML ?

3 Answers 3

3

Return a JSON string encoded with json_encode().

$php_array_result = array(1,2,3,4,5,6);

// Send the correct MIME header and echo out the JSON string
header("Content-type: application/json");
echo json_encode($php_array_result);
exit();

In your jQuery ajax call, add the dataType: "json" property.

$.ajax({
   type:'post',
   url: 'posts_in.php',
   dataType: "json",
   success: function(data) {
      console.dir(data);
   },
   // etc...
Sign up to request clarification or add additional context in comments.

5 Comments

How do I access the return data ? $.parseJSON(data)?
See addition above. In the success callback function, data will be an object from the JSON automatically parsed. In Firebug, Chrome Developer Tools, or some other debugging platform, console.dir() will show you how its contents are organized and you can go from there.
how can i read response? Firebug returns Response: ["hunx2",389]. Do i still use $.parseJSON()?
It looks like your data is already a JSON object like it should be. I think you need to access the two values as Response[0] and Response[1] to retrieve "hunx2" and 389 respectively.
Thanks for explaining that header part, saved me a load of a headache!
1

How about returning a JSON string? You use json_encode on the server side and use jQuery.parseJSON() on your jQuery.

Comments

1

I suggest you encode the data back using a JSON encoded array (json_encode()) , echo it a the response. JSON is a standard and common way to pass data back to the client.
Using jquery, you can deserialize the data using $.parseJSON(), as described here.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.