How can I do API Call after different APi Call is finished? - javascript

Go to http://starodaj.eu/apitest/index2.html to see my code
Click "Show Availability". It should populate inputs. I have a problme (probably with asynchronous) so I can't populate everything by 1 click. When I click 'ShowAvailability' more times - everything work fine. How can I fix that?
function callAPI(yourAPIKey){
var enquiry = "http://api.roomex.com/api/hotel?apiKey=" + yourAPIKey;
//alert(enquiry);
$.ajax({
url: enquiry,
type: 'GET',
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpCallback2",
complete: function (response, responseCode) {
},
success: function (json) {
$.each(json.Contracts, function (index, contract) {
// alert("Count before increament : " + Count);
// alert(contract.ContractCode);
ContractsArray[Count] = contract.ContractCode;
// alert("Count after increament : " + Count);
// alert("ContractsArray[Count]: " + ContractsArray[Count]);
Count++;
});
for(var i = 0; i < Count; i++){
//alert("ContractsArray[" + i + "]: " + ContractsArray[i]);
getAvailability(yourAPIKey, ContractsArray[i], startDate, endDate);
getRates(yourAPIKey, ContractsArray[i], startDate, endDate);
//alert("Finish of ContractsArray[" + i + "]: " + ContractsArray[i]);
}
}
});
}

Your script produces errors with these lines
jsonpCallback: "jsonpCallback3",
jsonpCallback: "jsonpCallback",
jsonpCallback: "jsonpCallback2",
when I removed them it just fills the entire table

Related

Nested ajax call with an value from the first into the seconds Ajax call's url

I want to do live search and I need to use an id value from the first ajax call inside the second one.
I get the info when I type fast into the search, but if I search again or continue, I get this and the outer ajax wont be called again.
GET
http://api.themoviedb.org/3/movie/366924/videos?api_key=KEYHERE…9a6ebe&callback=jQuery1102017797202615180896_1472038138300&_=1472038138301
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val(),
movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
}
})
.then(function() {
$.each(resultArray,
function (index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function () {
$("#myList").append("stuffs");
}
});
});
});
}
$(this).change();
});
Try This -
$('#movie-search')
.keyup(function() {
var input = $('#movie-search').val();
var movieName = encodeURI(input);
if (input.length > 3) {
$("#myList").empty();
$.ajax({
url: url + searchMode + apiKey + '&query=' + movieName,
dataType: 'jsonp',
success: function(data) {
console.log(data.results);
resultArray = data.results;
$.each(resultArray,
function(index, value) {
console.log(value.id);
var searchVideo = 'movie/' + value.id + '/videos';
$.ajax({
url: url + searchVideo + apiKey,
dataType: 'jsonp',
success: function() {
$("#myList").append("stuffs");
}
});
});
}
});
}
$(this).change();
});

JSON object length is returning a big value instead of expected 750 records

I'm trying to append records to my table which are being loaded from an AJAX request which returns JSON, but if I try to use output.length it returns a big number instead of 750 records. This causes the for loop to be run for 10000 times instead of 750. Why is this?
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
console.log(output.length);
// buildTable(result);
}
});
}
function buildTable(output) {
for (var i = 0; i < output.length; i++) {
$('<tr>').append(
$('<td>').text(output[i].naam),
$('<td>').text(output[i].perc),
$($('<input id="' + output[i].id + '" onclick="editData(this)" type = "button" value = "Edit" />')),
$($('<input id="' + output[i].id + '" onclick="readData(this)" type = "button" value = "Read" />')),
$($('<input id="' + output[i].id + '" onclick="deleteRow(' + output[i].id + ')" type = "button" value = "Delete" />'))
).appendTo('#tableA');
}
}
Check with this probably
function getData() {
$.ajax({
data: {
action: 'getData'
},
url: "api/ajaxcall.php",
type: 'post',
async: false,
dataType: 'html',
success: function(output) {
output = JSON.parse(output.d); //May it need to parse the string
console.log(output.length);
// buildTable(result);
}
});
}

how to access returned variable from one ajax call in next ajax call

