6

I want to use the jQuery $.ajax to make a POST call sending some information (via POST like: page.aspx?var1=value....).

But I also want jQuery to handle that the service is returning JSON so that I get back a JSON object.

var data = {name: _name, ...};

var request = $.ajax({
    url: url,
    type: "post",
    data: data,
    //dataType: "json"
});

As soon as I use dataType: "json", which allows me to receive the JSON object I get an parseerror on the request!

Hope you can help me out with that!

THANKS IN ADVACE!

5
  • What's the exact error you get? Commented Feb 28, 2013 at 8:34
  • 1
    If you're getting a parse-error, it likely means your JSON is invalid. Can you paste the string of JSON you get returned? It's likely the syntax is broken somewhere. Commented Feb 28, 2013 at 8:35
  • You can set a header like "Content-Type: application/json" in the request and jQuery will autmatically know what its getting. Commented Feb 28, 2013 at 8:35
  • You can't control what the server is going to send back to you unless they define a way to do so. So, are you supposed to be sending them the form in JSON, or are you supposed to be sending a standard POST object? Next question - what format does the server define as being the response? Commented Feb 28, 2013 at 8:36
  • Holy crap. You guys really are QUICK!! I think I have found the problem. I was thinking that the parseError was because it was trying to parse my POST data into json, but actually there was a non-well-formatted json returing form the server!!! :) I am right that dataType: 'json' is the setup for receiving a json object and that type: 'post' allows me to make a normal POST-call with whatever data.. right?! THANK YOU SOME MUCH FOR THAT FAST RESPINSE AND HELP!! Commented Feb 28, 2013 at 8:43

4 Answers 4

9

From the requested url you have to make data in JSON format like

echo json_encode($response);

and then you will get that response JSON in success function like this:

       $.ajax({
            type:"POST",
            url: "your_url",
            data:data,
            success: function (response){
                var arr = $.parseJSON(response);

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

1 Comment

In my own experience, I have had best results when invoking the browsers native JSON parser rather than use jQuery library for parsing. All modern browsers now support this method, making it a better method for cross-browser compatibility. var arr = JSON.parse(response);
0

make sure your serverside script return encoded json.

In php use json_encode().

echo json_encode($response);

also set dataType : 'json' in $.ajax call.

5 Comments

the proper way is to set the header on your POST file by header('Content-type: application/json'); ... this forces the server to recognize it as json. no need for the dataType:json at that point.
@LifeInTheGrey isn't that what jQuery does when you set the dataType ?
@barts it certainly TRIES to, but it is successful only a portion of the time. a proper PHP header declaration works 100% of the time, guaranteed. and wouldn't it make more sense to have server-side PHP code rather than javascript code, for performance reasons?
@LifeInTheGrey dataType: 'json', indicate that the response type is JSON it is not necessary if your PHP script correctly sets the Content-Type: application/json response header..otherwise its needed..
@DipeshParmar the point was that by declaring the header in PHP you can avoid unnecessary Javascript. it means guaranteed results on the backend, and faster processing on the frontend. but it was just a best practices recommendation, ur more than welcome to do as u wish.
0

Firstly post request does not have the parameters appended after the URL. The format you have specified is for GET request. You can achieve the same goal with following:

$.post(
'/yourURLL',
{'data' : dataJson},
function(data){
    handleIncomingJSON(data);
}).error(function(data, textStatus){handleUnsuccessfulSave(data, textStatus)});

Comments

0

As per the jQuery $.post documentation, I highly recommend implementing all the major callback methods (done, fail, always) initially so that if there were errors with your JSON response then they don't get hidden:

var jqxhr = $.post( 
    "example.php", 
    function(response) {var arr = JSON.parse(response);},
    'json'
)
.done(function() {console.log( "second success" );})
.fail(function() {console.log( "error" );})
.always(function() {console.log( "finished" );});

Comments

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.