Sending an array of objects to PHP function with jQuery.ajax request
ajax, arrays, javascript, jquery, php
Solution
Very easy:
<script>
var myarray = new Array();
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
$.post(
'test.php',
{ data: paramJSON },
function(data) {
var result = JSON.parse(data);
}
</script>
php side:
if(isset($_POST["data"]))
{
$data = json_decode($_POST["data"]);
$myarray = $data->myarray;
foreach($myarray as $singular)
{
// do something
}
}
Problem
There is an array of objects like this: ``` rectangle[0].width = w; rectangle[0].height = h; rectangle[1].width = w; rectangle[2].height = h; rectangle[3].width = w; rectangle[3].height = h; ... ``` How we may to send this array to PHP function with jQuery.ajax request and vise versa, modified array from PHP function as response? I mind that JS code may be: ``` request = $.ajax({ type : "POST", url : "post.php", data : {rec :rectangle} }); request.done(function(msg) { alert(msg); }); request.fail(function(jqXHR, textStatus) { alert("Function inaccessible: " + textStatus) }); ``` and PHP: ``` if (isset($_POST["rec"]) { $rec = $_POST["rec"]; $arr_length = count($rec); $response = $arr_length; } echo $response; ``` Please, demonstrate the true form of request. Thanks.