0

I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.

Heres the JSON that gets passed on to the PHP

[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]

The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together

var dataz = [];
var arrayContainingAll = [];

$("li", "#ingredientlist").each(function() {
    var tempArray = [];
    tempArray.push($(".ingredientname", this).text());
    tempArray.push($(".unittext", this).text());
    tempArray.push($(".amounttext", this).text());
    arrayContainingAll.push(tempArray);
});

dataz.push($("h1").text());
dataz.push($("#method").val());
dataz.push(arrayContainingAll);
var json = JSON.stringify(dataz);

How can i make PHP parse the multidimensional array correctly? I have fixed it by passing on 3 different stringified arrays, but its more the curiosity of why a multidimensional array fails

The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));

because it appearantly is important to show how i post the data, heres the JS to do the ajax request

$.ajax({
    url: '/api/savenewrecipe.php',
    type: 'POST',
    data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(),
    success: function(result) {
        if (result.ok == true) {
            // @todo remove this for debugging purposes
            //document.location.href = '/recipe/' + result.id;
        }
        else {
            showError("Noget gik galt!", 2000);
        }
    }

});
5
  • where do u post it to php in ur js?? Commented Mar 10, 2011 at 21:21
  • did you pass it through stripslashes() ? Commented Mar 10, 2011 at 21:23
  • no, look in the code - i simply put it through json_decode Commented Mar 10, 2011 at 21:24
  • also what does ur php think is in $_POST[ingredients'] ? Commented Mar 10, 2011 at 21:25
  • @yoavmatchulsky please post the stripslashes text as an answer Commented Mar 10, 2011 at 21:29

1 Answer 1

2

If your server uses magic quotes, you'll need to remove them:

if (get_magic_quotes_gpc()) {
  $_POST['ingredients'] = stripslashes($_POST['ingredients']);
}
Sign up to request clarification or add additional context in comments.

1 Comment

i just read the comment section i think you beat me to the answer =) +1

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.