Tom
Tom

Reputation: 2634

passing json object with jquery ajax

Trying to go back to basics here and send a JSON object via ajax to my php. I can't even get to that part as I get a JSON error. Here is the jquery code:

jQuery(".deletebutton").on("click", function() {

        var employees = [
        { "firstName":"John" , "lastName":"Doe" },
        { "firstName":"Anna" , "lastName":"Smith" },
        { "firstName":"Peter" , "lastName": "Jones" }
        ];

        var dataString = JSON.stringify(employees);

        // Lets put our stringified json into a variable for posting
        var postArray = {json:dataString};

        jQuery.ajax({
            type: 'POST',
            url: 'index.php?option=com_recordings&task=deletevideos&format=raw',
            data: postArray,
            dataType: 'json',
            success: function(data){
                if (data == "blah")
                    alert(data);

            }
        });
});

I get this error (when I check errorThrown): SyntaxError: JSON.parse: unexpected character. I checked with jsonlint.com that it is valid JSON. What am I doing wrong?

Upvotes: 3

Views: 12792

Answers (3)

user3165240
user3165240

Reputation: 36

change to data: dataString

and no problems will occure

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

dataType refers to the request header, not the response. If you are not sending back valid JSON, jQuery won't like it. You want to send JSON, but you probably want to get back something else. Just remove dataType and it should work properly, unless there's an error on the server script.

Upvotes: 3

flec
flec

Reputation: 3009

The thing you are posting is a js-object not json. You have to post the stringified json.

data: dataString

Upvotes: 1

Related Questions