Sending variable from one ajax call to the next - javascript

I have an API I'm trying to query which requires an initial request to generate the report, it returns a report ID and then in 5 seconds you can pull it from that report ID.
This is what I have which works perfectly and returns the reportID:
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
}});
});
});
It returns this:
{"reportID":1876222901}
I'm trying to make it call another ajax call on the back of the first one to collect the report using the reportID as the data varaible "ref". So for example, the second ajax query should have ref: 1876222901
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result);
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID
},
success: function(result){
console.log(result);
}
});
}});
});
});
What I am stuck with is the way I am passing the variable from the result of the first ajax call to the second. It doesn't seem to make it there. How should I send my report ID 1876222901 into my second ajax call please?

You can do this without jQuery just using browser built-in DOM APIs and the fetch API
const r2 = document.getElementById('r2')
const loading = document.getElementById('loading')
const handleAsJson = response => response.json()
const fetchRef = ({reportId}) =>
fetch(`report.php?type=get&ref=${reportId}`)
document.onready = () => {
r2.addEventListener('click', () => {
loading.show();
// you don't have to interpolate here, but in case these
// values are variable...
fetch(`report.php?type=${'queue'}&ref=${2}`)
.then(handleAsJson)
.then(fetchRef)
.then(handleAsJson)
.then(console.log)
})
}

The solution is instead of writing
ref: result.reportID
You have to write it like this
ref: result.reportID.reportID
Because as your said, the first time you use console.log(result.reportID) the result is {"reportID":1876222901}. Which means you have to chaining dot notation twice to be able to reach the value 1876222901 in the next ajax call.
To be clear:
$(document).ready(function(){
$("#r2").click(function(){
$('#loading').show();
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result); // as you said, console.log(result.reportID) return {"reportID":1876222901}
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'get',
ref: result.reportID //which means, this line would be => ref: {"reportID":1876222901}
// we will correct it like this => ref: result.reportID.reportID
// then we properly get => ref:1876222901
},
success: function(result){
console.log(result);
}
});
}});
});
});
Hopefully it fixes your error.

I think you can try to make another function for calling after your first ajax like
$(document).ready(function(){
$("#r2").click(function(){
$.ajax({
url: "report.php",
dataType: 'json',
data: {
type: 'queue',
ref: 2
},
success: function(result){
console.log(result.reportID);
callSecondAjax(result.reportID)
}});
});
});
now make that function like
function callSecondAjax(reportId){
// do some stuff
}

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

jQuery ajax in ajax request

We have some code(simplified) that looks like bellow. We run function x which does an ajax call. When the call is done we call a different function recalculateOrderObjects which also does an ajax call. When this one is completed, it should output the data that which is obtained via the second call. However, what actually happens is that only the first ajax call is made and the second is not executed (or at least immediately goes to done) but does show the data obtained from the first call as the data obtained from the second one.
When running only the recalculateOrderObjects function the function does work as expected.
Edit 1
The subscription variable is a global
There are no errors on the console
Also, when I first call recalculateOrderObjects independent the function work when first x is called and after that I call recalculateOrderObjects independently the function will not work and shows the same behaviour as when called from `x.'
Edit 2
I tried the suggestion to use successinstead of doneas well. With the same result. recalucateOrderObjects is called succesfully, thought after one executing x the whole ajax call in recalucateOrderObjects is never requested again but instead thinks that it is succesfully executed.
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription}
})
.done(function (data) {
console.log('Data ' + data);
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
async: false
}).done(function (response) {
recalculateOrderObjects();
}
});}
x();
You can't get success responce by ".done" function.
"success" function gives you responce after ajax load.
Please try below code
function recalculateOrderObjects() {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
recalculateOrderObjects();
}
});
}
x();
OR
function x(){
jQuery.ajax({
type: "get",
dataType: "json",
url: url,
success: function(data) {
$.ajax({
type: 'post',
url: url + "something",
data: {data: subscription},
success: function(data) {
console.log('Data ' + data);
}
});
}
});
}
x();

How to call json object from AJAX?

Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);

Jquery set HTML via ajax

I have the following span:
<span class='username'> </span>
to populate this i have to get a value from PHP therefor i use Ajax:
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
}
})
}
Now when i debug i see that the returned data (data) is the correct value but the html between the span tags stay the same.
What am i doing wrong?
Little update
I have tried the following:
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html('RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRr');
}
})
}
getUsername();
Still there is no html between the tags (no text) but when i look at the console the method is completed and has been executed.
Answer to the little update
The error was in my Ajax function i forgot to print the actual response! Thank you for all of your answers, for those of you who are searching for this question here is my Ajax function:
public function ajax_getUsername(){
if ($this->RequestHandler->isAjax())
{
$this->autoLayout = false;
$this->autoRender = false;
$this->layout = 'ajax';
}
print json_encode($this->currentClient['username']);
}
Do note that i am using CakePHP which is why there are some buildin methods. All in all just remember print json_encode($this->currentClient['username']);
The logic flow of your code is not quite correct. An asynchronous function cannot return anything as execution will have moved to the next statement by the time the response is received. Instead, all processing required on the response must be done in the success handler. Try this:
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: { },
success: function(data){
$('.username').html(data); // update the HTML here
}
})
}
getUsername();
Replace with this
success: function(data){
$('.username').text(data);
}
In success method you should use something like this:
$(".username").text(data);
You should set the html in callback
function getUsername() {
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
$('.username').html(data);
}
})
}
Add a return statement for the function getUsername
var result = "";
$('.username').html(getUsername());
function getUsername(){
$.ajax({
type: 'POST',
url: myBaseUrl + 'Profiles/ajax_getUsername',
dataType: 'json',
data: {
},
success: function(data){
document.write(data);
result = data;
}
})
return result;
}
You can use .load()
Api docs: http://api.jquery.com/load/
In your case:
$('.username').load(myBaseUrl + 'Profiles/ajax_getUsername',
{param1: value1, param2: value2});

Why can't I do .ajax ( return data; )? jQuery

I'm trying to get my function to return the data it got into another function but it doesn't seem to work? How can I get it to return the data?
function playerid(playername) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
return data;
}
});
}
I want to use it in another function like this
showBids(playerid(ui.item.value));
function showBids(playerid) {
$.ajax({
type: "POST",
url: "poll.php?",
async: true,
dataType: 'json',
timeout: 50000,
data: "playerid="+playerid,
success: function(data) {
//.each(data, function(k ,v) {
//})
//$("#current_high").append(data);
setTimeout("getData()", 1000);
}
});
First of all, your playerid() does not return anything, so what do you want to use? It has only $.ajax() call in it, no return statement (one of the callbacks in $.ajax() has return statement, but see below).
Secondly, JavaScript does some things asynchonously, otherwise every interface element would need to wait to react to user action until the AJAX call returns from the server.
Use event-based approach, by passing callbacks to some functions. Then, after they finish, just call the callbacks passing them the result:
function getplayerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
//$("#test").text(data);
callback(data);
}
});
}
and then use it like that:
getplayerid(ui.item.value, showBids);
(notice function name change since it does not actually return player ID, it gets it and passes it to callback)
You could try to use syncronous Ajax:
function playerid(playername) {
return $.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
async : false //making Ajax syncronous
}).responseText;
}
Otherwise you need to use showBids function as callback:
function playerid(playername, callback) {
$.ajax({
type: "POST",
url: "fn.php?playerid",
data: "playername="+playername,
success: function(data) {
callback(data);
}
});
}
//Usage
playerid(ui.item.value,showBids);

Categories