Sharon Haim Pour
Sharon Haim Pour

Reputation: 6713

Javascript special characters

I have an html with a form. After the user submits the form, the values in the form are sent to a database with ajax. My problem is that is the user submits the form with a plus sign (+) in one of the fields, the plus sign won't show in the db.

my code:

function update()
{
    var branch_id = 1;
    var saleTitle = $("#title").val();
    var saleText = $("#text").val();
    var imgSrc = $("#imgSrc").html();
    var datastr ='branch_id=' + branch_id + '&saleTitle=' + saleTitle +
                 '&saleText=' + saleText + '&imgSrc=' + imgSrc + '&func=update';

         $.ajax({
         type: "POST",
         url: "update.php",
         data: datastr,
         success: function(msg){
             //alert( "Data Saved: " + msg );
             if (msg == "")
             {
                 $("#message").html("Update was successful!");
             }
             else
             {
                 $("#message").html("Error") + "   " + msg;
             }
         }
     });
}

Upvotes: 1

Views: 599

Answers (3)

Quentin
Quentin

Reputation: 943143

Pass an object, not a string.

var dataobj = { 
    branch_id : branch_id,
    saleTitle : saleTitle,
    saleText  : saleText,
    imgSrc    : imgSrc,
    func      : "update"
};
// …
data: dataobj

Then jQuery will take care of escaping the data (+ means a space in this data format) and concatenating it into the application/x-www-form-urlencoded data for you.

Upvotes: 1

Royi Namir
Royi Namir

Reputation: 148524

use : encodeURIComponent(xxx) on the field which has the plus sign

encodeURIComponent('~!@#$%^&*(){}[]=:/,;?+\'"\\')

will result :

~!%40%23%24%25%5E%26*()%7B%7D%5B%5D%3D%3A%2F%2C%3B%3F%2B'%22%5C

Upvotes: 3

Diode
Diode

Reputation: 25135

You can try jQuery Serialize http://api.jquery.com/serialize/

Upvotes: 0

Related Questions