I have the following code. whenever i change the value in the array - data[0] to say data[1] the value changes. i have about 4 items stored in the data array.
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://<mywebsite>/user/id/1",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("Success");
},
error: function() {
alert('Failed!');
},
}).then(function(data) {
var result = data [1];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
});
});
I want to display all the data in the array. how do i do that? I have tried doing it this way but it didnt work . i have tried other ways too , but still.
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://<mywebsite>/user/id/1",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("Success");
},
error: function() {
alert('Failed!');
},
}).then(function(data) {
var result = data [1];
console.log(result);
for (i = 0; i < result.length; i++) {
$('.ch-name').append(result[i].ch_name);
$('.ch-logo').append(result[i].ch_logo);
$('.ch-desc').append(result[i].ch_desc);
$('.ch-genre').append(result[i].ch_genre);
}
});
});
the description is a little unclear but i think i see what youre trying to do.
it should be accomplished by changing that for loop to loop over data, not results
for (i = 0; i < data.length; i++) {
$('.ch-name').append(data[i].ch_name);
$('.ch-logo').append(data[i].ch_logo);
$('.ch-desc').append(data[i].ch_desc);
$('.ch-genre').append(data[i].ch_genre);
}
if this is not what youre trying to do, please post what the structure of data looks like, and how you want to display that
Related
I'm having an error when using several ajax calls, I put this in an array and I need capture when finish all.
My code is this:
var userId=[1,2,3];
var ajaxR = [];
for (var us in userId) {
var usId = userId[us];
ajaxR.push($.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "myurl",
data: { id: usId }
}));
}
$.when.apply($, ajaxR).always(function (e) {
//Here I have the error but arguments it's ok
var objects = arguments;
});
When I debbug this code I have an error in $.when function:
Uncaught TypeError: Cannot read property '0' of undefined
Update:
My complete function is it:
function UserFromWS(userId) {
var users = [];
var ajaxR = [];
for (var us in userId) {
var usId = userId[us];
ajaxR.push($.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "url",
data: { id: usId }
}));
}
$.when.apply($, ajaxR).always(function (e) {
var obj = arguments;
return obj;
});
// return users;
}
The error disapear if I put return users; in end of function. But it finish returning users array empty, before return obj. I need call the function in this way:
var allUsers = UserFromWS ([1,2,3]);
The function should return obj in $.when promise.
Fist thing to check is that "userId" is being passed as an array. Then the for loop need to be modified to correctly loop the array (Why is using "for...in" with array iteration a bad idea?).
Also the function needs to return a promise:
function UserFromWS(userId) {
var users = [];
var ajaxR = [];
for (var i = 0; i< userId.length; i++) {
var usId = userId[i];
ajaxR.push($.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "url",
data: { id: usId }
}));
}
return $.when.apply($, ajaxR).done(function (e) {
var obj = arguments;
return obj;
});
// return users;
}
Also you will need to wait for the result of this function:
var users = [10];
UserFromWS(users).then(function(result) { /* do stuff now */ });
Why do you save the ajax call to array, JQuery can recongnize the request by himself, and you can call the same $.ajax() many times without error.
Example:
$.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "url",
data: { id: usId }
}).done(function (e) {
var obj = arguments;
return obj;
});
Or if you want to continue with your system, know that when use promise
see https://api.jquery.com/jquery.when/
I have an AJAX call I am using to grab some data from a DB.
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
data: {
dataset: 'Users'
},
async: false,
timeout: 5000,
cache: false,
success: function(data) {
var result = data.result;
console.log(result);
}
});
I can see from the console that the data is successfully retrieved, except that I can't print this data to a DOM ID element. Even if I do a document.write(result); the text that is displayed on the screen is
[object Object],[object Object],[object Object]
Again, the data is retrieved successfully because I can see it, I just can't get at it.
I know this is probably a silly question and it'll end up being something I can learn in a 101 class, but can someone explain what is happening here and how I can get at my data?
In your posted screenshot it seems like you are getting the result from the AJAX call as a form of Array. So, to access its data you should probably have to do something like... document.write(result[0].user_name) or
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
data: {
dataset: 'Users'
},
async: true,
cache: false,
success: function(data) {
var result = data.result;
for (var i = 0; i < result.length; i++) {
document.write(result[i].user_name);
}
console.log(result);
}
});
Hope this helps.
Your Code Is Fine but on the success it is returning array of object then you have to modify your code like this
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
contentType:'application/json;charset=utf-8',
data: {
dataset: 'Users'
},
async: false,
timeout: 5000,
cache: false,
success: function(data) {
alert(data[0].user_name);
console.log(result);
}
});
success: function(data) {
$.each(data,function(index,obj)
{
console.log('object ' + index);
$.each(obj,function(key,value)
{
console.log(key + ':' + value);
});
});
}
You are getting an array of objects from server. You cannot directly print that. You need to iterate through this array for printing the values. For this you can use $.each jquery function to first iterate through the array of object and then again to iterate through all the key-value pairs of each object. You can read about $.each function here
I have an ajax response with data extracted from a sql query. It has this structure:
Response
id:"id"
titulo:"title"
url:"url"
What I am trying to do is to find the position within the ajax response where a given unique id is.
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
console.log(response);
console.log(response.indexOf(27188964));
}
});
The second log prints -1, knowing that the number should be at the first position.
EDIT:
I need the position in order to start moving through the array by increasing 'index'
response[index].url
If your response is an array of objects you can use Array.prototype.filter():
$.ajax({
url: 'select.php',
type: 'get',
data: {
"id": id
},
dataType: "json",
beforeSend: function() {},
success: function(response) {
var resultIndex;
var result = response.filter(function(obj, index) {
if (obj.id === '27188964') {
resultIndex = index;
return true;
}
return false;
});
console.log('resultIndex:', resultIndex);
console.log('result:', result);
}
});
I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.
I'm having some problems with JSON.Parse in my code and I cant find the reason of this I have a function which call two ajax functions, one on the start and another on the success function . Its working fine but when I'm try to parse the second one response the code breaks without giving any error and the real mystery is JSON.parse(object); dosent give any problem but when I use a variable to store the result like this var list =JSON.parse(object); my code broke and I dont what is the reason behind this my current code is given below
function getData()
{
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = JSON.parse(response.d);
var temp = 0;
for (var i = 0; i < result.length; i++) {
if (result[i].data > 1) {
var subList = JSON.parsegetFullData (result[i].id));
}
}
});
}
function getFullData (id) {
var sublist;
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData2",
data: JSON.stringify({ id: id }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
return response.d;
}
});
}
any thought will help a lot
When you use $.ajax with dataType:"json", the response is already parsed for you. And there doesn't seem to be a reason to try to parse response.d.
Simply use
$.ajax({
type: "POST",
url: "MyPage.aspx/GetData",
data: JSON.stringify({ data: data})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (results) {
for (var i = 0; i < results.length; i++) {
console.log(results[i].id, results[i].LastName);