Reputation: 186
I am using ajax to send data through an AJAX call to set.php:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: "data=" + data,
success: function (result) {
alert(result);
}
});
Before sending the AJAX call, I am using JavaScript to alert()
the data, the data is:
JeCH+2CJZvAbH51zhvgKfg==
But when I use $_POST["data"]
, the data is:
JeCH 2CJZvAbH51zhvgKfg==
Which displays pluses replaced with spaces, how can I solve this problem?
Upvotes: 2
Views: 1978
Reputation: 1390
I believe you need to encode that +
with its URL Encoded value %2B
.
To do this, use the replace
method.
var data = data.replace(/\+/g, "%2B");
Upvotes: 1
Reputation: 1042
Taking a look at the jQuery docs, you can pass an object to data
instead of the actual query built by hand. Try:
$.ajax({
url: "ajax/set.php",
dataType: "html",
type: 'POST',
data: {
data: data
},
success: function (result) {
alert(result);
}
});
Upvotes: 1
Reputation: 782106
When using $.ajax
, use an object rather than a string with the data:
option. Then jQuery will URL-encode it properly:
data: { data: data },
If you really want to pass a string, you should use encodeURIComponent
on any values that might contain special characters:
data: 'data=' + encodeURIComponent(data),
Upvotes: 6