Search code examples
phpjsonform-data

JSON.parse Error after decoding JSON.stringify-ed Array


I want to submit an array of arrays through JSON. So I create an object, apply JSON.stringify() on it and set it to a formData...

    var sources = new Array();
    $('.source-instance').each(function(){

        var auxObject = {};
        auxObject["sourceTitle"] = $(this).find(".source-title").val();   

        sources.push(auxObject);
        console.log('sources: ' + JSON.stringify(sources));
    });

    formData.set('sources', JSON.stringify(sources));

When I check the data

console.log(formData.get('sources'))

I get

[{"sourceTitle":"SomeTitle"},{"sourceTitle":"AnotherTitle"}]

... which I then proceed via AJAX to the server.

On server side in php I loop over the array and let it print:

foreach (json_decode($request['sources'], true) as $sourceInstance) {
    print_r($sourceInstance);
}

I get

Array
(
    [sourceTitle] => SomeTitle
)
Array
(
    [sourceTitle] => AnotherTitle
)

which looks pretty fine. But I also get

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

How come that? And how can I repair this? I don't see, where it is coming from.

EDIT the ajax looks like this:

    $.ajax({
        url: '/piece/store',
        type: 'POST',
        processData: false,
        contentType: false,
        dataType: 'JSON',     
        data: formData,
        success: function(response){
           if (response.status == 'error'){
              // show the erors
           }
           if (response.status == 'success'){ // "redirect" to success page
               window.location.replace('/succes');
           }
        },
        error: function(response){
           $(".optional.errors").show();
           $('ul.errors').empty();
           $.each(response.errors, function (index, error) {
               $('ul.errors').append('<li>' + error + '</li>');
           });    
       }
    });

the php responds:

$response = [
    'status' => 'success',
];                     
return response()->json($response);

Solution

  • That error message happens when jQuery is trying to parse the response from the ajax call.

    In your ajax request, you have set: dataType: 'json', which tells jQuery to expect the response to be a json-string. jQuery will then try to parse that json-string into a json-object (using JSON.parse()).

    However, since you have print_r($sourceInstance) in your PHP-code, the response won't be a valid json-string and will make JSON.parse() fail.

    Any output on the server side (echo, var_dump, print_r etc) will be a part of the response.