views:

27

answers:

2

Hi,

Is there a better way to replace a string as having & in the textarea breaks the script as it thinks its another & parameter?

function doRequest(){
var str = $('textarea#tr').val();
$.ajax({
   type: "POST",
   url: "index.php?sd=t",
   data: "txt="+str.replace(/&/g, "and"),
   success: function(){
        $("div").css('color','red');
        $("div").text('Saved');
        $("div").fadeTo(800,1);
        $("div").animate({backgroundColor:'#000000'}, 200);
        $("div").animate({backgroundColor:'#FFFF90'}, 400);
        stre = false;
   }
 });
}
+1  A: 
data: { txt: $('textarea#tr').val() }
Darin Dimitrov
+4  A: 

You can pass your data as an object and let jQuery serialize it, like this:

data: {txt: str},

Note this won't put the word "and", it'll escape it, leaving %26.

What actually happens under the covers is calling encodeURIComponent(), like this:

data: "txt="+encodeURIComponent(str),

I'd go with the first method, I'm just showing what is happening underneath for better understanding of how the encoding works.

Nick Craver
the reason of having txt is so that from within php i use $_GET['txt'], if i remove this to let jquery serialize what will the get request be called?
Slug
@Slug - It'll still be called `txt`, whatever the property name is in the object, that's what the parameter's called on the GET request, e.g. this will still serialize to "txt=something", you can test/see it with `alert($.param({txt: str}))`, that's what gets called under the covers :)
Nick Craver
oh yes sorry i over looked that, thanks very much!
Slug