2

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?

sahar21
  • 186
  • 2
  • 15
  • 1
    possible duplicate of [AJAX POST and Plus Sign ( + ) -- How to Encode?](http://stackoverflow.com/questions/1373414/ajax-post-and-plus-sign-how-to-encode) – showdev Aug 03 '15 at 20:12

3 Answers3

6

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),
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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");
Kenneth Salomon
  • 1,352
  • 11
  • 18
  • Better to use `encodeURIComponent`, so that all special characters will be replaced, not just `+`. – Barmar Aug 03 '15 at 20:16
  • That is very true. I guess my answer is just solely focused. If anyone uses my answer, you really should use `encodeURIComponent` instead to account for all special characters – Kenneth Salomon Aug 03 '15 at 20:17
  • No problem, I think the other folks have better/more accurate answers though. Did any of them work for you yet? – Kenneth Salomon Aug 03 '15 at 20:39
1

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);

    }
});
TJ Mazeika
  • 942
  • 1
  • 9
  • 30