I am creating a json object in which I am pulling fields from form and then using jquery Ajax POST to send the data. But when I see my network tab after pressing submit I basically get the json headers but all the values that should have been pulled from the form are blank except the values I am hardcoding. Note that my json data also has a nested json of type room.
Below is my jquery part:-
var formData={
"checkInDate": $("#checkInDate").val(),
"checkOutDate": $("#checkOutDate").val(),
"roomsWanted":$("#roomsWanted").val(),
"room":{
roomType: $("input[name=roomType]:checked").val(),
roomProperty:"non-smoking"
}
};
$("#checkAvailabilityForm").submit(function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: '',
dataType: 'json',
data: JSON.stringify(formData),
contentType: 'application/json',
success: function(dataRecieved){
var dataRecieved= $.trim(dataRecieved);
if(dataRecieved === ''){
}else{
}
}
});
});
Move your declaration of formData inside of the .submit() function. The way you have it now the page loads, and then var formData = ... immediately sets the value for formData (to the values of the new empty form).
Your code should look like this:
$("#checkAvailabilityForm").submit(function(e){
e.preventDefault();
var formData={
"checkInDate": $("#checkInDate").val(),
"checkOutDate": $("#checkOutDate").val(),
"roomsWanted":$("#roomsWanted").val(),
"room":{
roomType: $("input[name=roomType]:checked").val(),
roomProperty:"non-smoking"
}
};
$.ajax({
type: 'post',
url: '',
dataType: 'json',
data: JSON.stringify(formData),
contentType: 'application/json',
success: function(dataRecieved){
var dataRecieved= $.trim(dataRecieved);
if(dataRecieved === ''){
}else{
}
}
});
});
You don't need to stringify your json just past the json as it
data: formData
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 would like to send the form in its entirety, using ajax.
The form has an Id which is 'FormId'.
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax
({
url: Url,
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
When debugging the code I can see that testForm is equal to the entire form.
var cvForm = new FormData(testForm[0]);
Is empty for some reason.
The form has many fields, so I hope it is possible to send the entire form, instead of defining every single field in js before sending them.
Thanks in advance.
When you use FormData, the content type should be multipart/form-data, not application/x-www-form-urlencoded. You should also use processData: false to prevent jQuery from trying to serialize the FormData object.
$.ajax
({
url: Url,
type: "POST",
contentType: "multipart/form-data",
processData: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
If the form doesn't have any file uploads, you can use $('#FormId').serialize() to serialize it in URL-encoded format, then your $.ajax call would work. You don't need the contentType option, it defaults correctly.
You need to set contentType to false so proper Content-Type header with correct boundary will be set. Also set processData to false to prevent jQuery serializing data
const Url = '/CV/AutoSave/';
var testForm = $('#FormId');
var cvForm = new FormData(testForm[0]);
$.ajax({
url: Url,
type: "POST",
processData: false,
contentType: false,
data: cvForm,
success: function (result) {
console.log(result.Id)
}
});
I am making a form submission through AJAX using jQuery. I have the following code:
$("#myForm-form").on("submit", function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
'eoss': 'indexEOSS',
'form': 'myForm',
'values': createJSON(),
'formData': formData
},
success: function(data) {
console.log(data);
eval(data);
myFormForm(data);
},
processData: false,
contentType: false
});
return false
});
However I get this:
GET http://localhost/EOSS2/request.php?[object%20Object] 404 (Not Found)
When I remove processData: false and contentType: false I get the following error:
Uncaught TypeError: Illegal invocation
What should I do?
You have two issues here. Firstly your error message indicates that you're sending a GET request, which does not work with FormData. Using POST would seem the most applicable in this case.
Secondly, you cannot send FormData in an object as jQuery will attempt to URL encode it which will lead to issues. Instead use the append() method to add information to your FormData object. Try this:
$("#myForm-form").on("submit", function(e) {
e.preventDefault();
var $form = $(this);
var formData = new FormData($form[0]);
formData.append('eoss', 'indexEOSS');
formData.append('form', 'myForm');
formData.append('values', createJSON());
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'), // change the attribute in HTML or hardcode to 'post'
data: formData,
success: function(data) {
console.log(data);
// eval(data); < never, ever use eval()
myFormForm(data);
},
processData: false,
contentType: false
});
});
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 need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);