views:

334

answers:

2

how to sanitize user inputs that you gather by jquery .val() so you can write it in a dataString... in the example you see below when user writes

if some text that contains & the rest of the comment doesn't seem to work fine because it counts the rest as an other variable to POST..

is there a sanitaziation or serialization code? jQuery's sanitize() function works on forms but i want something that i can use directly use on strings...

var id = $("some_id_value_holder_hidden_field").val();
var comment = $("#sometextarea").val();

var dataString = "id=" + id + "&comment=" + comment;

$.ajax({

type: "POST",
url: "write_comment.php",
data: dataString,
dataType: "json",
success: function(res) {
  // Success
},
error: function(xhr, textStatus, errorThrown) {
  // Error
}
});

Any suggestion will be much appreciated Regards

+3  A: 

there is a built-in encodeUriComponent that does exactly what you're looking for. Besides that, you can provide an object in "data" field, in which case url encoding will be handled by jquery. In your example:

 $.ajax({
     type: "POST",
     url: "write_comment.php",
     data: { id: id, comment: comment},
     etc...
stereofrog
+1 encodeUriComponent is what you want, not escape.
Plynx
+2  A: 

Since you're using jquery, you can use the included Form plugin to serialize the array.

serialize() - Creates a url string from form fields (eg, someEle=someVal&anotherEle=anotherVal)

serializeArray() - Returns a key/value array of all the form elements (useful to know)

$.ajax({
    url : 'write_comment.php',
    type : 'post',
    data : $('#form-element').serialize(),
    success : function(data)
    {
        alert('yay!');
    }
});

Edit: Edited to remove incorrect escape() part.

John Himmelman
i could not make it work with textareas and input fields. i think serialize function can only be applied to form tag...i have just a text area with no form tag around it so i need a function to serialize string not the whole form
Yasin Ergul