User97798 User97798 - 6 months ago 37
JSON Question

Getting JSON Error while calling multiple function

Getting JSON Error while calling multiple function


Error - Uncaught SyntaxError: Unexpected token ' in JSON at position 0


I am calling multiple function in jquery but it is giving error i have tried so much way but the error get changed but it not working what should i do.

HTML

<div id="div1">
<input type="submit"onclick='Function1()'>
<input type="text" value="Text1" id="input1">
<input type="text" value="Text2" id="input2">
</div>

<div id='div2'></div>


jQuery

function Function1(){
var input1 = $("#input1").val();
var input2 = $("#input2").val();
var datajson = { "input1" : input1, "input2" : input2 };
var data = "'"+JSON.stringify(datajson)+"'";
Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}

function Post_Funtion(URl,DATA,FUNCTION){

var url = encodeURIComponent(URl);
var data = JSON.parse(DATA);

$.ajax({
type: "POST",
url: url,
data: data,
cache: false,
success: function(html) {
eval(FUNCTION);
}
});
}

Answer

You are trying to JSON.stringify() the post data incorrectly, then turning around and parsing it back to pass to the ajax options.

This whole step is needless. Pass the object through as is and jQuery will take care of it from there

function Function1(){
    var input1 =  $("#input1").val();
    var input2 =  $("#input2").val();
    var data = { "input1" : input1, "input2" : input2 };   
    Post_Funtion('testpost.php',data,'$("#div2").html(html);')
}


function Post_Funtion(URl,DATA,FUNCTION){    
    var url = encodeURIComponent(URl);       

    $.ajax({
       data: DATA,
       /* other options the same */

    ....
}
Comments