1

I've been trying to send a JSON string to PHP server like this:

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure : JSON.stringify(structure)},    
});

However, every quotation mark from the string I send is escaped automatically, so I can't decode it in PHP with json_decode(). I could remove all the escape characters, but I really doubt that this way of sending JSON data to server is safe.

So, I was wondering if you have any ideas on how to do that in a simple and safe (not necessarily bulletfroof) way?

Thank you!

3 Answers 3

4

You can just do '{"structure":' + JSON.stringify(structure) + '}' or {structure: structure}

The first one is a JSON String so jQuery doesn't need to parse it. The second is a javascript object, so jQuery knows exactly how to parse it.

But you are mixing the two, so jQuery is confused and re-encodes your object, because you encoded only half your object.

So another alternative would be JSON.stringify({structure: structure })

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

1 Comment

jQuery isn't "confused", it does simply what it's supposed to do: JSON encoding an object that contains a string.
1

Try this

$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: {structure: structure},    
});

Comments

0
$.ajax({  
    type: "POST",  
    url: "themes.php?page=themeoptions",  
    data: structure,    
});

Quoting from the documentation:

dataObject 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 based on the value of the traditional setting (described below).

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.