Passing Ajax GET response after initial Ajax POST call - javascript

I am trying to do a second ajax call when initial ajax post is done, the initial call is a Post and the second call is a get type, on the second call I am able to get the values of url file.php but can't use the returned value as a condition condition parameter.
here's a copy of the js:
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
dataType: 'json'
})
.done(function() {
//SOME UI UPDATES ARE HAPPENNG HERE
//SOME OTHER AJAX CALL AFTER INITIAL CALL IS DONE
$.ajax({
url: 'progress.php',
type: 'GET',
data: status,
async:false,
cache:false
})
.done(function(response) {
console.log("success"); // GETS STRING VALUE OF PROGRESS.PHP
if (response == "success") {
//DO SOMETHING ELSE
};
})
.fail(function(response) {
console.log("error");
});
})
.fail(function() {
//console.log("error");
//INITIAL POST ERROR GOES HERE
});

response also contains a new line to the end. Better checking the string contains in this case.
response.indexOf('success') !== -1

Related

Checking if form has been submitted via ajax - PHP

As the title says, I wanna check if this ajax method has been submitted or not and show the result in a condition.
Here is the Ajax POST code;
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: handleResult
});
And here is the condition I put but it is not working.
function handleResult(data){
if(data == 'error'){
window.location.href ='404.php';
}
else{
$( "#clearcart" ).click();
window.location.href = "ordercomplited.php";
}
}
try this
$.ajax({
url: "addorderInfo.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function (data) {
alert(data)
},
error: function (error) {
alert(error.responseText) // if your request doesn't work
}
});
There isn't sufficient code to know why is not working.
IMHO the ajax call is not handling the error. Try to edit your code as follow:
$.ajax({
url: "addorderInfo.php", // Url to which the request is sent
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) {
handleResult(data);
}
error: function(data) {
handleError(data);
}
});

multiple ajax call to single function javascript

I have 3 ajax call. Data from each ajax call is passed to john_doe();
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data1){
john_doe(data1);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
john_doe(data2);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data3){
john_doe(data3);
});
Main function
function john_doe(param){
console.log(param); //Print data from all three ajax call.
}
How to separate data1, data2 and data3 in john_doe function? because I need to carry out arithmetic operation.
Currently,
Input
data1 = one,two,three
data2 = four
data3 = five
Output
console.log(param) would give output as
one
four
five
I want output as
console.log(param[0])
console.log(param[1])
console.log(param[2])
param[0] containing one,two,three
param[1] containing four
param[2] containing five
I dont have control over the data. How to access data1, data2 and data3 separately?
Using promises you can access all the data in Promise.all() callback and do whatever you need with it all at once. Assumes using jQuery 3+. Can use $.when in older versions
var urls =['data-1.json','data-2.json','data-3.json'];
// array of ajax promises
var reqPromises = urls.map(function(url){
return $.ajax({
url: url,
dataType: "JSON",
type: "GET"
});
});
Promise.all(reqPromises).then(function(res){
// res is array of all the objects sent to each `$.ajax` from server
// in same order that urls are in
var param = res.map(function(item){
return item.val
});
console.log(param)
})
DEMO
Quick and dirty solution is simply pass in an identifier, why is this dirty because it isn't really extensible with respect to adding say 4th or 5th call each time you do this you need to add more identifiers and your if statement in the main method will end up pretty ugly at one point. But that said sometimes "Keeping It Simple" is ok.
Main function:
function john_doe(identifier, param) {
// best to use something more readable then numbers
if(identifier == 1) {
console.log(param); //Print data from all ajax call 1.
} else if(identifier == 2) {
console.log(param); //Print data from all ajax call 2.
} else if(identifier == 23) {
console.log(param); //Print data from all ajax call 3.
} else {
// handle bad id
}
}
In your ajax calls, pass in the right identifier, for example Call 2:
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data2){
// numeric 2 in in the first param is your identifier
john_doe(2,data2); });
Adding a param to let you know where it is being called from
Call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call1',data);
});
Call 2
$.ajax({
url: url2,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call2',data);
});
Call 3
$.ajax({
url: url3,
dataType: "JSON",
type: "GET",
}).success(function(data){
john_doe('call3',data);
});
Main function
function john_doe(call,data){
console.log('Called from : ' + call);
console.log(data); //Print data from all three ajax call.
}
How about this?
Declare an object container to hold your response data values and your arithmetic operation function.
var myParams = {
all_params: [],
getParams: function(){
return this.all_params;
},
setParam: function(index, data){
this.all_params[index] = data;
},
yourArithmeticOperation: function(){
console.log(this.all_params); // your actual logic using all 3 ajax response data
}
}
Then, in your ajax calls:
// call 1
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(0, data); // add ajax 1 response data
});
// call 2
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(1, data); // add ajax 2 response data
});
// call 3
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
}).success(function(data){
myParams.setParam(2, data); // add ajax 3 response data
});
In case you need all your response data,
// after all three ajax calls
params = myParams.getParams();
console.log(params);
And finally, your arithmetic operation,
myParams.yourArithmeticOperation();
try adding async: false to your ajax calls
$.ajax({
url: url1,
dataType: "JSON",
type: "GET",
async: false,
}).success(function(data){
john_doe('call1',data);
});

