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

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.

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.

I guess the problem is with the line: data: {mobname: 1}
As you can't assign a variable name as object property like that... it should be inside a square brackets like this data: {[mobname]: 1}
EDIT: if you aren't using browser supported by ES 2015 you could even do
data: JSON.parse('{"'+mobname+'":1}')
EDIT 1 if you want to send the json data as string and convert that on php side you could simply do data: '{"'+mobname+'":1}'
This might cause your ajax call to fail, and might not return a JSON as you're expecting (using the line dattype:JSON);
So removing datatype:JSON can also help you by showing what you're doing wrong

JSON objects are differentiated from standard JavaScript objects by using double quoted in both the key and the value - unless either is an integer.
It is explained in the relevant W3Schools site.
Therefore, in your AJAX request, you have to send a properly formatted JSON object:
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: {"mobname": 1}, //here's the change
dataType: "json",
/* rest of the code */
You can of course pass a variable as well:
var JSON_obj = {"mobname": 1, "othermob": 2, /*rest of the JSON */ };
$.ajax({
type: "POST",
url: "/system/mobproc.php",
data: JSON_obj, //here's the change
dataType: "json",
/* rest of the code */
Again, with properly formatted JSON objects (and with properly included JS script if it's in another file), this should work.

Related

ajax json : how to retrieve data from json object received by ajax?

Here is the code:
$.ajax({
url: MyURL,
method: 'GET',
processData: true,
contentType: 'application/json;',
dataType: "json",
success: function(data) {
alert("Success data= "+JSON.stringify(data));
var count = Object.keys(data).length;
alert("count = "+count );
result=data[0];
alert("result.CountryName:"+ result.CountryName);
alert("total " + keys.length + " keys: " + keys);
error: function(data) { alert("ajax Error"); },
});
The 1st alert seems ok and gives:
Success data= "[{\"CountryName\": \"france\", \"Currency\": \"Euro\", \"PriceMax\": 500.00, \"PriceStep\": 50.00, \"PriceMin\": 100.00}]"
From the firebug/network/response i see the same data (with the backslash!!)
The 2nd alert gives 107. Apparently each character is an object ?
But when i check the syntax on http://jsonlint.com/ the json is correct.
Finally the last alert gives: undefined.
So what is wrong ?
Thank you for your help
The data you're sending is an array containing a single object. You'll need to use data[0]['CountryName'].
The response that you have is not an JSON object, it is a String. So you need to parse it to a JSON and then take the first position of the array.
json_data = JSON.parse(data)
result = json_data[0]
and then you use a property of that object:
result.CountryName
The problem was the slash in the json string.
I read Why does JSON returned from the django rest framework have forward slashes in the response? and make some modif in my django code.
i changed return JsonResponse(simplejson.dumps(data), safe=False)
to return JsonResponse(data, safe=False) and the slash disappeared then the javascript code worked.
Thanks for your help Daniel and Rubico

knockout's viewModel does not get updated

I have the following knockout's viewModel :
var viewModel={
businessName: "",
....
}
I also tried to identify the field like this: businessName: ko.observable("")
Then, I have a load method that requests for a JSon with a newly populated data
And this is how I'm trying to apply the new data:
$.ajax({
//
url: "#Html.Raw(#Url.Action("Load"))",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
success: function (result) {
//OPTION 1:
viewModel.businessName = result.vm.BusinessName;
//OPTION 2:
var viewModel2 = ko.mapping.fromJS(result.vm);
console.log(viewModel2.businessName);
}
});//ajax
As a result:
if I use Option1, I get the new data but it does not get updated on the page.
If I use Option2, it writes "undefined"
Please advise how can I update the new data on the page?
I checked the similar topics but there is no answer that helps
PS
It seems I resolved OPTION 1. But still don't understand why OPTION 2 does not work
ko.observable is a function, not a property. So you get it's value like this:
var whatsTheValue = myVM.MyObservable();
and you set it like this:
myVM.MyObservable(newValue);
This is all in the docs.
Note, however, when using the data-bind syntax in your HTML, you don't need to explicitly unwrap your observable by using the parenthesis because KO is smart enough to do it automatically:
<span data-bind="text: MyObservable"></span>
You have to use ko.observable in the ViewModel and access/write it accordingly.
var myViewModel = {
businessName = ko.observable('')
};
...
$.ajax({
...
success: function(result) {
myViewModel.businessName(result.vm.BusinessName);
},
...
});
Otherwise your view won't have any clue you changed businessName. In the implementation ko.observable, besides actually storing the new value, broadcasts some events to your view, letting it know the stored value changed.

How to use a list of objects or array in json post request to a WebService?

as described in the title, I'm trying to call a WebService method via JSON/Ajax in JavaScript with several String parameters and 2 lists or arrays.
For now everything worked fine with single parameters in this format:
var WSParameters = "{pParam1: 'abc', pParam2: 'def'}"
$.ajax({
type: "POST",
url: "WebService.asmx/" + webMethod,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: WSParameters,
success: function (result) {
// stuff to be done on if request was successful
},
error: function (message) { alert('Error loading data! ' + message.responseText); }
});
But now I need to provide the web service method a list/array of values. The web service method looks like this:
[WebMethod(true)]
public void editExistingSystem(System.Collections.Generic.List<String> pFirstList,
System.Collections.Generic.List<String> pSecondList,
String pParam1,
String pParam2)
{
// Stuff
}
I guess it should be something like this, but obviously this didn't work:
var WSParameters = "{pFirstList: 15,4,13, pSecondList: 'gr00001_96594737', pParam1: 'abc', pParam2: 'def'}"
Could you please help me with finding the correct syntax to define a list in this parameter list?
Thanks a lot in davance
Br
vm370
As so often, I found the solution almost right after asking the question...
Sorry guys for bothering you. The correct paramter string to the example in my starting post would be:
var WSParameters = "{pfirstList: ['15','4','13'], pSecondList: ['gr00001_96594737'], pParam1: 'abc', pParam2: 'def'}"
Thanks and best regards
vm370

Getting invalid json primitive error in jquery-ajax

I am using Jquery Ajax for calling the methods in controller, but i am always getting invalid json primitive error.
Below is the Code.
Client side Code
$("#something >li").each(function () {
widgetsobj.push({
WidgetId: $(this).attr("dbid"),
ColumnNumber: 2,
RowNumber: 3,
WidgetType: "Graph",
WidgetName: "ddd",
PageName : "Page1"
});
});
$.ajax({
url: "/Home/ABC",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) },
success: function (data) {
alert("ss");
},
error: function (data) {
debugger;
}
});
at controller
[HttpPost, ValidateInput(false)]
public JsonResult ABC(string pagename1, List<XYZ> widgetsobj1)
{
// do something
}
Note XYZ is object with below properties.
WidgetId
ColumnNumber
RowNumber
WidgetType
WidgetName
PageName
So please let me know where i am wrong.
The thing about ajax is that it is very picky about what you send through. You need to make absolutely sure that everything is in the correct format.
i.e. you are using double quotations (") rather than single (') and so on.
The best thing to do, would be to use Firebug or a similar console to view the POST as it is executed or to use alert() to view the POST data before it is sent off. That way you can identify where the problem is.
Remember, when you use json.stringify() it is going to turn whatever you feed it into what it believes will be an acceptable JSON string and because it is just a string there could be syntax errors at any point!
From what I can see here, there may be an issue at:
data: { pagename1: pagename, widgetsobj1: JSON.stringify(widgetsobj) }
You may want to try:
data: { "pagename1": pagename, "widgetsobj1": JSON.stringify(widgetsobj) }
I got the same error. My solution was to add:
dataType: 'json',
to the ajax call. Looks like you already had that in in your ajax call. But Hope this helps someone else.

Using jQuery and JSON with AJAX responseText?

Ok, I'm a bit new when it comes to jQuery and json. If I'm using json as my return type, can I still retrieve responseText from an XMLHttpRequest object?
here's the code that i'm using:
json response: {"clients": []}
$.ajax({
type: "POST",
url: "/myurl/whatever.php",
data: myData,
dataType: "json",
success: function(msg){
status.html(msg[0]);
},
error: function(msg) {
status.html("Error: " + msg[0]);
}
});
is the use of msg[0] correct if i want to output the json response or am i missing something?
how can i still use the above code with XMLHttpRequest to get the status, responseText, etc.
thanks, all!
As far as I know, the call to $.ajax returns a XHR object, and from that the responseText can be extracted, e.g.:
var xhr = $.ajax( {
url:' someInfo.php',
data: 'which=squirrels',
asynch: true
} );
var resp = xhr.responseText;
The response text will contain a json string, which would need to be converted to an object to be of any use.
If you want to use the response as a json object directly within your success: function, do as #cloudhead suggested, and use msg. The dataType : "json" in your options takes care of the conversion for you.
If you're using json, then you get a json object back, not an XML object. You can output it directly, without using [0].