1

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

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 - 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 :)
1
data: { txt: $('textarea#tr').val() }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.