javascript - ajax - sending data as json to php server and receiving response -
i'm trying grasp more should @ once.
let's have 2 inputs , button, , on button click want create json containing data inputs , send server.
i think should it, might wrong i've seen lot of different (poorly explained) methods of doing similar.
var item = function(first, second) { return { firstpart : first.val(), secondpart : second.val(), }; }; $(document).ready(function(){ $("#send_item").click(function() { var form = $("#add_item"); if (form) { item = item($("#first"), $("#second")); $.ajax ({ type: "post", url: "post.php", data: { 'test' : item }, success: function(result) { console.log(result); } }); } }); }); in php have
class clientdata { public $first; public $second; public function __construct($f, $s) { $this->first = f; $this->second = s; } } if (isset($_post['test'])) { // stuff, object of type clientdata } the problem $_post['test'] appears array (if pass json_decode error says array , if iterate using foreach values expect see). ajax call correct? there else should in php bit?
for sending raw form data:
js part:
$.ajax ({ type: "post", url: "post.php", data: item , success: function(result) { console.log(result); } }); php part:
.. if (isset($_post['firstpart']) && isset($_post['secondpart'])) { $fpart = $_post['firstpart']; $spart = $_post['secondpart']; $obj = new clientdata($fpart, $spart); } ... for sending json string:
js part:
$.ajax ({ type: "post", url: "post.php", data: {'test': json.stringify(item)}, success: function(result) { console.log(result); } }); php part:
.. if (isset($_post['test'])) { $json_data = $_post['test']; $json_arr = json_decode($json_data, true); $fpart = $json_arr['firstpart']; $spart = $json_arr['secondpart']; $obj = new clientdata($fpart, $spart); } ...
Comments
Post a Comment