David
David

Reputation:

jQuery AJAX call undefined error with special characters

I tried to make an AJAX call using jQuery, the data has special characters, e.g {'data':'<p>test</p>'}. It seems failed to pass this data in the first place. It will work if i just pass {'data':'test'}. encodeURIComponent and JSON.stringify failed here due to the special character < > /.

Could anyone please help with it? Thanks.

$.ajax({
    type: "POST",
    url: "services.aspx",
    data: "data=" + encodeURIComponent(JSON.stringify(obj)),
    dataType: "text",
    error: function(xhr, textStatus, errorThrown)   {   
        alert("ERROR"); },
    success: function(data)
            {   

            }               
}); 

Regards,

David

Upvotes: 4

Views: 3298

Answers (4)

Gobi
Gobi

Reputation: 291

I'm not an asp dev but I got the same issue while handling html post via jquery ajax I used to post like this:

var data = 'id='+ escape(currid) +'&html='+ escape(div_html);

$.post("http://...", data, ...);

Hope this will help you better.

Upvotes: -2

Nalum
Nalum

Reputation: 4213

Assuming that obj in encodeURIComponent(JSON.stringify(obj)) is a string or a json object then your script should work.

If obj = {'data':'<p>test</p>'}; then you don't need the encodeURIComponent you could just do data: JSON.stringify(obj)

Is there any more to the code, it might help more if you could post it.

Upvotes: -1

Ned Batchelder
Ned Batchelder

Reputation: 375584

This type of problem is sometimes tricky to debug, because so many components touch your data, and each needs its own style of quoting or escaping to be sure your data gets through as you intended.

The first thing to do is to make sure the data is getting to the ajax function properly. Just before the ajax function, use a console.log or alert() to see what the data looks like. Depending on where the data is coming from, it may not even be correct at that point.

You can use Firebug's Net panel to look at what request was actually made to the server to see the data leaving the browser. If you have access to the server, you may be able to debug within the ajax function handler there to see what data it received.

Basically, you have to walk the entire trail from where the data begins, to where the data is wrong, and find the point at which it made a wrong turn.

Upvotes: 1

googletorp
googletorp

Reputation: 33265

I gave this a quick test in firebug, and it actually worked just fine, data was sent and everything, so it sounds like your problem is not related to the ajax call itself but the function you are posting to.

Upvotes: 3

Related Questions