I have the following code which I’m using to populate form fields. This code receives a JSON dataset which has been encoded using the PHP json_encode function.
The code works fine for single quotes and double quotes seperately, however there are occassions when I will have single quotes inside double quotes. An example would be text inside a textarea which might say: The man said “I’m going on vacation”.
I’ve read the single quote doesn’t need escaping and the double quotes are being escaped correctly. I’ve copied the JSON code from Firebug into a validator and it comes back correct which makes me think the code below is at fault. The error I’m getting in Firebug is a syntax error. Strangely enough if I have two single quotes (ie. to open and close) the problem no longer exists.
I’ve spent 3 hours looking at this and don’t seem any closer to a resolution. I appeciate all advice as ever! I can provide further code snippets as needed.
$.ajax({
type: "GET",
url: "casedata.php",
data: {'caseid':'<?php echo($caseid); ?>', 'callid':'<?php echo($_GET['callid']); ?>', 'stage':'thlViewCall'},
dataType: "json",
async: false,
success: function(data){
$.each((data), function(i, e) {
if($("input[type=text]")) {
$('#'+i).val(e);
}
if($("input[type=select-one]")) {
$('#'+i+' option').prop("selectedIndex", e);
}
if($("input[type=select-multiple]")) {
$('#'+i+' option').prop("selectedIndex", e);
}
if($("input[type=radio]")) {
$('input[name="'+i+'"][value="'+e+'"]').attr('checked', 'checked');
}
});
}
});
Edit:
Apologies, please find the JSON demonstrating this error below:
{"calldate":"06-07-2012","adviserid":"18","service":"THL","dda_sen":"eqa","finalhearing_date":"24-07-2012","reason_for_tribunal":"part_4","next_deadline_description":"before_final_evidence","understanding_paperwork":"1","ability_negotiate":"1","legal_complexity":"1","comments":"test","action":"referred_to_tss_for_telephone_support","bgInfo":"The man said \"I'm going on holiday\"","initialAdvice":"test2","logreceived":"no","monitored":"no","monitoredby":"","monitoreddate":"00-00-0000","monitorednotes":"","legalsupport":"no","legalsupportid":"0","legalsupportdate":"00-00-0000","legalsupportnotes":""}
I have fixed this and would like to share my result considering the advice I’ve received in multiple questions on multiple topics.
I found selecting using input[type] very unreliable, for some reason my text fields were being detected as radio boxes causing unwanted results. The simplest way to fix this was to use class selectors applied to my form elements, an example of my code is below:
This evaluates the name of the field passed in the “i” javascript variable, checks the CSS class of the field then sets the value or attribute accordingly. This is very tidy in my opinion and makes CSS styling that bit easier too.
I hope my explanation cancels out that -1 for missing the JSON to start with 🙂