I want to access returned variable from one ajax call in another ajax call and want to repeat the second ajax call continuously. my code is below, and the required variables are mentioned in code comments.
<script type="text/javascript" language="javascript">
$( document ).ready(function() {
$.ajax({
url : "functions.php?id=enter_game&name=<?php echo $name; ?>",
type : "GET",
//dataType : 'json',
success: function(result){
if(result){
$("#game_status").html(result["game"]);
var limit = Object.keys(result).length - 4;
for(var x = 1; x <= limit ; x++)
{
$("#users").append('<li>'+result[x]["name"]+'</li>');
//$("#users").append('<li>abd</li>');
}
// I want to access these variables in next ajax call
var user_id = result["current_user_id"];
var word_id = result["word_id"];
}
}
});
// start updating continuously
var timer, delay = 1000; // time in milli seconds
timer = setInterval(function(){
$.ajax({
type : 'GET',
// the variables from previous ajax call result should be avaialable here
// and only this ajax call should be made upon delay time.
// previous ajax call should not be made more than once.
url : 'functions.php?user_id='+user_id+'&word_id='+word_id,
//dataType: 'json',
success : function(data){
if(data){
$("#game_status").html(Math.floor((Math.random() * 10) + 1));
}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
});
}, delay);
});
</script>
Any help would be much appreciated.
try below code . declare variables out side function. read more about variable scope in java script here
<script type="text/javascript" language="javascript">
var user_id;
var word_id;
$( document ).ready(function() {
$.ajax({
url : "functions.php?id=enter_game&name=<?php echo $name; ?>",
type : "GET",
//dataType : 'json',
success: function(result){
if(result){
$("#game_status").html(result["game"]);
var limit = Object.keys(result).length - 4;
for(var x = 1; x <= limit ; x++)
{
$("#users").append('<li>'+result[x]["name"]+'</li>');
//$("#users").append('<li>abd</li>');
}
// I want to access these variables in next ajax call
user_id = result["current_user_id"];
word_id = result["word_id"];
}
}
});
// start updating continuously
var timer, delay = 1000; // time in milli seconds
timer = setInterval(function(){
$.ajax({
type : 'GET',
// the variables from previous ajax call result should be avaialable here
// and only this ajax call should be made upon delay time.
// previous ajax call should not be made more than once.
url : 'functions.php?user_id='+user_id+'&word_id='+word_id,
//dataType: 'json',
success : function(data){
if(data){
$("#game_status").html(Math.floor((Math.random() * 10) + 1));
}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
});
}, delay);
});
Define you variables outside of the first ajax function.
$( document ).ready(function() {
//define them here first
var user_id = '';
var word_id = '';
$.ajax({
url : "functions.php?id=enter_game&name=<?php echo $name; ?>",
type : "GET",
//dataType : 'json',
success: function(result){
if(result){
$("#game_status").html(result["game"]);
var limit = Object.keys(result).length - 4;
for(var x = 1; x <= limit ; x++)
{
$("#users").append('<li>'+result[x]["name"]+'</li>');
//$("#users").append('<li>abd</li>');
}
//then set them here
user_id = result["current_user_id"];
word_id = result["word_id"];
}
}
});
// start updating continuously
var timer, delay = 1000; // time in milli seconds
timer = setInterval(function(){
$.ajax({
type : 'GET',
// should be accessible from here
url : 'functions.php?user_id='+user_id+'&word_id='+word_id,
//dataType: 'json',
success : function(data){
if(data){
$("#game_status").html(Math.floor((Math.random() * 10) + 1));
}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
});
}, delay);
});
});
Set the second ajax function inside a function and call it after getting the response from first ajax call
$(document).ready(function() {
$.ajax({
url: "functions.php?id=enter_game&name=<?php echo $name; ?>",
type: "GET",
//dataType : 'json',
success: function(result) {
if (result) {
$("#game_status").html(result["game"]);
var limit = Object.keys(result).length - 4;
for (var x = 1; x <= limit; x++) {
$("#users").append('<li>' + result[x]["name"] + '</li>');
//$("#users").append('<li>abd</li>');
}
// I want to access these variables in next ajax call
var user_id = result["current_user_id"];
var word_id = result["word_id"];
aftrAjax(user_id, word_id);
}
}
});
function aftrAjax(userid, wordid) {
var timer, delay = 1000; // time in milli seconds
timer = setInterval(function() {
$.ajax({
type: 'GET',
// the variables from previous ajax call result should be avaialable here
// and only this ajax call should be made upon delay time.
// previous ajax call should not be made more than once.
url: 'functions.php?user_id=' + user_id + '&word_id=' + word_id,
//dataType: 'json',
success: function(data) {
if (data) {
$("#game_status").html(Math.floor((Math.random() * 10) + 1));
}
},
error: function(xhr, status, errorThrown) {
alert("Sorry, there was a problem! Error: " + errorThrown + ", Status: " + status + ", xhr: ," + xhr);
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
});
}, delay);
}
});
A cleaner and better way using jQuery.Deferred()
The below is more of a demo than editing your code. So, feel free to adapt this to your situation.
$demo = $("#demo"); // remove - for demo only
var ajax1 = function() {
$demo.append("Begin ajax call 1<br/>"); // remove - for demo only
var dfd = $.Deferred();
$.ajax({
url: "/echo/xml/",
//url: "functions.php?id=enter_game&name=<?php echo $name; ?>",
type: "GET"
}).done(function(result) {
$demo.append("Ajax call 1 complete<br/>"); // remove - for demo only
//your code...
//............
//............
dfd.resolve(result);
});
return dfd.promise();
};
var ajax2 = function() {
$.when(ajax1()).done(function(result) {
// the variables from previous ajax call result are avaialable here
//var user_id = result["current_user_id"];
//var word_id = result["word_id"];
$demo.append("Begin ajax call 2<br/>"); // remove - for demo only
var times = 1;
var repeatAjax = function() {
if (times > 10) return; // remove - for demo only
$demo.append("Ajax call 2 called " + times + " time(s)<br/>"); // remove - for demo only
$.ajax({
type: 'GET',
url: "/echo/xml/", //['functions.php?user_id=', user_id, '&word_id=', word_id].join(""),
}).done(function() {
//your code...
//............
//............
$demo.append("Ajax call 2 complete<br/>"); // remove - for demo only
times++; // remove - for demo only
//optional - you may want to subtract the approximate response time from 1000, so, you'd actually achieve close to 1000ms :)
setTimeout(repeatAjax, 1000);
});
};
repeatAjax();
});
};
//Start the function
ajax2();

Rest API Multiple Lists in SharePoint

Because SharePoint works async i cannot store the data from multiple lists in array's and access them later.
I need to use 3 lists because they contain data from employees, holidays, and more.
See my code below for more information.
Is there no easier way to work with SharePoint and multiple lists to get the data. I tried also with executequeryasync but i cannot find a working solution for multiple lists. Or to store the value of each list in an array or variable and use it in another function because it's async.
$(function () {
$('#title').html("Inloggen verlofaanvraag");
});
function inLoggen() {
var initialen = $('#initialen').val();
var wachtwoord = $('#wachtwoord').val();
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst werknemers')/Items?$filter=wInitialen eq '" + initialen + "' and wWachtwoord eq '" + wachtwoord + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var werknemers = data.d.results;
for (var i = 0; i < x.length; i++) {
rInitialen = x[i].wInitialen;
rWachtwoord = x[i].wWachtwoord;
rVolledigenaam = x[i].wVolledigenaam;
}
if (i === 0) {
alert("U hebt geen toegang tot deze pagina !");
}
else {
$('#title').html("Welkom " + rVolledigenaam);
$('#inlogform').hide();
persoonlijketellers(werknemers);
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function persoonlijketellers(werknemers) {
var rId = werknemers[0].ID;
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
wettelijkeverlofdagen(werknemers, ptellers);
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
function wettelijkeverlofdagen(werknemers, ptellers) {
var rId = ptellers[0].ID;
alert(rId);
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Lijst persoonlijke tellers')/Items?$filter=pWerknemer eq '" + rId + "'",
type: "GET",
headers: { "accept": "application/json;odata=verbose" },
success: function (data) {
var x = data.d.results;
var ptellers = data.d.results;
for (var i = 0; i < x.length; i++) {
}
},
error: function (xhr) {
console.log(xhr.status + ': ' + xhr.statusText);
}
});
}
You can store the data from multiple lists in array and access them when all of your async calls are complete, you just need to use some sort of promise pattern.
jQuery's .when method is probably the most useful in a situation like this:
function SPData() {
function getJsonDataAsync(url) {
// returning the $.ajax object is what makes the next part work...
return $.ajax({
url: url,
method: "GET",
contentType: "application/json",
headers: {
accept: "application/json;odata=verbose"
}
});
}
var requestURI1 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI2 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var requestURI3 = _spPageContextInfo.webServerRelativeUrl + "/_api/lists/..."
var req1 = getJsonDataAsync(requestURI1);
var req2 = getJsonDataAsync(requestURI2);
var req3 = getJsonDataAsync(requestURI3);
// now we can do the next line, because req1/2/3 are actually deferreds
// being returned from $.ajax
jQuery.when(req1, req2, req3).done(function(resp1, resp2, resp3) {
/* do something with all of the requests here...
resp1/2/3 correspond to the responses from each call and are each an
array that looks like: [data, statusText, jqXHR], which means that your
data is in resp1[0], resp2[0], etc. */
});
If you want, you can also just assign the returned values to variables in a higher level context, then use individual jQuery deferreds so that you can be sure all of the calls have succeeded before you start working with the data...
...
var x1, x2, x3;
// use the .then(function() { ... }) pattern because we are just returning a
// deferred/promise from $.ajax
getJsonDataAsync(requestURI1).then(function(data) {
x1 = data;
getJsonDataAsync(requestURI2).then(function(data2) {
x2 = data2;
getJsonDataAsync(requestURI3).then(function(data3) {
x3 = data3;
// do something with x1, x2, and x3
});
});
});
}

this object reference not working inside $.each

Why won't foo get appended?
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
$(this).parent().parent().append('foo');
});
}
})
Because inside each, this is set to the current element being iterated over (docs), so normally we define this to be something else before we enter the each loop:
var that = this;
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
However, in this circumstance, this in the success callback of an AJAX request is equal to the jqXHR object which launched the request, not the DOM element you're after, so we have to move the var that = this to even further away;
var that = this;
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success: function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">' + val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$(that).parent().parent().append('foo');
});
}
})
var $this = $('#Selector').parent().parent();
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
url: 'barfoochakalaka',
success:
function(response) {
$.each(response, function(index, val) {
var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>';
$this.append('foo');
});
}
})
EDIT:
added .parent().parent() to the original selector, so you are not calling this for each loop
Response may not be an array, just a string. Try assigning the response to an element and then using a selector to grab all children in that element before doing an .each()
Your response is not an object of elements, it's most likely a list of strings possibly with your selectors(?) if that's it then use $($(this)).

Categories