Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How to stop AJAX function escaping JSON string used to POST data

I need to serialize all inputs from a form into a JSON string.
With the help of this post, I can successfully create a valid string as below:

{"input01":"value01","input02":"value02","input03":"value03"}

However, when I try to use the string to POST data using jQuery's Ajax function, it seems to add backslashes to the string, resulting in the JSON string being sent using GET rather than POST. The loaded PHP page returns a $_GET array of:

[{\"input01\":\"value01\",\"input02\":\"value02\",\"input03\":\"value03\"}] =>

I have tested the JSON string using alert() to confirm the structure is correct before being used in the AJAX function.
Additionally, if I just manually type in the valid JSON string, the AJAX posts the data correctly.

My code is as follows:

var dataJSON = $.toJSON($('#form').serializeObject());
alert(dataJSON);

$.ajax({
    type: "POST",
    url: "ajax.php",
    data: 'Query01=01&Query02=02',
    dataType: 'json',
    success: function(data){
       if (data==1){
         $('#wrap').load('ajax.php',dataJSON);
       }
    }
});
like image 910
ticallian Avatar asked Oct 14 '09 12:10

ticallian


People also ask

Does Ajax use Get or Post?

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option.

How does Ajax return success data?

The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds. The function takes three parameters, namely: The data returned from the server, formatted according to the dataType parameter, or the dataFilter callback function.

How GET and POST method are used in Ajax?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

Can Ajax return JSON?

You couldn't directly return an array from AJAX, it must have converted in the valid format. In this case, you can either use XML or JSON format. In the tutorial demonstration, I will return an array of users from AJAX, while return converts the array into JSON format using the json_encode() function in the PHP.


1 Answers

I did it so that it works with stripslashes on the php side.

Something like this:

$data = json_decode(stripslashes($_POST['json_data']));
like image 70
Magnus TechApple Avatar answered Oct 01 '22 07:10

Magnus TechApple