Make an API call inside of another API call? - javascript

I basically need to combine data from two different API calls. Here is what I have right now:
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
var api = data.results[0].api;
for (var i=0;i<api.length;++i)
var api2url = api[i].api2url;
{
$('tbody').append('<tr><td>'+api[i].thing+'</td></tr>');
}
}
});
The above works.
The problem is that I also need data from https://website.com/api2.json (which will come from data from the api1 call). I need my final code to look like:
$('tbody').append('<tr><td>+api[i].thing+'</td></tr>');

Easiest way forward would be to make that API call in the success callback of your first API call. Might look something like:
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
// now you have closure over results from api call one
$.ajax({
url: 'apiURL2', // or something
type: "GET",
dataType: 'json',
headers: {'X-API-Key': data.results.apiKey // or something },
success: function(moreData){
var api = data.results[0].api;
for (var i=0;i<api.length;++i)
{
$('tbody').append('<tr><td>'+api[i].thing+ moreData.thing'</td></tr>');
}
}
})
});

const getDataFromApi = (endpoint) => {
return new Promise((resolve, reject) => {
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: (data) => {
return resolve(data);
}
});
});
};
Promise.all([
return getDataFromApi('https://website.com/api.json');
]).then((data) => {
return Promise.all([
data,
getDataFromApi('https://website.com/api2.json')
]);
// here your business logic (for loop in your code)
}).then((data) => { // with bluebird it's easier use spread
const dataApi1 = data[0];
const dataApi2 = data[1];
})
.catch((err) => {
console.error(err);
});

You can make the second ajax call on the success of the first. Then perform your DOM updates as needed. But the idea is to run the second ajax call once the first has completed and was successful.
function callApi2(aip1) {
$.ajax({
//params for the call
url: api1.api2url,
success: function(data) {
var api2 = data.results[0].api; // or whatever the property is
$('tbody').append('<tr><td>'+api1.thing+'</td></tr>');
},
});
}
var url= "https://website.com/api.json";
$.ajax({
url: url,
type: "GET",
dataType: 'json',
headers: {'X-API-Key': 'xxxxxx'},
success: function(data){
var api1 = data.results[0].api;
for (var i=0; i<api1.length;++i){
callApi2(api1[i]);
}
}
});

Related

How to delete or post data using ajax(POST,DELETE) [duplicate]

GET:$.get(..)
POST:$.post()..
What about PUT/DELETE?
You could use the ajax method:
$.ajax({
url: '/script.cgi',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
$.ajax will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
console.log(result);
})
copy from here
Seems to be possible with JQuery's ajax function by specifying
type: "put" or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
It's basically just a copy of $.post() with the method parameter adapted.
Here's an updated ajax call for when you are using JSON with jQuery > 1.9:
$.ajax({
url: '/v1/object/3.json',
method: 'DELETE',
contentType: 'application/json',
success: function(result) {
// handle success
},
error: function(request,msg,error) {
// handle failure
}
});
You should be able to use jQuery.ajax :
Load a remote page using an HTTP
request.
And you can specify which method should be used, with the type option :
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
ajax()
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
For brevity:
$.delete = function(url, data, callback, type){
if ( $.isFunction(data) ){
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
contentType: type
});
}
You can do it with AJAX !
For PUT method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...
Must works for others Frameworks
Note: Tested with Laravel 5.6 and jQuery 3
I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!
CRUD
this may make more sense
CREATE (POST)Request
function creat() {
$.ajax({
type: "POST",
url: URL,
contentType: "application/json",
data: JSON.stringify(DATA1),
success: function () {
var msg = "create successful";
console.log(msg);
htmlOutput(msg);
},
});
}
READ (GET)Request
// GET EACH ELEMENT (UNORDERED)
function read_all() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
console.log("success!");
console.log(res);
htmlOutput(res);
},
});
}
// GET EACH ELEMENT BY JSON
function read_one() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
$.each(res, function (index, element) {
console.log("success");
htmlOutput(element.name);
});
},
});
}
UPDATE (PUT)Request
function updat() {
$.ajax({
type: "PUT",
url: updateURL,
contentType: "application/json",
data: JSON.stringify(DATA2),
success: function () {
var msg = "update successful";
console.log(msg);
htmlOutput(msg);
},
});
}
DELETE (DELETE)Request
function delet() {
$.ajax({
type: "DELETE",
url: deleteURL,
success: function () {
var msg = "delete successful";
console.log(msg);
htmlOutput(msg);
},
});
}
GitHub Reference
You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
alert('Yupi Yei. Your product has been deleted')
});
This will also apply for

