I have a form on my HTML page with some fields to be filled and an option to upload a file. My Javascript function converts the inputs to the fom into a json file. I am trying to push this generated json along with the file uploaded by the user to a webservice but I am getting an error which says
405 OPTIONS
Here's the Ajax function I wrote. The formData.serializeObject() function gives me the Json output to the form.
$(function() {
$('form').submit(function() {
($('#file')[0].files[0].name);
var formData = new FormData($("form")[0]);
formData.append("filename", $('#file')[0].files[0].name);
var obj = new FormData();
form = form
$.ajax({
url: "Webserviceurl:port/function_to_send_json",
type: "POST",
data: JSON.stringify(formData.serializeObject()),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data) {
$.ajax({
url: "Webserviceurl:port/function_to_send_file",
type: "POST",
data: obj,
contentType: false,
success: function(data) {
},
error: function(data) {
console.log("Error Happened");
}
});
return false;
},
error: function(data) {
console.log("Error Happened");
}
});
})
});
What could I be doing wrong here?
The error message is being reported because you are making a preflighted request. This means the browser is sending an OPTIONS request asking for permission to make a POST request.
The server is responding to the OPTIONS request with a 405 error meaning "You can't make an OPTIONS request to this URL!"
That said …
data: JSON.stringify(…),
If you are sending JSON then you should say you are sending JSON, which ha a content type of application/json, not:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
There is no serializeObject method on formData objects, so formData.serializeObject() should be throwing an exception.
This question covers how to upload files with Ajax.
Related
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);
}
});
I am submitting a form using ajax. Form is consist of some textboxes, textareas etc (string data) and a file as well. I am sending the form as javascript FormData().
The problem is that the Ajax request sometimes failed but not always.
e.g. I tried to upload bigger files in zip, it was uploaded successfully five times but on the sixth attempt it got failed due to an error i got in the console "ERR_CONNECTION_RESET"
How to overcome this that it never happens. Thanks
Ajax Request using FormData():
var formData = new FormData();
formData.append("consider all my data here from form",data);
$.ajax({
url : 'abc.com/controller/function&token='+token,
type: 'post',
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$("#loader").show();
},
complete: function () {
$("#loader").hide();
},
success: function(json){
$("#loader").hide();
console.log(json);
},
error: function(error){
console.log(error);
alert("Something went wrong while updating chapter info. Please, refresh and try again.");
}
});
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});
I have the following jQuery AJAX request:
// collect form data and create user obj
var user = new User();
user.firstname = $("#usrFirstName").val();
user.lastname = $("#usrSurname").val();
user.role = $("#usrRole").val();
// actual ajax request
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: user,
contentType:"application/json; charset=utf-8",
dataType: 'json'
}).done(function(data, status) {
alert(JSON.stringify(data));
}).fail(function(data, status) {
alert(status);
alert(JSON.stringify(data));
});
The response from the Server is:
"status":400,"statusText":"Bad Request"
"The request sent by the client was syntactically incorrect."
The server is running Spring-MVC. But as far as I can tell it is working correctly. Because if I'm sending a request manually with Postman and the following configuration it works.
Header:
Content-Type application/json; charset=utf-8
Content:
{"firstname":"alex","lastname":"lala","role":"admin"}
I have to mention that it is a cross-domain request (for the time developing, it will be hosted on the same domain as the server later). I did disable the security settings in the browser and AJAX requests to the server are working fine (as long as I don't have to send data).
you need to serialize your json, try:
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user),
contentType:'application/json; charset=utf-8',
dataType: 'json'
})
JSON.stringify() method is used to turn a javascript object into json string. You need to have this. In addition it is better to include success and error portions in the AJAX.
$.ajax({
type: 'POST',
url : 'http://awesome-url',
crossDomain: true,
data: JSON.stringify(user), // turn a javascript object into json string
contentType:'application/json; charset=utf-8',
dataType: 'json',
success: function (html) {
alert(html);
}, error: function (error) {
alert(error);
}
})
I have client URL and getting response from that URL through browser. While sending through AJAX I am getting a null response. Right now I am working with a .Net application. Here I am given my script. Please guide me to get proper response and thanks in advance.
Response:
{
"resultFlag": false,
"message": "Dealer not found",
"info": []
}
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: URL,
//data: data,
dataType: "json",
contentType: "application/json; charset=utf-8", // content type sent to server
success: function (result) {
// JSON.stringify(result);
alert(JSON.stringify(result));
},
error: function () {
alert('error');
}
});