I am updating some div as follows:
for(var i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
The value of i does not work inside the ajax call. I am trying to pass the value of i so that it can attach the element to the proper div. Can someone help me out?
Ok. This works but would really love if someone can explain it! I broke my head over this so posting it here just in case someone needs it.
for(i = 0; i < data.length; i++)
fetchItem(i)
fetchItem = function(i) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
Have you tried making i a global variable:
Change:
for(var i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
To this:
for(i = 0; i < data.length; i++) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
Also I agree with Nick. You can do the looping first then send the array (JSON) serverside to be processed. This way the application will be much more responsive.
I think your problem has to do with scope.
You should wrap the what's in the for loop into a function
for(var i = 0; i < data.length; i++) {
doAjax(i);
}
function doAjax(i) {
var query = base_url + data[i];
$.ajax({
url: query,
type: 'GET',
dataType: 'jsonp',
timeout: 2000,
error: function() { self.html("Network Error"); },
success: function(json) {
$("#li" + i).html("<img src='" + json.result.list[0].url + "' />")
}
});
}
The i value for the closure function of success is correctly bound only when it is not in a for loop.
That should work. Good luck.
Related
I am using jQuery for making management panels. Some of them are simple and some of them are more interactive. I am getting someone's name from an input type text that has id name. Which is the right way to do this?
1 - ) $("#name").val();
2 - ) let name = $("#name");
console.log(name.val());
My another question is
if you put all city list in select . These cities have also districts related to them and they are in also select. JQuery ajax works async and preferred way is also using async. If I prepare a create page for example, for adding company , I need to get first cities then districts like this
function getDistricts(cityId) {
$.ajax({
url: "/Administrator/General/GetDistricts?cityId=" + cityId,
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyDistrict.empty();
for (var i = 0; i < response.data.length; i++) {
companyDistrict.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
function getGetCities() {
$.ajax({
url: "/Administrator/General/GetCities",
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyCity.append('<option value="' + '0' + '">' + 'İl seçiniz.' + '</option>');
for (var i = 0; i < response.data.length; i++) {
companyCity.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
and on update page for company. My code is like that
function getGetCities(cityId,districtId) {
$.ajax({
url: "/Administrator/General/GetCities",
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyCity.append('<option value="' + '0' + '">' + 'İl seçiniz.' + '</option>');
for (var i = 0; i < response.data.length; i++) {
companyCity.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
companyCity.val(cityId);
getDistricts(cityId, districtId);
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
function getDistricts(cityId, districtId) {
$.ajax({
url: "/Administrator/General/GetDistricts?cityId=" + cityId,
type: "GET",
contentType: "application/json; charset=utf-8;",
cache: false,
async: true,
success: function (response) {
if (response.success === true) {
companyDistrict.empty();
for (var i = 0; i < response.data.length; i++) {
companyDistrict.append('<option value="' + response.data[i].id + '">' + response.data[i].name + '</option>');
}
companyDistrict.val(districtId);
}
else {
fireAlert(response.success, response.message);
}
},
error: function (error) {
fireAlert(false, error.statusText);
}
});
}
I am just wondering that if I use the right way. Is this way right and how can i use jquery and javascript with asp.net core effectively ?
I am trying to get share count of pininterest and below code is working well
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.getJSON(PIUrl, function (data) {
pi_like_count = data.count;
alert(pi_like_count +' pininterest');
});
but when I am trying to put below code issue is coming as
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
method: 'GET',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
},
error: function (data) {
alert('error' + data.count + ' pininterest');
console.log(data);
},
async: false
});
Console.log error as
promise: function promise()
readyState: 4
responseText: "{\"error\":\"Invalid callback, use only letters, numbers, square brackets, underscores, and periods.\"}"
This issue is coming when I am using $.ajax, I had tried same to get facebook share count and is working well but pininterest is not working
more explaination
function GetScores(url) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?'
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest');
} ,
complete: function (jqXHR, data) {
pi_like_count = data.count;
alert(pi_like_count + ' pininterest complete');
},
error: function (req, status, error) {
alert('error');
},
async: false
});
//Fetch counters from Facebook
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
alert(fb_share_count+' facebook');
},
async: false
});
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
return totalshare;
}
Here Facebook count and total share count is get then after the pinterest count alert is showing i.e. when this function is calling second time then after pinterest is giving old count.
Try it:
function GetScores(url, onCountTotal) {
var FBUrl, TWUrl, LNUrl, GLUrl, PIUrl;
var url1 = "";
url1 = encodeURIComponent(url1 || url);
//Fetch counters from PInterest
var pi_like_count = 0;
PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
$.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl,
success: function (data) {
pi_like_count = data.count;
var fb_share_count = 0;
FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
dataType: 'json',
url: FBUrl,
success: function (data) {
fb_share_count = data.share.share_count;
var totalshare = parseInt(fb_share_count) + parseInt(pi_like_count);
onCountTotal(totalshare);
//alert(fb_share_count + ' facebook');
},
error: function (data) {
onCountTotal(-1);
},
async: true
});
},
error: function (req, status, error) {
onCountTotal(-1);
},
async: true
});
}
//EXAMPLE HERE CALL FUNCTION WITH CALLBACK
GetScores("http://www.google.com", function (count) {
alert("Count = " + count);
});
Here's what you could try using a CallBack :
var result = 0;
function handleData(data) {
result+=data.count;
}
function GetScores(url) {
var url1 = encodeURIComponent(url1 || url);
getFb(url1).done(handleData);
getPi(url1).done(handleData);
return result;
}
function getPi(url1){
var PIUrl = "https://api.pinterest.com/v1/urls/count.json?url=" + url1 + "&format=jsonp" + '&callback=?';
return $.ajax({
type: 'GET',
dataType: 'json',
url: PIUrl
});
}
function getFb(url1){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
return $.ajax({
type: 'GET',
url: FBUrl
});
}
You can adapt for every platform you need the shares from, just add another function in GetScores and handle properly the returned json
You could also do something like :
function getFb(url1, callback){
var FBUrl = "https://graph.facebook.com/?id=" + url1 + "&format=json";
$.ajax({
type: 'GET',
url: FBUrl,
success: callback
});
}
getFb(function(data){
result+=data.count;
});
Try to adapt your code depending on the result of your alerts
here is my example
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
now i realized that the call function doesn't fire at all....i read other post here and they say that it happens when JSON is not in valid format but here i am getting JSON from Google API so i hope its in valid format.... JSON is here
http://maps.googleapis.com/maps/api/geocode/json?latlng=27.88,78.08&sensor=false
can you please give your comments on this? or may be i am making some mistakes
Maybe try a full ajax call:
$.ajax({
url: "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false",
data: {},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
console.log(element);
};
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
can you add it to
$(document).ready(function(){
});
for example:
$(document).ready(function () {
var url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + area.getCenter().lat + "," + area.getCenter().lng + "&sensor=false";
$.getJSON(url, function (data) {
alert("inside json");
//console.log(data);
$.each(data.results[0], function (i, inside) {
console.log(i);
});
//var addr = data.results[0].geometry.location.lat;
});
});
I Have 3 nested $.ajax calls using JSONP, the first $.ajax calls work in the function but the third fails to execute the call back giving me this error: Uncaught TypeError: Property 'insertFilmData' of object [object Object] is not a function
CODE:
function searchFilms(film, settings) {
if (film === '') {
console.log("enter a movie");
} else {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/configuration?api_key=XXX',
async: false,
jsonpCallback: 'getSearchResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.images) {
settings.imageData = json.images;
getSearchResults(json, settings);
}
}
});
function getSearchResults(data, settings) {
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/search/movie?api_key=XXX&query=' + film,
async: false,
jsonpCallback: 'deliverResults',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json.total_results !== 0) {
deliverResults(json, settings);
}
}
});
function deliverResults(data, settings) {
var results = data.results;
var html = "<ul id='film-search-results' data-role='listview' data-inset='true'>";
for (var i = 0; i < results.length; i++) {
var result = results[i];
var filmId = result.id;
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
}
});
function insertFilmData(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
}
html = html + "</ul>";
console.log(html);
$('#content-add-title').html(html);
$('#film-search-results').trigger("create");
}
}
}
}
I'm pretty new to using JSONP for cross domain calls so i'm not sure what's going wrong seeing as the first two call backs fire and it's only the last one that doesn't. any help or direction would be greatly appreciated. Thanks
It's looking for a method called insertFilmData and can't find it. Presumably it will work if you define the function to be a method of the object which is a parameter to the ajax call, ie:
$.ajax({
type: 'GET',
url: 'http://api.themoviedb.org/3/movie/' + filmId + '?api_key=XXX&append_to_response=' + settings.extras,
async: false,
jsonpCallback: 'insertFilmData',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
if (json) {
settings.html = html;
insertFilmData(json, settings);
}
},
insertFilmData: function(data, settings) {
var poster_base_url = settings.imageData.base_url;
var poster_size = settings.imageData.poster_sizes[0];
var poster_filepath = data.poster_path;
var poster_url = poster_base_url + poster_size + "/" + poster_filepath;
var html = settings.html + "<li><img src='" + poster_url + "' alt='Poster' /><a class='ui-link-inherit'><h3 class='ui-li-heading'>" + data.title + "</h3><p class='ui-li-desc'><strong>" + data.tagline + "</strong></p><p class='ui-li-desc'>" + data.overview + "</p></a></li>";
}
});
Alternatively, you could just keep it as it is now, but change the line jsonpCallback: 'insertFilmData', to jsonpCallback: insertFilmData,. This will mean one of the arguments to the ajax call will be the function itself, not the name of the function. (And if I understand this correctly, it doesn't matter that the function definition is below this line, because it's a named function and it's in scope.)
I am using the following functions to populate the dropmenu menu, my problem is that my click event is not firing ,and i am not able to populate the dynamic dropdown menu.
This is my Jquery function
function testXmlMenu() {
getmenu(function (results) {
$("div[id ^= 'menuItemGroup']").slideUp(500);
$.ajax(
{
type: "POST",
url: "JsonWebService.asmx/GetMenuItems",
data: '{"menuId":"' + results.data.MenuId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (items) {
$(event.target).children().remove();
var html = "<div id='menuItemGroup" + event.data.MenuId + "' style='display:none'>";
for (var j = 0; j < items.length; j++) {
html += "<div id='MenuItems'> <a href='" + items[j].NavigateUrl + "'>" +
items[j].Text + "</a></div>";
}
html += "</div>";
$(event.target).append(html);
$("#menuItemGroup" + event.data.MenuId).slideDown(500);
},
error: function (err) {
alert(err.status + " - " + err.statusText);
}
});
});
}
function getmenu(callback)
{
$.ajax({
type: "POST",
url: "JsonWebService.asmx/GetMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success:
function (results) {
$(results).find("Menu").each(function () {
var Text = $(this).find("Text").text();
var MenuId = $(this).find("MenuId").text();
alert(MenuId);
var dmenu = $("#Menudiv");
dmenu.append("<td><ul>"+Text+"</ul></td>");
$("dmenu.td").click(callback(results));
});
}
});
}
I think your jQuery selector is switched around for your click action.
It should be:
$("td.dmenu").click(callback(results));