I have a textarea in a form that I'm trying to send via ajax with jQuery. My problem is when the textarea contains linebreaks and ampersand (&).
I get the value of the textarea 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);
With the textarea value as follows:
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 the PHP script, I json_decode the posted data and it works correctly.
If I then change the textarea to include an ampersand as follows:
1/8 CLEAR MIRROR
3/8 CLEAR GLASS & GLASS
the json_decode fails. The 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 change the js code above to this:
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 data cases with a syntax error.
So, how can I send textarea data that contains linebreaks and ampersands via ajax to a php backend, and have json_decode not fail?
Solution:
Based on some of the 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, in case it can help anyone else.
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;