json data char '&' disturbs ajax post request data - php

i am generating a json string using JSON.stringify and my json string will be like
jsonstring=[{"step1":[{"nm":"John & joe"},{"title":"Hello & hai"}]},{"step2":[{"desc":"1234"},{"usr":"abc#xyz.com"}]}]`
i am escaping & with \& and sending this json string to server through ajax.
$.ajax({
url:"test-usr-data.php",
type:"post",
data:"usrdata="+jsonstring,
success: function(response){
console.log("data is "+response);
},
complete:function (jqXHR, textStatus){
console.log("ajax Request completed"+textStatus);
}
});
The problem is with & char in json string, even though i am escaping & to \& data is not posted to server but ajax request status is success.
I tried removing & from json string it works fine and data is posting to server correctly.
Can any one help me in correct way to escaping & in json string.

Who told you that escaping in URL's works by prepending a backslash?
jQuery will take care of it, just do
data: {usrdata: jsonstring},
FYI: You could use encodeURIComponent as well
data: "usrdata=" + encodeURIComponent(jsonstring),

The way to URI encode a & is as %26, given that 0x26 (38) is the ASCII code for that character.
But don't, use the data: { key: value, ... } way of passing parameters to $.ajax instead, and have jQuery do it all for you.

Related

Strings are escaped after ajax post

PHP version is 5.6.2
When sending a JS-object, why do strings end up escaped in PHP?
Here is my JS-code:
$.ajax({
url: url,
type: 'POST',
data: {obj: obj},
success: function(data) {},
error: function(req, status, error){},
timeout: 20000
});
All st'rin'gs end up like st\'rin\'gs in PHP. Of course I can stripslashes but what's the proper way of doing this?
Solution for everybody in the same situation, who checked and debugged and still can't find a solution: If you're using Wordpress, that's the cause. WP escapes all $_POST-variables automatically and since this AJAX was posted against wp_ajax.php, it was escaped.
I took the easy way out and did:
stripslashes_deep($_POST['obj'])
You must check your magic quotes configurations first and do proper changes, please consider reading this post: Why are $_POST variables getting escaped in PHP?

$_POST, $_GET unescape escaped query characters

I have a search field where users paste URLs (url is the search query). Most urls work fine, but urls with escaped characters are getting 'unescaped'. For example :
When I copy some url from Chrome browser I get escaped url:
url = input query : 'http://website.com/search/my%20query'
echo $_POST['q'] ~ result is 'http://website.com/search/my query'
The query is submitted by $.ajax :
var qurl = $("#url input[name=q]").val();
var queryString = "q="+qurl;
$.ajax({
url : "script.php",
type: "POST",
data: queryString,
.....
How can I receive the query with the escaped characters ?
Should I bother and process(escape the query of my query) the query url myself?
Magic quotes you are off:
php.ini
magic_quotes_gpc=Off
magic_quotes_runtime=Off
magic_quotes_sybase=Off
Your question is a bit short on detail so, unfortunately, there is a fair bit of speculation in this answer:
The % in %20 should be encoded as %25 (giving %2520) when the data is submitted.
PHP will then decode it to give you %20 in $_POST.
I've never heard of PHP double decoding the data before. So it sounds like the problem is that whatever is making the request is failing to encode the data. This is most likely caused by not using a regular form to submit it and using JavaScript instead.
The solution therefore, is to encode it properly in the JavaScript.
For example:
data = "query=" + encodeURIComponent( document.getElementById('myInput').value );
Update in response to JavaScript being added to the question:
var qurl = $("#url input[name=q]").val();
var queryString = "q="+qurl;
My earlier speculation is confirmed. You haven't encoded the data into the correct format for a query string. Since you are using jQuery.ajax, you can use that to handle your encoding (by passing it an object of data) instead of building the query string manually (and then passing a string):
$.ajax({
url : "script.php",
type: "POST",
data: {
q: $("#url input[name=q]").val()
},

The & is not allowed for my new password

I have a window on my site where the visitors can change them password.
The problem is that the & character is never taken :
If I put those two new passwords :
stack&
stack& (the second is the confirmation)
The insertion in the BD is stack (without the &).
This is the js code :
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
the alert shwos me "stack&"
In PHP, a var_dump of $_POST gives me :
stack (without the &).
Is & a reserved word for jquery ?
This is my js code :
$.ajax({
type: 'POST',
url: 'modification_mdp.php',
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
dataType: 'text',
success: function(reponse) {
reponse = $.trim(reponse);
Have you an idea to reselove this problem please ?
Thanks in advance.
Encode the field value
data: 'nouveau_mdp=' + encodeURI($('input#champ_nouveau_mdp').val()),
by this way & is encoded with the ascii number.
Try passing an associative array, which jQuery will encode for you:
data: { nouveau_mdp: $('input#champ_nouveau_mdp').val() }
You'll need to change the PHP code that receives this value to match (it gets an array rather than a string).
The ampersand character is not allowed to pass by Get method or by Post method in PHP. As the usual syntax to access the PHP by GET method is ines.php?user=username&password=mypassword,
the '&' character separates the two Variables.
That is why it is does not take '&' from 'Stack&' You may use Javascript to Validate if & is not entered in the text Box. Use JavaScript to encode the varaible... No decoding is required at the PHP end
encodeURIComponent("stack&")
This line is the problem:
data: 'nouveau_mdp=' + $('input#champ_nouveau_mdp').val(),
The & character has a special meaning in HTTP. If you had multiple parameters they would be separated by & e.g. nouveau_mdp=mynewpassword&old_mdp=myoldpassword
What you need to do is encode characters such as &, = etc as their hex equivalents i.e. %26 and %3D respectively.
In JavaScript you can do this with the encodeURI() function.
Though, as mentioned in the other answer, jQuery also allows you to pass a JSON dictionary of parameters, and it will do the encoding for you.

Correctly decoding double-encoded UTF-8 on PHP

So im trying to send data from an HTML page through Ajax, to a PHP page.
Thats the piece of jQuery code that im using:
$.ajax({
url: "test.php",
type: "POST",
data: {
name: "João"
}
}).done(function (data) {
alert(data);
})
As you can see, the parameter im sending is "João". Before making the Ajax request jQuery encodes it on the background, "João" becomes "Jo%C3%A3o" which is double encoded UTF-8.
My problem arises when the request is sent and PHP tries to decode it on the background. PHP decodes automatically it only once when I use $_POST, so instead of getting "João" I get "João". That happens because PHP is decoding every % individually, so %C3 becomes à and %A3 becomes £.
If I try to decode it manually through utf8_decode() it will work, but im here to know if there's a better solution. What I really need is a way for PHP to decode my data correctly, even if it's double-encoded, or even triple-encoded.
That's not double-encoded, it's correct UTF-8. It looks like the PHP is expecting latin-1 encoding instead, and is showing you what the same bytes would mean if they were not
UTF-8.
In this case, since your characters seem to be below 0xFF, you could also URL-encode them first as Jo%E3o in latin-1 if you can't work out how to have PHP recognize UTF-8.

jQuery ajax + responseText + Character encoding

I perform an AJAX request to a PHP script in JavaScript and by using the jQuery library.
Here is my command which performs the AJAX request :
$.ajax({
async: "false",
cache: "false",
data: {login: strLogin, password: strPassword},
datatype: "text",
error: connexionAjaxError,
success: connexionAjaxSuccess,
type: "POST",
url: "./Connexion"
});
".Connexion" is a URL redirection to my PHP script.
connexionAjaxError is a JavaScript function inevitably executed as soon as the HTTP response is received.
The reason : My PHP script results to a text/plain page with HTTP status code equal to 500.
Here is the most relevant part of my PHP script :
header("HTTP/1.0 500 Internal Server Error;
Content-type: text/plain;
charset=ISO-8859-1");
echo "été";
Here is the signature of the connexionAjaxError callback function :
function connexionAjaxError(jqXHR, textStatus, errorThrown)
My PHP results to the string "été".
My PHP internal encoding is ISO-8859-1 so the result string is encoded [e9 74 e9] in hexadecimal notation.
But jqXHR.responseText in the connexionAjaxError callback function contains a 1-character string.
I have used the charCodeAt method of the JavaScript String object to get the unicode (UTF-8 ?) code for the character.
The character is encoded 65535 in decimal notation equivalent to [ff ff] in hexadecimal notation.
I do not understand why jqXHR.responseText does not contain the 3-character string "été".
I am not an expert in JavaScript but I suppose jqXHR.responseText can only contains a string encoded in UTF-8.
So the string "été" in jqXHR.responseText would be encoded [c3a9 74 c3a9] in hexadecimal notation.
I have retrieve the UTF-8 code for the character "é" from the following web site : http://www.utf8-chartable.de/
I make a lot of development in Spanish and I've noticed a few things that might help you, since I've gone through this already:
The charset in the header function should be UTF-8.
Also, the FILE itself (the PHP script) must be saved in UTF-8, you can easily achieve this if you edit the file with Notepad++ and select the encoding to be UTF-8 without BOM.
Same goes for your javascript and HTML files, they should all be encoded with UTF-8 without BOM rather than ANSI.
Let me know!
Try to set the Contenttype like this in your call, as far as I know jQuery Ajax is always utf-8 if not specified.
$.ajax({
...
datatype: "text",
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
error: connexionAjaxError,
success: connexionAjaxSuccess,
type: "POST",
...
});
Edit:
If my answer isn't helpfull, it might help if you check the servers charset configuration, and also post it.

Categories