Created
June 11, 2017 20:26
-
-
Save infantito/574c0ab1173515257cddc8f8eec4c76e to your computer and use it in GitHub Desktop.
Example of how to get ajax call in a synchronous way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let url = 'https://jsonplaceholder.typicode.com'; | |
let buttonAjax = document.querySelector('.buttonAjax'); | |
buttonAjax.addEventListener('click', doSomething); | |
function doSomething() { | |
console.log('do something more...'); | |
return getAjax(callback, 'users', anotherAjax); | |
} | |
function getAjax(callback, webservice) { | |
$.ajax({ | |
type: 'GET', | |
url: `${url}/${webservice}`, | |
// dataType: 'json', | |
// data: {}, | |
success: function(data) { | |
return callback(data, anotherAjax); | |
}, | |
error: function(error){ | |
return callback(error); | |
} | |
}); | |
} | |
function anotherAjax(callback, webservice) { | |
$.ajax({ | |
type: 'GET', | |
url: `${url}/${webservice}`, | |
// dataType: 'json', | |
// data: {}, | |
success: function(data) { | |
return callback(data); | |
}, | |
error: function(error){ | |
return callback(error); | |
} | |
}); | |
} | |
function callback(data, nextAjax) { | |
// Ajax nested | |
if (nextAjax) { | |
return nextAjax(callback, 'users?id=1'); | |
} | |
console.log(data) | |
return data; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://jsonplaceholder.typicode.com/
https://stackoverflow.com/questions/39067752/javascript-function-ajax-call-returns-undefined
https://stackoverflow.com/questions/17802211/ajax-call-returning-undefined