Search code examples
javascriptangularjssymfonyngresource

AngularJS, ngResource - Unexpected token Error


EDIT:

I got the mistake but no solution. It seems that 'isEditable', 'isOnline' and 'isRecycled' are not sent as booleans but as strings. Therefore my Validaton did not pass and the Error-Response was not valid JSON.

But why does the .save() call sents the booleans as string?


Original Post

Can anyone tell me why following function throws

SyntaxError: Unexpected token '

at Object.parse (native)

at fromJson (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.js:1072:14)

As my postData is logged correctly, I think there is a mistake in my resource-save. On the server side I have a simple selfmade php-framework made using Symfony2 components and the $save call of the resource adds a new row in my database and returns this row as a JSON object.

        $scope.createStructure = function($event, createdStructure){
        $event.preventDefault();
        if(createdStructure.copy != null){
            copyId = createdStructure.copy.id;
        } else {
            copyId = 0;
        }
        postData = {
            'title': createdStructure.title,
            'id': copyId,
            'isEditable': false,
            'isOnline': false,
            'isRecycled': false
        }
        console.log(postData);
        Structure.save({}, postData, function(response){
            console.log(response);
            console.log(newStructure);
        });
    }

Solution

  • PHP can't tell what data type is being passed in. The POST data is seen as a string. Check this previous answer out. I believe it covers the issue you are having.

    PHP also has FILTER_VALIDATE_BOOLEAN, which is also covered in the answer I linked. I think it'll help you.

    For example:

    $isEditable= filter_var ($_POST['isEditable'], FILTER_VALIDATE_BOOLEAN);
    

    That should make $isEditable a boolean.