i am generating a json string using JSON.stringify
and my json string will be like
jsonstring=[{"step1":[{"nm":"John & joe"},{"title":"Hello & hai"}]},{"step2":[{"desc":"1234"},{"usr":"abc@xyz.com"}]}]`
i am escaping &
with \&
and sending this json string to server through ajax.
$.ajax({
url:"test-usr-data.php",
type:"post",
data:"usrdata="+jsonstring,
success: function(response){
console.log("data is "+response);
},
complete:function (jqXHR, textStatus){
console.log("ajax Request completed"+textStatus);
}
});
The problem is with &
char in json string, even though i am escaping &
to \&
data is not posted to server but ajax request status is success.
I tried removing &
from json string it works fine and data is posting to server correctly.
Can any one help me in correct way to escaping &
in json string.
Who told you that escaping in URL's works by prepending a backslash?
jQuery will take care of it, just do
data: {usrdata: jsonstring},
FYI: You could use encodeURIComponent
as well
data: "usrdata=" + encodeURIComponent(jsonstring),
The way to URI encode a &
is as %26
, given that 0x26 (38) is the ASCII code for that character.
But don't, use the data: { key: value, ... }
way of passing parameters to $.ajax
instead, and have jQuery do it all for you.