In most of my AJAX functions I have to double encode free text entered by a user, i.e. I have to do encodeURIComponent(encodeURIComponent(myString)).
If I do it just once most symbols except double quotes and long hyphens work.
If I alert out the result from a single encode quotes are encoded, but it breaks the JSON string which is why I am confused.
Is this a bug with JavaScript or am I missing something? Is it related to the way that you have to double encode ampersand in PHP to get it to work?
Hi,
Here is the code that lets a user store a note against something:
function saveAdminNote() {
var note = encodeURIComponent(encodeURIComponent($('#adminNote').val().replace(/(\r\n|\n|\r)/gm,""))) ;
JSON = '{"mode":"UPDATE_INTNOTE", "jobid":'+jobId+', "note":"'+note+'"}' ;
clearTimeout(tOut2) ;
tOut2 = setTimeout(function(){
$.ajax({
data: 'dataString='+JSON,
url: 'core/job-builder-controlV2.php',
type: 'POST',
success: function(data){
if(data)
{
$.prompt(data) ;
}
}
})
}, 250) ;
}
So if my data structure is flat, there is no advantage to using JSON at all?
I was under the impression that JSON gave a little more security?
The basic problem is that you are trying to construct JSON by mashing together strings (instead of using a JSON library) … and encoding parts of those strings (instead of encoding the resulting JSON string (i.e. the non-URI data that you want to put into the URI) … which jQuery will do for you).
If you want to submit JSON as part of a form encoded data request, then you would:
$.ajax({
data: {
dataString: JSON.stringify({
"mode": "UPDATE_INTNOTE",
"jobid": jobId,
"note": $('#adminNote').val()
})
},
…
Since you have a flat data structure here (i.e. no objects or arrays in the data) then you don't need to use JSON at all.
$.ajax({
data: {
"mode": "UPDATE_INTNOTE",
"jobid": jobId,
"note": $('#adminNote').val()
},
(Then, in your PHP, just access $_POST['mode']
etc, instead of parsing the JSON and then getting the data from the resulting object)