I have textarea in the form that I am trying to submit via ajax using jQuery. My problem is that textarea has strings and ampersands (&).
I get a textarea value with the following js code:
// Find all the fields with class dirty $('#customer .dirty').each(function() { fieldName = $(this).attr('id'); fieldValue = $(this).val(); // Create an object of dirty field names and values var fields = { 'fieldName' : fieldName, 'value' : fieldValue }; // Add the object of field names and values to the custRecordToUpdate array custRecordToUpdate.push(fields); // note: this was initialized before }); var arrayToSend = { customer : custRecordToUpdate }; var dataToSend = JSON.stringify(arrayToSend);
Given the value of textarea:
1/8 CLEAR MIRROR 3/8 CLEAR GLASS
If I console.log (dataToSend) , I get the following:
{"customer":[{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR\n3/8 CLEAR GLASS"}]}
On a PHP script, I have json_decode the published data and it works correctly.
If I then changed the text box to include an ampersand as follows:
1/8 CLEAR MIRROR 3/8 CLEAR GLASS & GLASS
Json_decode error . console.log (dataToSend) displays the following:
{"customer":[{"fieldName":"cust_note","value":"1/8 CLEAR MIRROR\n3/8 CLEAR GLASS & GLASS"}]}
json_last_error () displays syntax error
If I changed the js code above:
fieldValue = encodeURIComponent($(this).val());
Then console.log (dataToSend) displays:
{"customer":[{"fieldName":"cust_note","value":"1%2F8%20CLEAR%20MIRROR%0A3%2F8%20CLEAR%20GLASS"}]}
and json_decode fails with both cases with a syntax error .
So how can I send text data containing strings and ampersands via ajax to a php server and json_decode failed to start?
Decision:
Based on some comments below, I decided to change the ajax code that sends the data, and this solved the problem, although I'm not sure why.
Anyway, here is the code if it can help anyone.
var returnedHTML = $.ajax({ type: "POST", url: 'index.php/customer/save_edit_customer', //data : "data="+dataToSend, // This is how I was sending it before data : { "data" : dataToSend }, // This is the new code that works! async: false, cache: false }).responseText;