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

5

12

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);
       }
    }
});
Unswerving answered 14/10, 2009 at 12:15 Comment(2)
You're calling .ajax(), then making another ajax request with .load(). Is that correct?Phlogistic
Roatin, that is correct. The example above is simplified from my actual script. The actual script posts data using $.ajax that needs to be validated, if successfully validated, the $.load function loads HTML generated from data posted by the JSON string.Unswerving
U
0

After scouring Google and the jQuery site, i've come to the personal conclusion that the $.load function will convert any variable passed to it as a querystring (As my original problem above outlined). If you wish to pass a JSON string through it, it has to be manually typed.

To get around this, I used the low level $.ajax function instead. An advantage of using this method meant I could also send POST data using the standard .serialize() function rather than having to convert my form data into JSON.

My final code:

var formData = $('#form').serialize();

$.ajax({
     type: "POST",
     url: "ajax.php",
     data: 'Query01=01&Query02=02',
     dataType: 'json',
     success: function(data){
          if (data==1){
               $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: formData,
                    success: function(html){
                         $("#wrap").replaceWith(html);
                    }   
               });
          }
     }
});

If anyone else has a solution, please comment.

Unswerving answered 15/10, 2009 at 0:25 Comment(1)
Since you're using php as server-side. I guess, you could have used the php function stripslashes()Valance
S
11

This is the default behaviour of $.ajax(). You can change it by setting the processData option to false. See $.ajax() options.

data  Object, String

Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key i.e. {foo:["bar1", "bar2"]} becomes '&foo=bar1&foo=bar2'.

and

processData   Boolean Default: true

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, or other non-processed data, set this option to false.

Supervisor answered 14/10, 2009 at 12:21 Comment(3)
I've tested the info you've listed above without any luck. From what i can see the $.ajax options do not effect the nested $.load function. Any ideas on how i could change the same options for $.load?Unswerving
@Unswerving I am not sure why you need the load function inside the success function anyway. Can you not just get everything you need in the $.ajax request using the json value?Synoptic
processData:false returned nothingPestilential
A
4

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

Something like this:

$data = json_decode(stripslashes($_POST['json_data']));
Argyres answered 25/12, 2017 at 13:9 Comment(0)
F
2

Be sure that you

echo $_GET['varwithurl']

not

echo json_encode($_GET['varwithurl'])

as many php web examples do.

I send data with url with $.ajax() and don't see unwanted backslashes in php script.

Fortuity answered 14/12, 2011 at 12:8 Comment(0)
U
0

After scouring Google and the jQuery site, i've come to the personal conclusion that the $.load function will convert any variable passed to it as a querystring (As my original problem above outlined). If you wish to pass a JSON string through it, it has to be manually typed.

To get around this, I used the low level $.ajax function instead. An advantage of using this method meant I could also send POST data using the standard .serialize() function rather than having to convert my form data into JSON.

My final code:

var formData = $('#form').serialize();

$.ajax({
     type: "POST",
     url: "ajax.php",
     data: 'Query01=01&Query02=02',
     dataType: 'json',
     success: function(data){
          if (data==1){
               $.ajax({
                    type: "POST",
                    url: "ajax.php",
                    data: formData,
                    success: function(html){
                         $("#wrap").replaceWith(html);
                    }   
               });
          }
     }
});

If anyone else has a solution, please comment.

Unswerving answered 15/10, 2009 at 0:25 Comment(1)
Since you're using php as server-side. I guess, you could have used the php function stripslashes()Valance
E
-2
<html>
<head>
<script src="resources/jquery-2.1.0.js"></script>
<script src="resources/jquery.serializejson.min.js"></script>
</head>
<body>
  <script>

        $(document).ready(function(){

            $("#simplepost").click(function(e){

                var MyForm = $("#appForm").serializeJSON();
                console.log(MyForm);

            $.ajax(
                    {
                        url: "rest/emp/create",
                        type: "POST",
                        data: JSON.stringify(MyForm),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success:function(maindta){
                            alert(maindta);
                        },
                        error: function(jqXHR, testStatus, errorThrown){
                            alert(errorThrown);
                        }
                    });
            e.preventDefault(); //STOP default action
        });
    });
</script>
<h2>Hello World!</h2>
<form id="appForm" method="POST">
    EmployeeID:<input type="text" name='id' value="" />
    Employee Name:<input type="text" name="name" value=""/>
<br>
<input type="button" value="Submit" id="simplepost" />
</form>
</body>
</html>
Empire answered 10/10, 2014 at 23:29 Comment(1)
Code dumps without explanation are rarely helpful. Please consider adding some context to your answer.Quinone

© 2022 - 2024 — McMap. All rights reserved.