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);
}
});
Related
I have a jsp file which has a form. And the form has some text fields and image upload field.I need to send text data to one servlet and image to another servlet when I click the submit button. is this possible ?
Yes.. I think it is possible .. the way I know you have to use a javascript library like jquery. Below is how it happens
On form submit you prevent the post to servlet. Then you can use ajax like shown below to send 2 requests to 2 different servlets. Below shows one ajax call.. you can do another after that call. I trying to show you below
$("form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
var author = $("#author").val();
$.ajax({
url: 'fileUploadServletUrl',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (response) {
alert(response);
}
});
$.ajax({
url: 'textDataServletUrl',
type: 'POST',
data: {'author':author },
async: false,
cache: false,
processData: false,
success: function (response) {
alert(response);
}
});
return false;
});
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']));
}
}
I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});
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
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
});
});