Sending data, Class, and Method through Ajax

How can I send data through ajax to a specific method in a another PHP class? In the url value I have pointed to the class file, but where can I assign the method name to use?
$.ajax({
type:'POST',
url:'ResortController.php',
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Pass the data in data:vidData and specify your function name after call of controller.
url = BASE_PATH + 'ResortController/FUNCTION_NAME';
vidData = {id: 123, vidName: "testVideo"};
$.ajax({
type:'POST',
url:url,
data: vidData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
Using $_POST in your function you will get your ajax data in $_POST['vidData'].
Also you need to call data instead of vidData variable in success of ajax console.log(data).
You need to have a server-side mechanism in place to handle how to direct your requests. Presumably the url you are sending a request to just has the class declaration...you need some sort of dispatcher or else php doesn't know what to do:
jQuery:
$.ajax({
type:'POST',
url:'/dispatcher.php',
data: {
"data":vidData,
"class":"ResortController",
"method":"rMethod"
},
cache:false,
success:function(data){
console.log("success");
console.log(vidData);
//window.location.reload();
},
error: function(data){
console.log("error");
}
});
/dispatcher.php
<?php
// This is dangerous if you have no controls in place to allow/restrict
// a program to run a command
// Anyone could send a cURL request and run an automated class/method through
// this mechanism unless you have some way to restrict that
if(!empty($_POST['class']) && !empty($_POST['method'])) {
// Here you want to have some way to check that a request is valid and not
// made from some outside source to run arbitrary commands
// I will pretend you have an admin identifier function....
if(is_admin()) {
call_user_func_array(array($_POST['class'],$_POST['method']),array('data'=>$_POST['data']));
}
}

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();

Ajax Call waiting for the response of another Ajax Call?

I have two ajax call that cannot be done in one call. When the first ajax call starts the second ajax call can start immediately or whenever the user presses a send button. If the second ajax call starts he has to wait for the response of the first ajax call because he needs data from it.
How can I achieve that the second ajax call sends his request only after the first ajax call's response has been arrived?
Is there another way than setTimeout?
Can I register a listener for ajax call 2 on ajax call 1 somehow?
My code would be:
var xhrUploadComplete = false;
// ajax call 1
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
xhrUploadComplete = true;
}
});
// ajax call 2
if (xhrUploadComplete) {
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
...
}
});
}
Edit: The second ajax call cannot be posted in done() or complete() of the first call, because it depends on the users choice to send the final form. The purpose of this two step process is to send an image to the server just after the user had inserted it to an input type=file.
Edit: In know that I cannot the the if(..) because this is an async call. I wrote it to make clear what I need to do. I think I need something like a future in Java.
xhrUploadComplete will be set to true asynchronously (in the future, when the request has finished) so your if-condition (that is evaluated right after the request is started) will never be fulfilled. You cannot simply return (or set) a value from an ajax call. Instead, move the code that waits for the results into the handler that would have set/returned the variable:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
complete: function(response) {
var returnedResponse = JSON.parse(response.responseText);
$.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false,
complete: function(response) {
…
}
});
}
});
With the Promise pattern you can compose those even more elegantly:
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false
}).then(function(response) {
var returnedResponse = JSON.parse(response.responseText);
return $.ajax({
url: url2,
type: "POST",
data: formdata2,
processData: false,
contentType: false
});
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
Maybe you need also need this:
var ajax1 = $.ajax({
url: url, …
}).then(function(response) {
return JSON.parse(response.responseText);
});
$(user).on("decision", function(e) { // whatever :-)
// as soon as ajax1 will be or has already finished
ajax1.then(function(response1) {
// schedule ajax2
return $.ajax({
url: url2, …
})
}).done(function(response) {
// result of the last request
…
}, function(error) {
// either of them failed
});
});

Categories