getting null value in function variable that assign in ajax success function in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
function getData(url) {
var responseData = null;
$.ajax({
type: "GET",
url: url,
crossDomain: true,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (result) {
responseData = result;
}
});
console.log(responseData);
return responseData;
}
var getapidata= getData('https://jsonplaceholder.typicode.com/todos/1');
console.log('getapidata',getapidata);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
It's an async event, So you should do something similar this syntaxe may help:
function getData(url) {
return $.ajax({
type: "GET",
url: url,
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: "jsonp"
});
}
var getapidata = getData('https://jsonplaceholder.typicode.com/todos/1').then(value => {
console.log(value)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I think you don't want to write $.ajax syntax every time when you need to send ajax call. if so then this code can help you.
Note You should must learn how JavaScript asynchronously works because the which you have written will never work.
Here is my code in which i have add some more functionality.
1) dynamically set URL and Methods
2) Now you can GET, POST, PUT, PATCH, DELETE using getData() function
getData() function required two parameter and one optional parameter depending upon you need to send data on server or not.
getData(URL, Method, Data if there)
$(document).ready(async () => {
function getData(url, method, data = {}) {
return $.ajax({
method,
url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
});
}
// getData(URL, Method, Data)
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'PATCH', {title: "new post"})
// await getData('https://jsonplaceholder.typicode.com/posts/1', 'DELETE')
// await getData('https://jsonplaceholder.typicode.com/posts', 'POST', {
// userId: Math.floor(Math.random() * 1000),
// title: "New Post",
// body: "This is my new post"
// })
var getapidata = await getData('https://jsonplaceholder.typicode.com/posts/1', 'GET')
console.log(getapidata)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Thank you

how to create a javascript rusable class to pass parameters to ajax

im new in JS,im looking for a way to create a class or function,reusable everywhere in my code,just pass it parameters and get the result,because currently I am doing like this:
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": tmpString }),
success: function (result) {
})}
I write this every time I need, and im sick of it,
function sendAjaxCustom(DataType,Type,Url,Ctype,Data){
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
})}
}
You can call this function in JS like
var result = sendAjaxCustom("json","POST",'#Url.Action("power","Ranking")',"application/json; charset=utf-8",JSON.stringify({ "regionalManager": tmpString }));
you will have the result in result variable.
You can create a function like this
function ajax(url, data) {
$.ajax({
dataType: "json",
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: data,
success: function (result) {
})}
}
Pass the url if it's dynamic and the object data on the second parameter.
Just create a simple function with your variables that need to change between calls and return the $.ajax result from there.
function ajaxWrapper(url, data, callback) {
return $.ajax({
dataType: 'json',
type: 'POST',
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: callback
});
}
When you want to call it:
ajaxWrapper('http://www.google.com/', { hello: 'world' }, function(result) {
console.log(result);
});
With the callback it's much more reusable, since you can use this anywhere and change what you do on completion of the function wherever you use it.
A simple solution is to return an object and pass it to the ajax and if some change is required then you can update the properties of the object before calling the ajax service
function commonAjaxParams() {
return {
dataType: "json",
type: "POST",
url: "#Url.Action("power","Ranking")",
contentType: "application/json; charset=utf-8",
//and so on that are common properties
}
}
//now in your application first call the function to get the common props
var commonParams = commonAjaxParams();
//change or add an parameter to your liking
commonParams.type = 'GET';
commonParams.success = function(){...} //if this action is need
commonPramss.error = function(){...}
//now call you ajax action
$.ajax(commonParams)
There is another way in which you may call the ajax function and you may get success, fail response return.
The benefit is you manage success or fail response independently for each ajax request.
$(document).ready(function() {
function ajaxRequest(dataType, requestMethod, dataURL, jsonData) {
return $.ajax({
dataType: dataType,
type: requestMethod,
url: dataURL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData)
});
}
var jsonData = {
"regionalManager": "jason bourne"
};
ajaxRequest(
"json",
"POST"
"#Url.Action('power','Ranking')",
jsonData)
.success((data) {
console.log("success");
}).error((err) {
console.log("error");
}).done(() {
console.log("done");
});
});

