accessing variables outside ajax - javascript

I have the following code:
var src, flickrImages = [];
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
// undefined returned here for flickrImages
map.setZoom(13);
map.setCenter(new google.maps.LatLng(xmlLat,xmlLng));
infowindow.setContent('<strong>' + xmlTitle + '</strong><br>' + xmlExcerpt + '<br><br>' + flickrImages.join(''));
infowindow.open(map,this);
I am trying to access flickrImages variable outside the ajax so I am able to put it inside a infowindow for google maps. Unfortunately outside the ajax it returns undefined.
I tried moving the flickr things into the ajax but unfortunately it then loses some of the other information such as xmlTitle and xmlExcerpt.
Any help is much appreciated.
Thanks in advance,
Dave.

The reason why flickrImages is undefined where your comment is, is because the call to $.ajax is asynchronous, which means it does not block until your request completes.
That's why there is a success function that gets "called back" when the underlying HTTP request completes. So, you need to handle your flickrImages variable from your success function, or alternatively, from your success function, pass flickrImages to some other function which does your processing.

The ajax call is asynchronous, so it won't wait around for an answer - it will just go ahead and run the rest of the script. Passing async:false in the settings (see http://api.jquery.com/jQuery.ajax/) should solve your problem, though it will make it a lot slower as the script will have to wait for the ajax call to return.
It would be neater for the rest of the script to be called from the success callback as you tried to do - how is it that xmlTitle and xmlExcerpt are unavailable there?

Define a global variable outside of your ajax call and assign it a value
var myData
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
myData = data
myFunction()
}
});

As said by Karl Agius a "The ajax call is asynchronous". For this you just have to add
async: false,
to your ajax request. Here is you code looks after adding this:
$.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json",
async: false,
statusCode: {
404: function() {
alert('page not found');
}
},
success: function(data) {
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
}
});
But its not a good practice to stop asynchronous in ajax call. But will work for you. Use Ajax callback on success instead (check here).

Here is another option. You create a function that return an ajax call like this.
function flickrImages (){
return $.ajax({
type: "GET",
url: "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bf771e95f2c259056de5c6364c0dbb62&text=" + xmlTitle.replace(' ', '%20') + "&safe_search=1&per_page=5&format=json",
dataType: "json"
});
}
Then on your code somewhere, you call this function an retrieve the success or in my case the .done() function like this
var result= flickrImages ();
flickrImages = [];
result.done(function(data){
$.each(data.photos.photo, function(i,item){
src = "http://farm"+ item.farm +".static.flickr.com/" + item.server + "/" + item.id + "_" + item.secret + "_s.jpg";
flickrImages[i] = '<img src="' + src + '">';
});
});
console.log (flickrImages);

Related

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

How to get json data from url with Cordova?

I started to develop an app with Cordova for android and I'm now searching around google for a solution(Whitelist) to get the JSON data from the URL.But I cannot find a simple tutorial. Most of the tutorials I found are not so beginner friendly. I'm thinking about trying to get the JSON data with pure javascript, but I think it's not a good idea. Are there some simple tips or tutorial that can solve this problem? I love to hear from you!
Like this? Assuming that hello.php returns your JSON data.
$.ajax({
url: "yourwebsite.com/hello.php",
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getdata(arr);
},
error: function () {
validationMsg();
}
});
function _getdata(arr){
//your JSON resuls are now in arr. Do what you need with the array.
}
This example could be very helpful.
You should try ajax calls in order to fetch data from the server, jQuery makes it very easy. Here is the function used in the example that loads the data from the server :
function getEmployeeList() {
$('#busy').show();
$.getJSON(serviceURL + 'getemployees.php', function(data) {
$('#busy').hide();
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '" class="list-icon"/>' +
'<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
'<p class="line2">' + employee.title + '</p>' +
'<span class="bubble">' + employee.reportCount + '</span></a></li>');
});
setTimeout(function(){
scroll.refresh();
});
});
}
I hope it help.
fetch('/echo/json', {
method: 'get'
}).then((JSONresponse) => {
// do whatever you want with your
// JSONresponse here
})

Waiting Until Ajax Calls in $.each loop Finish Before Executing Function [duplicate]

This question already has answers here:
jQuery callback for multiple ajax calls
(14 answers)
Closed 5 years ago.
I would like to call a function only after all of the ajax calls I am making in the $.each loop complete. What is the best way to achieve this?
function recaculateSeatingChartSeatIds()
{
var table_id = $(".seatingChartTable").attr("id");
var seat_id = 0;
$(".nameContainer").find("p").each(function()
{
seat_id++;
var participant_id = $(this).attr("data-part-id");
$.ajax({
method: 'POST',
datatype: 'jsonp',
url: base_url + 'users/assignToTableAndSeat/' + event_id + "/" + participant_id + "/" + table_id + "/" + seat_id
}).done(function () {
console.log("Participant Added");
}).fail(function (xhr, text, error) {
console.log(error);
});
});
funcToCallAfterAllComplete();
}
what if you set a flag on each p after the ajax call and then always call a function that checks to see if all p's have that flag
$(".nameContainer").find("p").each(function()
{
seat_id++;
var participant_id = $(this).attr("data-part-id");
$.ajax({
method: 'POST',
datatype: 'jsonp',
url: base_url + 'users/assignToTableAndSeat/' + event_id + "/" + participant_id + "/" + table_id + "/" + seat_id
}).done(function () {
console.log("Participant Added");
$("p[data-part-id='"+ participant_id +"']").data('completed', 'completed');
}).fail(function (xhr, text, error) {
console.log(error);
});
});
tryFuncToCallAfterAllComplete(){
$(".nameContainer").find("p").each(function()
{
if($(this).data('complete') != 'completed'){
return;
}
}
funcToCallAfterAllComplete();
}
funcToCallAfterAllComplete();
}
this would allow you to still call them all at the same time, and funcToCallAfterAllComplete would only run when all ajax calls have finished

Using/looping response from Ajax call from another function

I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.

how to print or echo JSON.stringify data i php

i am trying to fetch google contact list using contact api. i got the result and its showing in chrome and firefox console. i want to print the data in php. on the same page
<script type="text/javascript">
function auth() {
var config = {
'client_id': 'xxxxxxxxxxxxxxxxxxxxx',
'scope': 'https://www.google.com/m8/feeds'
};
gapi.auth.authorize(config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
//alert(JSON.stringify(data));
// display all your data in console
console.log(JSON.stringify(data));
}
});
}
</script>
i tried ajax but not worked. is there any best way to do it. JSON.stringify(data) is a array
You have nothing to do with PHP here. You are receiving a callback from $.ajax and the only way to show that data on ur page is to use JavaScript/jQuery.
See example below on how to parse $.ajax callback and .append() the data to some element on ur page:
<div id="contacts"></div>
function fetch(token) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json",
dataType: "jsonp",
success:function(data) {
$.each(data.feed.entry,function(){
$('#contacts').append('<div>Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t + '</div>');
console.log('Name: ' + this.title.$t + ' Phone: ' + this.gd$phoneNumber[0].$t);
});
}
});
}
Note: if You need to parse ur data with PHP then You have to use curl.

Categories