Jquery Ajax escapes strings despite magic_quotes_gpc = off
-
29-06-2021 - |
Question
Data I post via jQuery Ajax are being escaped even when magic_quotes_gpc = off
on the server.
Getting data directly from $_POST
(not using ajax) works fine, unescaped. but sending them through ajax
escapes them.
$.ajax({
url: 'includes/updateDb.php',
type: 'POST',
data: {
id: $this.attr('data-id'),
text: $this.html()
}
});
test's
-> test\'s
Is that a feature or a bug? How should I proceed? Strip the strings via PHP
on the server?
Solution 3
It turned out that despite phpinfo()
showed that magic_quotes_gpc
were turned off, they were indeed on. It was a shared-hosting feature that caused php.ini
to affect only the topmost folder. I didn't realize this.
Apologies and thanks for help -)
OTHER TIPS
AJAX is encoded as application/x-www-form-urlencoded
by default in jQuery, in your PHP use utf8_decode
to get the unescaped data
From jQuery website
contentTypeString
Default: 'application/x-www-form-urlencoded; charset=UTF-8'
now as you have been answered before
the jQuery.ajax( url [, settings] )
send only be defualt which means that it can be changed the data encoded .. this helps preventing further issues 99% of the times ...
the defualt encoding that they use is
application/x-www-form-urlencoded; charset=UTF-8
now that can be changed to any type of content let's say text/javascript
if that was the data type your sending .
but usually what we are trying to send to php is either a string or an array .
this array needs to be encoded in some way that both languages understand ...
now from version 5.2.0 php supports the json encode which is the best way to send data from java .
so you can send a json encoded number to php which looks something like this
{"foo-bar": 12345}
and using the json_decode()
turn it into
$json = '{"foo-bar": 12345}' ;
$obj = json_decode($json);
print $obj->{'foo-bar'}; // will return 12345
so officially every body just uses this format to send data from javascript to php.
for your own sake here is an example of what a php code will look like
let's say that you send something like username and password
the array will look something like this {"id": "234" , "text" : "helloo,/////text////"}
$posted_data = $_POST['id'];
$parsed_data = josn_decode('$posted_data');
echo $parsed_data -> {'text'}; // should print helloo,/////text////