How to read data from json format using jquery. below is what i have tried, but unfortualtly i couldn't able to read exact data which i want.
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (data != null) {
$.each(data, function (i, item) {
alert(data[0]);
alert(data[0].DistrictCode)
alert(item);
alert(item[0]);
alert(item.DistrictCode);
$('#tblDistricts > tbody').append('<tr><td>'+item.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
})
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});'
In alert box , I'm getting 'undefined' or '[object] [Object] only, I could not able to read exact data. I got stuck here.
Edit:
Web api will return the data as List objects.
[HttpGet]
[Route("GetDistrict/", Name = "GetDistrictList")]
public List<DistrictModels> GetDistrictList()
{
BAL_District oBAL_District = new BAL_District();
return oBAL_District.GetDistrictList();
}
Use var Data = $.parseJSON(response);
Example
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
JSON.parse turns a string of JSON text into a Javascript object.
How to access JSON object
FYI, as of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I think you wish to call this function -
http://api.jquery.com/jquery.parsejson/
if you are getting [object,object] it means you have already fetched the Json Object. And if you need some clarifications, please share the expected Json you want.Thanks
Use JSON.stringify(object). It is super safe way to print out.
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (!!data) {
// '!data' means data variable is not available and '!!data' returns true:boolean if variable is valid
//idx is 'index', I made the code as a loop. It will not work if array is empty.
//It is good way to avoid error
for(var idx in data){
if(idx == 0) {
//JSON.stringify makes object type to string type. It is safe to use since it is a native javascript function
alert(JSON.stringify(data[idx]);
//You can access member by 'data[idx].memberName'
//DOM adding code can be here
}
}
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json' parameter.
You should not use data variable in $.each(). Then you could use the $.each() function to loop through the data:
$.ajax({
url: '#Url.HttpRouteUrl("GetDistrictList", new { })',
type: 'GET',
datatype: "json",
success: function (data, txtStatus, xhr) {
console.log(data);
if (data != null) {
$.each(data, function (index, element) {
alert(element);
alert(element[0]);
alert(element.DistrictCode);
$('#tblDistricts > tbody').append('<tr><td>'+element.DistrictCode+'</td><td>test</td><td>test</td><td>test</td><td>test</td><td>test</td></tr>');
});
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("error in GetDistrictList : " + errorThrown);
}
});'
or use the $.getJSON method:
For example:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
Note: As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON objects, use the native JSON.parse method instead.
Related
I have simple AJAX call.
It looks like this:
myApp.onPageInit('about', function (page) {
search_term = $$("#search_term").val();
const key = "xxxx-xxxx";
const nick = "https://api.xxx.xxx/" + search_term + "?api_key=" + key;
$$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
//myApp.showPreloader('Please wait...');
},
success: function(data) {
//myApp.hidePreloader();
console.log(data);
console.log(data['summonerLevel']);
},
statusCode: {
404: function() {
// myApp.alert('Account does not exist.', 'ERROR');
}
},
error: function(data) {
myApp.alert('Account does not exist.', 'ERROR');
// ak je ovaj error, netko je dirao putanju - fajl
},
});
})
When I'm trying to get properties from data object, every time it says undefined.
Console log: {"id":"xxxx","accountId":"xxxx","puuid":"xxxx","name":"Data","profileIconId":3015,"revisionDate":1546082318000,"summonerLevel":37}
Second console log: undefined
I tried dot notation and bracket notation, but everytime same status(undefined).
Like this:
console.log(data['summonerLevel']);
console.log(data.summonerLevel);
Any suggestion for this problem?
use JSON.Parse() method and try taking the value with object.attributename
$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
},
success: function(data) {
var data=JSON.Parse(data);
console.log(data.summonerLevel);
console.log(data.accountId);
},
statusCode: {
404: function() {
}
},
error: function(data) {
},
});
I have to get values from two different URLs and then to merge it. I know it would much better if i'll get all of the data in one URL, but that's how i've got and i need to work with it.
I want to print out the value of a_value, but it's been printed out while b hasn't returned his value. I've read some articles of how to make the functions synchronous but still don't know how to implement it into my code, and don't know what is the best solution for my case. I'm pretty new with JavaScript and still need some help and guiding.
function any_function() {
$.ajax(
{
url : '/url1',
type: "GET",
success:function(data, textStatus, jqXHR)
{
$("#print").html(a(data));
}
});
}
function a(data){
x = 'any value' //`do something with data and insert to this variable`
a_value = x + b(`some id that extracted from data`)
return a_value
}
function b(id){
$.ajax({
url: '/url2',
type: 'GET',
success: function (data, textStatus, jqXHR) {
b_value = c(data, id)
}
});
return b_value
}
function c(data, id){
//do something with `data` and return the value
return c_value
}
function f() {
var request1 = $.ajax({
url : '/url1',
type: 'GET'
});
var request2 = $.ajax({
url: '/url2',
type: 'GET'
});
$.when(request1, request2).done(function(result1, result2){
data1 = result1[0]
data2 = result2[0]
// r1 and r2 are arrays [ data, statusText, jqXHR ]
// Do stuff here with data1 and data2
// If you want to return use a callback or a promise
})
}
This can be done in a synchronous-looking fashion with promises:
$.get(url1)
.then(function(data1){
return $.get(url2)
})
.then(function(data2){
return $.get(url3);
})
.then(function(data3){
// All done
});
You just need to make the second call in the success handler of the first one:
function any_function() {
$.ajax({
url : '/url1',
type: "GET",
success:function(data, textStatus, jqXHR) {
$("#print").html(a(data));
b("someId");
}
});
}
function a(data){
x = 'any value' //`do something with data and insert to this variable`
a_value = x + b(`some id that extracted from data`)
return a_value;
}
function b(id){
$.ajax({
url: '/url2',
type: 'GET',
success: function (data, textStatus, jqXHR) {
b_value = c(data, id);
return b_value;
}
});
}
function c(data, id){
//do something with `data` and return the value
return c_value
}
My page is receiving JSON encoded data from a php script. Using my browsers dev network tool I can see the data is as follows:
{"state":200,"message":null,"result":"..\/0images\/listimg\/orig\/54ab4719bf848.jpeg","id":"957"}
I have an input tag on the page called
<input class="avatar-src" name="avatar_src" type="hidden" value="">
Using jquery, I would like to store the value for "id" from the json string in the value attribute of my input tag.
There is a JS script that is already processing the "state", "message" and "result" objects from the json string. If possible I would like to leave that script alone and use a separate one to extract the JSON object "id". How would I do this?
Here is part of the first ajax response that manages "state" "message" and "result"
ajaxUpload: function () {
var url = this.$avatarForm.attr("action"),
data = new FormData(this.$avatarForm[0]),
_this = this;
$.ajax(url, {
type: "post",
data: data,
processData: false,
contentType: false,
beforeSend: function () {
_this.submitStart();
},
success: function (data) {
_this.submitDone(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
_this.submitFail(textStatus || errorThrown);
},
complete: function () {
_this.submitEnd();
}
});
},
syncUpload: function () {
this.$avatarSave.click();
},
submitStart: function () {
},
submitDone: function (data) {
console.log(data);
try {
data = $.parseJSON(data);
} catch (e) {};
if (data && data.state === 200) {
if (data.result) {
this.url = data.result;
if (this.support.datauri || this.uploaded) {
this.uploaded = false;
this.cropDone();
} else {
this.uploaded = true;
this.$avatarSrc.val(this.url);
this.startCropper();
}
this.$avatarInput.val("");
} else if (data.message) {
this.alert(data.message);
}
} else {
this.alert("Failed to response");
}
},
Assuming this is actually JSON, you'd have to parse it first... For instance, say your JSON was linked to a reference (variable):
var myJSON = '{"state":200,"message":null,"result":"..\/0images\/listimg\/orig\/54ab4719bf848.jpeg","id":"957"}';
From here, you'd have to parse the JSON into a JavaScript object with JSON.parse:
var myJSON = JSON.parse(myJSON);
Then, from here you can select the values as a JavaScript object.
$(".avatar-src").val(myJSON.id);
It would be best to start by giving your input tag an ID attribute AS WELL AS a name attribute so it can be uniquely referenced.
So whatever var you populate with the JSON object (let's just call it: var jSn):
<input id="avatar_src" name="avatar_src" class="avatar-src" type="hidden" value="">
<script>
$('#avatar_src').val(jSn.id);
</script>
I need to add autocomplete to an input textbox. The data needs to be fetched from SharePoint using AJAX / REST.
This what I've done so far:
JS
var myData = [];
var requestHeaders = {
"accept": "application/json;odata=verbose"
}
$.ajax({
url: "https://my-URL/sites/RMA-GFPLC/_api/web/lists/GetByTitle('AD_DB')/items? $select=Title,Regional_x0020_Office,Commodity,Commodity_x0020_Year,StateLookUp/Title&$expand=StateLookUp",
type: 'GET',
dataType: 'json',
async: false,
headers: requestHeaders,
success: function (data) {
$.each(data.d.results, function (i, result) {
myData.push(result.Title);
});
myDataSource(myData);
},
error: function ajaxError(response) {
alert(response.status + ' ' + response.statusText);
}
});
function myDataSource(myData){
$('#myAutoCompleteSearch').autocomplete({
source: myData,
minLength: 3
});
}
So far my code is not working, and I'm getting "Uncaught TypeError: Cannot read property 'label' of null " error in my console. I;m wonder what am I doing wrong here? Thanks!
This error occurs when a source for Autocomplete function contains an element(s) with a null value.
Solution
Add the condition for checking if value is not null:
$.each(data.d.results, function (i, result) {
if(result.Title) {
myData.push(result.Title);
}
});
Jast insert your code in
$(document).ready(function () {
//your code here
}
Below is my ajax call
$(document).ready(function() {
$("#blog").focusout(function() {
alert('Focus out event call');
alert('hello');
$.ajax({
url: '/homes',
method: 'POST',
data: 'blog=' + $('#blog').val(),
success: function(result) {
$.each(result, function(key, val) {
$("#result").append('<div><label>' + val.description + '</label></div>');
});
},
error: function() {
alert('failure.');
}
});
});
});
I am getting 'TypeError: invalid 'in' operand obj ' error in my console
In advance thank you
Mention a dataType attribute in your ajax call.It consider text by default.That's why not able to iterate on result
dataType:'json'
Because your result should be array or json
the 'result' in success function should be an array
Shouldn't data be an object?
data: {
blog: $('#blog').val()
},