Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax encoding data

I have this code (below)..

$.ajax
({
    type: "POST",
    url: "../WebServices/Feedback.svc/sendfeedback",
    dataType: 'json',
    async: false,
    data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + encodeURIComponent(note) + '", "code" : "' + code + '", "permission" : "' + permission + '"}',
    contentType: "application/json; charset=utf-8"
});

I am using this to pass in data to a web service but the problem is if there are any characters in there like this (, / ? : @ & = + $ #). I have put in an encodeURIComponent which works fine and then in the web service I put them back again.

What i'm asking is if there is a better way of accomplishing this? It seems a bit crazy that I have to encode the string each time before passing it through..

Thanks

like image 700
tmutton Avatar asked Mar 10 '11 17:03

tmutton


2 Answers

pass data thru as an object instead of a string:

$.ajax
({
...
data: {stars: stars, rating: rating...(etc)}
});
like image 55
James Avatar answered Sep 20 '22 10:09

James


Is the web service belong to you or do you use someone else's web service? What was the reason the web service is not accepting (, / ? : @ & = + $ #)?

jQuery $.ajax default contentType is application/x-www-form-urlencoded which mean jQuery will encode the content. However, since you have specify different contentType, the data is not encoded thus you have to do your own encoding.

Alternatively, you could try to remove the contentType option and pass in your content normally (without encodeURICompnent).

$.ajax
({
    type: "POST",
    url: "../WebServices/Feedback.svc/sendfeedback",
    dataType: 'json',
    async: false,
    data: '{"stars": "' + stars + '", "rating" : "' + rating + '", "note" : "' + note + '", "code" : "' + code + '", "permission" : "' + permission + '"}',
});
like image 32
Quad Coders Avatar answered Sep 20 '22 10:09

Quad Coders