1

I'm programming an web page and I really stucked trying to send an Array of JSON objects to my PHP backend script.

this is my javascript code (using jQuery):

            var toSend = new Array();
            $("input[type=checkbox]").each(
                function (indice, item)
                {
                    var dom = $(item);
                    var domJSON = {
                        id: dom.attr("value"),
                        checked: (dom.attr("checked") == "checked" ? true : false)
                    };
                    //put object as JSON in array:
                    toSend.push($.toJSON(domJSON));                        
                }
            );
            $.ajax({
                type:"POST",
                url: "salvar_escala.php",
                data: {checkbox: toSend},
                success: function(response) {
                    $("#div_salvar").html(response);
                },
                error: function() {
                    alert("Erro");
                }
              }
            );

And in PHP I have this:

    //Grab the array
    $arrayFromAjax = $_POST['checkbox'];

    foreach($arrayFromAjax as $aux) {
        $temp = json_decode($aux, true);
        $id = $temp['id'];
        $value = $temp['checked'];

        //This line doesn't print anything  for $id and $value
        echo "Id: $id | Value: $value<br />";

        //This line prints an crazy string, but with right values
        echo "CHEKBOX[] => $b<br />";
    }

In this code, I'm decoding my objects to json, putting then in an array and sending. I also tried but objects in array (without json), and then, convert the array to json, and send them like that:

            $.ajax({
                type:"POST",
                url: "salvar_escala.php",
                dataType: "json",
                data: {checkbox: $.toJSON(toSend)},
                success: function(response) {
                    $("#div_salvar").html(response);
                },
                error: function() {
                    alert("Erro");
                }
              }
            );

But in this case, it's worse, the error function is called.

1 Answer 1

2

You should be able to do the following in PHP

<?php
$checkboxes = json_decode($_POST['checkbox']);
foreach($checkboxes as $checkbox) {
    $id = $checkbox['id'];
    $val = $checkbox['value'];
    print $id . ': ' . $val;
}

The problem is that you're trying to loop through a JSON string without first decoding it into a PHP array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man! I was a little confused with the json_encode/decode!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.