Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 389
azzy81 Avatar asked Mar 12 '26 14:03

azzy81


2 Answers

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);
});
like image 81
Nick Craver Avatar answered Mar 14 '26 04:03

Nick Craver


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

like image 28
jAndy Avatar answered Mar 14 '26 04:03

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!