jquery - Unable to use $.parseJSON on string variable constructed with array variable -
i'm able parse variable manually initialized json using jquery's '$.parsejson();' cannot parse variable identical json format constructed using array.
javascript
var questionstype = []; var questionshtml = []; var questionsquestion = []; //store questions, types, , html each fieldset 3 separate arrays for(var i=1;i<=formpreviewid;i++) { questionsquestion.push($("#formelement_"+i + " legend").text()); questionstype.push($("#formelement_"+i).attr("class")); questionshtml.push($("#formelement_"+i)[0].outerhtml); }; //alert(questionsquestion[1] + questionstype[1] + questionshtml[1]); //format values each fieldset values format in mysql var questionsvalues = []; var index = 0; for(var i=1;i<=formpreviewid;i++) { questionsvalues.push('{"question":"'+questionsquestion[index]+'","type":"'+questionstype[index]+'","html":"'+questionshtml[index]+'"}'); index++; }; //alert(questionsvalues); //questionsvalues = questionsvalues.replace("}{", "},{"); //alert(questionsvalues); //format mysql values json format var questionsvaluesjson = '{"questions":['+questionsvalues+']}';
using manually constructed string variable identical json format --
var questionsquestion2 = '{"questions":[{"question":"test16","type":"radio", "html":"<input>"},{"question":"test2","type":"checkbox", "html":"<input>"},{"question":"test3","type":"checkbox", "html":"<input>"}]}'; parsejson(questionsvaluesjson); //works fine
using string constructed array --
var questionsvaluesjson = '{"questions":['+questionsvalues+']}'; alert(questionsvaluesjson) : {"questions":[{"question":"d","type":"radio","html":"<fieldset id="formelement_1" class="radio"><tr><td colspan="2"><legend>d</legend></td></tr><tr><td><label for="1_1">d</label></td><td><input name="radio1" value="d" type="radio"></td></tr><tr><td><label for="1_2">d</label></td><td><input name="radio1" value="d" type="radio"></td></tr></fieldset>"}]} parsejson(questionsvaluesjson); //breaks script
i sending json php file decoded , used in foreach loop can manipulate objects insert data mysql database, throwing error when trying use object in foreach loop.
here error : 'trying property of non-object'
here code :
php
foreach ($thearray->questions $data) { $insert .= '("' . $data->question . '", "' . $data->type . '", "' . $data->html . '")'; } $insert = str_replace(")(","),(",$insert); $query = "insert registrationquestions (question, type, html) values " . $insert; $mysqli->query($query);
there quotes inside html strings:
"html":"<fieldset id="formelement_1" class="radio">
this totally broken (the string values ends @ id="
).
you need escape quotes \"
.
edit: of course answer "why doesn't work". better way indeed serialize objects json.stringify, takes care of issues , others, suggested in kevin's comment.
Comments
Post a Comment