jQuery Ajax get value via function?

I have created a save(id) function that will submit ajax post request. When calling a save(id). How to get value/data from save(id) before going to next step. How to solve this?
For example:
function save(id) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
return data;
},
error: function (error) {
return data;
}
});
}
Usage:
$('.btn-create').click(function () {
var id = 123;
data = saveArea(id); //get data from ajax request or error data?
if (data) {
window.location = "/post/" + data.something
}
}
You have two options, either run the AJAX call synchronously (not recommended). Or asynchronously using callbacks
Synchronous
As #Drew_Kennedy mentions, this will freeze the page until it's finished, degrading the user experience.
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
async: false,
data: JSON.stringify({
id: id,
})
}).responseText;
}
$('.btn-create').click(function () {
var id = 123;
// now this will work
data = save(id);
if (data) {
window.location = "/post/" + data.something
}
}
Asynchronous (recommended)
This will run in the background, and allow for normal user interaction on the page.
function save(id, cb, err) {
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
cb(data);
},
error: err // you can do the same for success/cb: "success: cb"
});
}
$('.btn-create').click(function () {
var id = 123;
save(id,
// what to do on success
function(data) {
// data is available here in the callback
if (data) {
window.location = "/post/" + data.something
}
},
// what to do on failure
function(data) {
alert(data);
}
});
}
Just make things a bit simpler.
For starters just add window.location = "/post/" + data.something to the success callback.
Like this:
function save(id) {
return $.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success:function(data){
window.location = "/post/" + data.something
}
}).responseText;
}
Or by adding all your Ajax code within the click event.
$('.btn-create').click(function () {
var id = "123";
$.ajax({
type: "POST",
url: "/post/",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
id: id,
}),
success: function (data) {
window.location = "/post/" + data.something
},
error: function (error) {
console.log(error)
}
});
}

Retrieve POST JSON response

I'm writing my first Ajax request, on a Groovy/Grails platform.
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
data: {source:"${source}"},
success: function (response) {
jsonData = response;
var res = JSON.parse(jsonData);
alert(res);//
}
});
Here is the response of my controller "url"
def result = [ value: 'ok' ]
render result as JSON
But it does not work and i get an error message in my browser
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var res = JSON.parse(jsonData);
I don't understand , the response seems to be a nice formatted JSON ?
EDIT i did a print as Paul suggests :
If i execute
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response)
console.log(response.value)
jsonData = response;
}
});
The first print is :
Object { value="ok"}
The second print is
ok
If i want to get the result, how is the proper way ?
Do i have to assign the value inside the statement "success: function (response) { "
doing something like
var result
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
result = response.value
}
});
console.log("result : "+result);
This code works for me !!
Or perhaps there is a way to get the result, doing something like
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
}
});
var result = newDataB.response.somethingblablabla
or
var result = OneFunction(newDataB.response)
??????
You can make object stringified before passing it to parse function by simply using JSON.stringify().
var newDataB = $.ajax({
method: 'post',
url: "${createLink(controller: 'util',action: 'test')}",
async: false,
data: {source: "abc"},
success: function (response) {
jsonData = response;
var res = JSON.parse(JSON.stringify(jsonData));
console.log(res);//
}
});
Hopefully this may help.
You shouldn't need to parse it, if your server is providing json.
You can use dataType though to force jQuery to use a particular type:
var newDataB = $.ajax({
method:'post',
url: url,
async: false,
dataType: 'json',
data: {source:"${source}"},
success: function (response) {
console.log(response);
}
});

Categories