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;
});
});
Related
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
Please look at this code on https://jsfiddle.net/safron6/9g98j68g/embedded/result/
I am trying to get the calculated result from the list of APIS and JSON code that is generated to show the precipIntensity. At the end of the code there is an alert and the code works in firebug but nothing is showing up. What may be the reason why the alert does not pop up?
var listAPIs = "";
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.getJSON(darkForecastAPI, {
tags: "WxAPI[" + i + "]", //Is this tag the name of each JSON page? I tried to index it incase this is how to refer to the JSON formatted code from the APIs.
tagmode: "any",
format: "json"
}, function(result) {
// Process the result object
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain")
{
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
});
totalPrecipSinceDate did not declared.
I can't access your hosted data source.
Replacing your current $.getJSON call with an $.ajax call should work:
$.each(threeDayAPITimes, function(i, time) {
var darkForecastAPI= "https://api.forecast.io/forecast/" + currentAPIKey + "/" + locations + "," + time +"?callback=?";
$.ajax({
type: 'GET',
url: darkForecastAPI,
async: false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
var eachPrecipSum = 0;
if(result.currently.precipIntensity >=0 && result.currently.precipType == "rain") {
$.each(result, function() {
eachPrecipSum += (result.currently.precipIntensity);
totalPrecipSinceDate += eachPrecipSum ; ///Write mean precip
alert(eachPrecipSum );
$("body").append("p").text(eachPrecipSum)
});
}
},
error: function(){
alert('failure');
}
});
});
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 have web methods that are called via AJAX in a .Net 4.0 web app. In many cases, the AJAX calls are made repeatedly in a for loop. My problem is, the information the web method is syncing to my server is time stamped and therefore must be synced in the order in which I am sending it to AJAX. Unfortunately, it seems whatever finishes first, simply finishes first and the time stamps are all out of order. I need to basically queue up my AJAX requests so that they execute in order rather than Asynchronously, which I know is the A in AJAX so this might be a totally dumb question.
How do I force the order of execution for AJAX calls done in a for loop?
Edit: Some code
for (var i = 0; i < itemCnt - 1; i++) {
try {
key = items[i];
item = localStorage.getItem(key);
vals = item.split(",");
type = getType(key);
if (type == "Status") {
var Call = key.substring(7, 17);
var OldStat = vals[0];
var NewStat = vals[1];
var Date1 = vals[2];
var Time1 = vals[3];
var miles = vals[4];
try {
stat(Call, OldStat, NewStat, Date1, Time1, miles, key);
}
catch (e) {
alert("Status " + e);
return;
}
}
else if (type == "Notes") {
var Call = key.substring(6, 16);
var Notes = item;
try {
addNotes(Call, Notes);
}
catch (e) {
alert("Notes " + e);
return;
}
}
else if (key == "StartNCTime" || key == "EndNCTime") {
var TechID = vals[0];
var Date = vals[1];
var Time = vals[2];
var Activity = vals[3];
var Location = vals[4];
var Type = vals[5];
try {
logTime(TechID, Date, Time, Activity, Location, Type,
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
}
catch (e) {
alert(key + ' ' + e);
return;
}
}
function stat(Call, OldStat, NewStat, Date1, Time1, miles, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/update_Stat",
data: '{ CallNumber:"' + Call + '", OldStat:"' + OldStat + '", NewStat:"' + NewStat + '", Date1:"' + Date1 + '", Time1:"' + Time1 + '", Miles: "' + miles + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Update Stat: " + err.Message);
location = location;
}
});
}
function logTime(TechID, Date, Time, Activity, Location, Type, key) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/nonCallTime",
data: '{ TechID:"' + TechID + '", Date1:"' + Date + '", Time1:"' + Time + '", Activity:"' + Activity + '", Location:"' + Location + '", Type: "' + Type + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Non Call Time: " + err.Message);
location = location;
}
});
}
function addNotes(Call, Notes) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Service.asmx/addNote",
data: '{ Call:"' + Call + '", Notes:"' + Notes + '"}',
success: function (data) { },
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert("Sync Notes: " + err.Message);
location = location;
}
});
}
You have to use callbacks.
function ajax1(){
//..some code
//on ajax success:
ajax2();
}
//etcetera...
Or might I suggest using a javascript library like jQuery to synchronize your ajax requests for you.
set the third parameter in xmlhttp object's open method to false to make it synchronous.
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
A general pattern for making actions serial would be such:
function doAjax(data, cb) {
...
// when ready call cb
}
(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
var xhr = doAjax(data, next);
})(function (next) {
doAjax(data);
});
Doing so in a for loop would require recursion.
(function next() {
if ( i < n ) {
doAjax(data[i++], next);
}
})();
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.