sahar21
sahar21

Reputation: 186

why replaced plus in string by space

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

Answers (3)

Kenneth Salomon
Kenneth Salomon

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

TJ Mazeika
TJ Mazeika

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

Barmar
Barmar

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

Related Questions