Steven Dropper Steven Dropper - 3 months ago 7
JSON Question

Unexpected end of JSON input... SO Wants more info

I'm confused... What's wrong with this?
Couldn't post without changing the title... I seriously don't know what's wrong

$(document).ready(function(){
$("#fmob").click(function(){
var mobname = $(this).attr("data-value");
console.log(mobname);
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {mobname: 1},
dataType: "json",
success: function(data){
if(data.response === true){
$("#fresponse").html(data.result);
}else{
$("#fresponse").html(data.result);
}
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});
});


I looked up here Unexpected end of JSON input from an ajax call

but somehow not what I expected... What's wrong? Thanks.

Answer

Try this approach:

$(document).ready(function(){
    $("#fmob").click(function(){
        var mobname = $(this).attr("data-value");
        console.log(mobname);
        var data = {}; // setup a data object
        data[mobname] = 1; // add the property with the key of the value of the "mobname" variable, with the data of 1 (per question)
        $.ajax({
            type: "POST",
            url: "/system/mobproc.php",
            data: data, // pass the data object as the POST data instead of defining an object inline
            dataType: "json",
            success: function(data){
                if(data.response === true){
                    $("#fresponse").html(data.result);  
                }else{
                    $("#fresponse").html(data.result);
                }
            },
            error:function(jqXHR,textStatus,errorThrown ){
              alert('Exception:'+errorThrown );
           }
        });
    });
});

Note the lines with comments, above.

In this approach, we setup a data object and specify a property using the value of the "mobname" variable, instead of defining the property inline. This allows us to use the dynamic value of the variable as the key for the property.