I have a webservice and it returns json data like this..
{"d":"{\"RES\":[],\"STAT\":\"FAIL\",\"SID\":\"0\"}"}
how i can i read the STAT=FAIL from this. I wrote service in c#.
my script is
$.ajax({
type: "POST",
url: "http://localhost/EMRDMSService/Service.asmx/User_Login",
data: "{lg:" + JSON.stringify(GetLogDet) + "}",
// url: "http://localhost/EMRDMSService/Service.asmx/Permission_List",
// data: "{userid:" + JSON.stringify(GetLogDet) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
console.log(r.d.STAT);
}
});
But the r.d.STAT is undefined?
Can anybody help me with this?
As said in some of the comments, {"d":"{\"RES\":[],\"STAT\":\"FAIL\",\"SID\":\"0\"}"} isn't correct JSON. However, if you can't update the webservice, you could try this in your success callback:
var d = JSON.parse(r.d);
console.log(d.STAT);
EDIT in response to OP edits r.d.STAT will be undefined because d is interpreted as a String, not a Object. That's why you'll have to parse it or update the webservice to remove the quotes around the value of d.
Related
If I use $.ajax JQuery and I call WebMethod, I get JSON:
$.ajax({
type: "POST",
dataType: "json",
data: JSON.stringify({ id: idX, id2: idY }),
async: true,
cache: false,
url: "/ws/Courses.asmx/GetCourses",
contentType: "application/json; charset=utf-8",
success: function (data) {
RenderCourses(data.d);
},
});
but JSON has "d" property.
function RenderCourses(data) {
if (data.d.length > 0) {
If I use json = JsonConvert.SerializeObject in C#, hasn't the "d" property.
string script = "var data = " + json + "; RenderCourses(data);";
ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "dataVar", script, true);
And RenderCourses fails.
Any reasons?
ADO.NET WebMethods always serialize the response like this. d meand "data". And you can't do anything with this.
JsonConvert.SerializeObject is a method from third party software (Newtonsoft). It just simple serialize your object to JSON.
I am facing some problem in assigning data to div on my view page.
The code is something like this:
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
alert(data);
$('#responsestatus').text(data.Response);
$('#divResult').html(data);
});
Here, as you can see, I can see the whole data in alert box. also, I have assigned the whole data to div and i can see whole data perfectly on my page.
The Sample Response which i got back is a huge data so i am posting link for it http://pastebin.com/eEE72ySk
Now I want to iterate through each and every data but unable to do it.
Example:
$('#responsestatus').text(data.Response.ResponseStatus);
Then error is:
UncaughtTypeError:Cannot read property 'ResponseStatus' of undefined
Please Someone tell me what is wrong here. Why cant I iterate over data in response
You are getting your response back as a string, but trying to operate on it like it were a javascript object.
There is one of two things you could do
Tell the server you're expecting json data back
Parse the string response to json after it is received.
The first should be as simple as setting the datatype property on the request
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
datatype: 'json',
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
$('#responsestatus').text(data.Response.ResponseStatus);
});
The second involves parsing the response before using it
$.ajax({
url: "/api/Flight/SearchFlight",
type: "Post",
data: $('form').serialize() + '&' + $.param({
'TokenId': $("#pageInitCounter").val()
}, true),
success: function(data) {
var result = JSON.parse(data);
$('#responsestatus').text(result.Response.ResponseStatus);
});
Use Json datatype..i wrote a sample here..
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
$(".loadingPnl").removeClass('hdn');
var siteurlA = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
var callUrl = siteurlA + "/_layouts/15/SynchronyFinancial.Intranet/CreateMySite.aspx/SaveAvailableFavoriteItem";
var linkName = $('.txtLinkName').val();
linkName = linkName.replace("'","\'");
$.ajax({
type: "POST",
url: callUrl,
data: "{'linkName': '" + linkName + "', 'webSiteUrl':'" + $('.txtWebAddress').val() + "','iconId':'" + $(".ddlIcons").val() + "'}",
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
return true;
}
The problem is you're building JSON yourself as the request parameters. Moreover, you're building invalid JSON (JSON property names are always with double quotes (")).
Instead, pass an object and let jQuery take care of how to send it - if you pass that instead of a string the server can figure it out. If you really want to do it yourself you can also pass an object to JSON.stringify.
var payload = {
linkName: linkName,
webSiteUrl: $('.txtWebAddress').val(),
iconId: $(".ddlIcons").val()
};
$.ajax({
type: "POST",
url: callUrl,
data: JSON.stringify(payload), // or just payload
contentType: "application/json; charset=utf-8",
processData: false, // if you just pass payload, remove this
dataType: "json"
// you had two `return`s here, but they wouldn't work, make sure
// you understand why
// http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call
});
You can send a JSON instead. Or use JSON.stringify if you want String.
{
'linkName' : linkName,
'webSiteUrl' : $('.txtWebAddress').val(),
'iconId' : $(".ddlIcons").val()
}
Don't create JSON string by yourself AND don't use JSON.stringify().
Problem with creating JSON string yourself is to escape string properly for JavaScript (which could be tricky). see Special Characters
Problem with JSON.stringify is that I found it somehow slower than XMLHttpRequest which is strange because I thought it is using JSON.stringify behind curtains.
XMLHttpRequest is handling this for you. If you just pass your object as a data and XMLHttRequest will do the trick.
$.ajax({
type: "POST",
url: callUrl,
data: {'linkName': linkName,
'webSiteUrl': $('.txtWebAddress').val(),
'iconId': $(".ddlIcons").val()
},
contentType: "application/json; charset=utf-8",
processData: false,
dataType: "json",
success: function (response) {
return true;
},
error: function (response) {
return true;
}
});
I have a problem here and no idea how to solve it...
I have a json file like this:
{"data":[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]}
But I need this format:
[{"kw":"48","val":"10","val2":"05"},{"kw":"49","val":"04","val2":"05"}]
In javascript/jQuery I make an ajax request and get the json back:
$.ajax({
type : "POST",
cache : "false", // DEBUG
url : weburl,
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(data) {
// Strip data?
}
});
Does anyone know how to do this?
Thanks!
success : function (data) {
var array = data ? data.data : null;
// now perform the required operations with array variable.
}
This will return just the array, not wrapped in a object.
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
var arrayYouWant = data.data; // http://thedailywtf.com/Articles/Data-Data-data-Data.aspx
}
});
Why do you need to strip it, you just reference it
success : function(data) {
var myArrayofObjects = data.data;
}
In order to really understand read about the Member operators in Javascript, particularly the dot notation. JSON is a subset of Javascript and the JSON object is a Javascript object in the end.
Not sure what you mean by archive. Do you mean simply access the array that is associated with the data property?
The array is associated to the 'data' property in your JSON string. I would maybe change the name of the data argument passed into the success function.
Try this:
$.ajax({
type: "POST",
cache: "false", // DEBUG
url: weburl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(resp) {
var yourArray = resp.data;
console.log(yourArray);
}
});
I have looked for a solution , but nothing that fits my needs was found on the site, so here goes:
I have a Controller that returns a Json:
return Json(new { Item = searchModule});
searchModule is a list of Profiles:
{ "Item":[{"ProfileID":4854,"NickName":"Johnny","users":null,"FirstName":"John","LastName":"Doe"}]}
In JavaScript we have:
$.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data.Item)
}
})
That returns an object. How can I obtain: Firstname,LastName and NickName ???
Additional answer: If I write the code like below:
var request = $.ajax({
type: "POST",
url: action/controller,
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
}
}).responseText
var obj = json.Parse(request)
, request is null.
since they're objects structured according to the JSON, you should be able to just access the properties like so: data.Item[0].Firstname. You may or may not need to use jQuery.parseJSON to get to this step - calling that is trivial.