JQuery POST request - return JSON

I want to use jQuery $.ajaxto make a POST call to send some information (via POST, for example: page.aspx?var1=value....).

But I also want jQuery to process that the service returns JSON, so that I return 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 get a JSON object, I get a parseerror on request!

I hope you can help me with this!

THANKS IN THE RECOMMENDATIONS!

+5
source share
4 answers

From the requested URL you need to make the data in JSON format as

echo json_encode($response);

and then you get the JSON response in the success function as follows:

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

            }
        });
+8
source

, script json.

php json_encode().

echo json_encode($response);

dataType : 'json' $.ajax.

0

Firstly, the mail request has no parameters added after the URL. The format you specified is for a GET request. You can achieve the same goal:

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

According to the jQuery $.postdocumentation I strongly recommend to implement all the main callback methods ( done, fail, always) initially so that if there were errors with the JSON response, they did not hide:

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" );});
0
source

All Articles