azzy81
azzy81

Reputation: 2269

Jquery $.post return data

With a Jquery $.post can the returned data be an array or return 2 sets of data?

Example:

$.post("MyScript.php", { action:"run" },function(data){
    alert(data);
});

Now this simple post above posts an action to a php script which does 2 functions and returns the data which is then displayed in an alert box. But my php script performs 2 functions and need to do different things with each of the returned data.

So in essence Im asking if the $.post can return 2 sets of data like this:

$.post("MyScript.php", { action:"run" },function(data1, data2){
    alert(data1);
    $("div1").html(data2);

});

or can the return data be an array where I can assign by values to elements of the array in the php script?

Im hoping this makes sense.

Upvotes: 3

Views: 7428

Answers (4)

Hanu
Hanu

Reputation: 11

As data only returns one thing, I found this worked for me.

Content of myfile.php being posted to:

<table>
  <tr><td>
    <h2>My Heading here</h2>
    <div id="mydiv">something here</div>
  </td></tr>
</table>

JQuery on file with form to post:

$.post("myfile.php", { txtField1: "whatever" },
        function (data) {
            var content = $(data).html();
            $("#submit_result").html(content);
        }
 );

This outputs the entire table and its html content into #sumbit_result.

Upvotes: 1

Jayme Tosi Neto
Jayme Tosi Neto

Reputation: 1239

It depends on MyScript.php returns you the response. It can be, plain text, json, xml, etc. But you can only receive only one data set. Nothing prohibits of this return data set have some datasets inside it. ;)

Anyway. If it's json data (it's simplier to work with jquery) you can do something like:

$.post("MyScript.php", { action:"run" },function(data){
    $.each(data, function(index, value)
    {
        alert( index+' : '+value );
    });
});

Give a look here: http://api.jquery.com/jQuery.post/ . They have some examples that can help you. ;D

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630429

It can only return one data thing...whatever is is, HTML, XML, JSON, etc...however you can return JSON with 2 properties on it, for example:

$.post("MyScript.php", { action:"run" },function(data){
  alert(data.property1);
  $("div1").html(data.property2);
});

Upvotes: 3

jAndy
jAndy

Reputation: 236022

I'm not 100% sure if I understand you right, but this sounds like you're looking for a JSON object. You can create a datastructure on your server with php and finally encode it as a JSON string. This JSON string is what you transfer to your client. You can tell jQuery that you're expecting a json formatted string as return value by passing in json into the $.post function. That way, jQuery will decode the json string into a true javascript object.

Ref.: $.post, JSON

Upvotes: 2

Related Questions