2

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.

2
  • 1
    where are you stuck? Check for any tuto regarding how to send data using ajax... Commented Dec 8, 2013 at 13:17
  • 1
    Constructive comment! Asked for the first time and at once punch :( Commented Dec 10, 2013 at 12:51

1 Answer 1

5

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
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I used the short form of $.ajax which is $.post.. I like it cuz it's way easier, and usually one doesn't need much more functionality ... usually!
Is JSON.stringify() JavaScript function?
Thank you, Omar Ali! You show me, that array will be placed to object before converting to JSON.
No worries.. let me know if you need anything else! :) Yes, JSON.stringify() is a javascript function I don't like to be a prick, but that you could have easily googled :) developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
But this is demonstrating how to post an object with an array in it, not how to post an array with objects. :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.