1

How can i send a string with a & in it (Ex : google & facebook) as the querystring value ? Now

var strUrl="ajaxpage.aspx?subject=my subject line &cmnt=google & facebook";
strUrl = encodeURI(strUrl);

$.ajax({ url: strUrl, success: function (data) {
     alert(data)
     }
 });

Now when i read query string "cmnt", I am getting only "google" because it breaks the &

What is the workaround for this ? Thanks

4 Answers 4

5

You will need to encode that character or the entire url


& would be encoded as %26

var strUrl="ajaxpage.aspx?subject=my subject line &cmnt=google %26 facebook";

or call encodeURIComponent()

var strUrl = "ajaxpage.aspx" 
    + "?subject=" + encodeURIComponent("my subject line")
    + "&cmnt=" + encodeURIComponent("google & facebook");
Sign up to request clarification or add additional context in comments.

1 Comment

Umm. When you encodeURIComponent you have to do it on a component of a URI, not the whole query string. With that example it will encode all the & and = so the query string will just be one big string and have no key/value pairs.
3

The short answer is: Use encodeURIComponent on data strings before sticking them in query strings.

The slightly longer answer is: You're using jQuery. It will fix this for you if you let it. Let the URL be just the URL to the main resource, then pass any data you want in the query string using the data property of the object you pass to the ajax method.

$.ajax({ 
    url: "ajaxpage.aspx", 
    data: { 
        subject: "my subject line",
        cmnt: "google & facebook"
    },
    success: function (data) {
        alert(data)
    }
 });

Comments

0

You can URL encode it as %26. Will that work for what you need to do?

Comments

0

Try using escape(see why) encodeURIComponent on 'google & facebook' and append to query string.

But I would recommend @Quentin's jQuery fix!

2 Comments

Don't use escape. Never use escape. It has been deprecated with good reason.
@Quentin: Yes, you're right. There are caveats, so I shouldn't be posting it for general consumption like I did.

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.