How I to for send an image and form with a request ajax?
HTML
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
</form>
<button id="btnSave">Save</button>
JQuery - AJAX
$("#btnSave").click(function()
{
var Url = 'http://localhost/systemm/public/painel/client';
var Dados = $('#FormClient').serialize();
$.ajax({
type:Type,
url: Url,
dataType: 'JSON',
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
});
When I serialize the data and put in an alert to display I see that the image is not there, how do I send the image along with my form to my server/controller?
Use formData object:
HTML
<form enctype="multipart/form-data">
<input type="text" class="form-control" id="Name" name="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button id="btnSave">Save</button>
</form>
JS
$("#btnSave").click(function() {
var Url = 'http://localhost/systemm/public/painel/client';
var formData = new FormData(this.form);
$.ajax({
type:'post',
url: Url,
dataType: 'JSON',
data: formData,
...
});
});
Let's try following,
<form id="POST_FORM" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button type="submit" id="btnSave">Save</button>
</form>
$("#POST_FORM").submit(function(){
var data = new FormData(this);
addPOST(data);
return false;
});
function addPOST(formData){
$.ajax({
type:'POST',
url: Url,
data:formData,
dataType:"json",
cache:false,
contentType: false,
processData: false,
success:function(response){
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
Try to change content dataType. Set dataType='false'
$.ajax({
type:Type,
url: Url,
dataType: false,
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
Hope this helps
This is the way i have done it.
var obj = document.getElementById('my_form_id')
var data = new FormData(obj);
$.ajax({
type: 'post',
url: $(obj).parent().attr('action'),
processData: false,
contentType: false,
data: data,
success: function(result){
profile_app.user.foto_url = result.url
},
error: function(error){
console.log("error");
}
});
Related
I am trying to upload multiple image files. Please check out my code.
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" id="images_input">
</from>
$(document).ready(function(){
$('body').on('submit', '#fileupload', function(e){
e.preventDefault();
var files = document.getElementById("images_input").files;
var files_array = [];
$(files).each(function(index, value){
files_array.push(value);
// files_array.push(value);
});//each
var user_id = $("#user_id_input").val();
var product_name = $("#product_name_input").val();
console.log("Data",files[0]);
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
url: url,
data:{
files:files_array,
user_id: user_id,
product_name: product_name
},
type: 'POST',
success: function(data){
alert(data);
}
});
});
$('#images_input').change(function(){
$("#fileupload").submit();
});//change
When I try to submit it I get this error https://prnt.sc/l8vmhn. Please help in this regard.
Adding processData: false to your options object fixes the error.
You need to use the FormData API. Like this.
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" id="images_input">
</form>
<script>
$(document).ready(function(){
$('body').on('submit', '#fileupload', function(e){
e.preventDefault();
var formData = new FormData();
var files = document.getElementById("images_input").files;
$(files).each(function(index, value){
formData.append('files[]', value);
});
formData.append('user_id', $("#user_id_input").val());
formData.append('product_name', $("#product_name_input").val());
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
type: 'POST',
url: url,
contentType: false,
processData: false,
data: formData,
success: function(data){
alert(data);
}
});
});
$('#images_input').change(function(){
$("#fileupload").submit();
});
</script>
Finally It worked like this:
$(document).ready(function(){
$('#images_input').change(function(){
$("#fileupload").submit();
});//change
$("#fileupload").on('submit',function(event) {
event.preventDefault();
var formData = new FormData(this);
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
url: url,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
console.log(data);
}
});//
});//submit
});//ready
I have a webpage that will submit a form and redirect to another page. Is there a way to do this through jQuery, and get the response page in a callback function? So that the page won't redirect and I can show a message from the server in the same page.
I have tried the following code but it doesn't work:
$('#reset-password-form').submit(function(data){
console.log(data);
return false;
});
Also I tried following code snippet, which also didn't work:
$('#reset-password-form').submit(function(data){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
return false;
});
Please advise.
Adding HTML Section:
<form id="reset-password-form">
<div data-message-bar="">
</div>
<input type="hidden" name="username" value="dummy">
<input type="hidden" name="validationToken" value="248gf293g2793g273f972">
<input required="" name="password" type="password">
<input required="" name="passwordconfirm" type="password">
<button data-action="reset-password">Reset Password</button>
</form>
you can use this
<button id="resetpass" data-action="reset-password">Reset Password</button>
$("#resetpass").on("click", function(event){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
})
Do not return anything, returning false ll quit form submission
<form onSubmit="formSubmit()" id="reset-password-form">
<div data-message-bar="">
</div>
<input type="hidden" name="username" value="dummy">
<input type="hidden" name="validationToken" value="248gf293g2793g273f972">
<input required="" name="password" type="password">
<input required="" name="passwordconfirm" type="password">
<button data-action="reset-password">Reset Password</button>
</form>
function formSubmit(){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
});
}
remove data from function and do not return false
$(document).on('submit', '#reset-password-form',function(e){
$.ajax({
url: window.location.href,
// contentType: 'multipart/form-data',
cache: false,
// contentType: 'text/html',
contentType: 'application/x-www-form-urlencoded',
// processData: false,
type: 'POST',
data : $('#reset-password-form').serialize(),
success: function(data){
console.log(data);
console.log('form submitted.');
},
error:function(data){
console.log(data);
console.log('form error.');
},
failure: function(data){
console.log(data);
console.log('form submit failed.');
}
})
.done(function(){
alert("Done");
$('#reset-password-form')[0].reset();
});
e.preventdefault(); // stop page refresh
});
I have difficulty submitting this form:
<form action="/someurl" method="post">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple"> Apple
<input type="checkbox" class="mychoice" name="name" value="orange"> Orange
<input type="checkbox" class="mychoice" name="name" value="pear"> Pear
</form>
And the jquery bit:
$('.mychoice').click( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
But nothing happens when I click a checkbox. How can I fix this?
UPDATE: It may worth mentioning that the form is located at a bootstrap modal.
You're missing the data property.
See: JQuery $.ajax() post - data in a java servlet for an example.
If you want to send the contents of the form, then you would use Form.serialize(), but you could put whatever data you want into the property.
$(document).ready(function() {
$('.mychoice').click(function() {
var formData = $('#myForm').serialize();
console.log('Posting the following: ', formData);
$.ajax({
url: '/someurl',
data: formData,
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/someurl" method="post" id="myForm">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple">Apple
<input type="checkbox" class="mychoice" name="name" value="orange">Orange
<input type="checkbox" class="mychoice" name="name" value="pear">Pear
</form>
Try this:
$(document).ready(function(){
$('.mychoice').change( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
supply missing data
$(document).ready(function() {
$('.mychoice').click(function() {
$.ajax({
url: '/someurl',
data: $(this).closest('form').serialize(),
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
if you are trying to receive the data with the csrf token do as below :
var fd = new FormData()
fd.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value)
fd.append('field_name', $("input[name='field_name']").serialize())
will return
['field_name=9&field_name=15&field_name=10']
you will then have to parse the info in your view ( django )
Try 'change' instead of 'click', like this:
$('.mychoice').change(function(){...})
I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}
Currently using this:
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};
And it's sending my file perfectly, but I need to send 4 field values along with it. Could anyone let me know how I post:
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
Along with the file? Many thanks
function acceptimage() {
var data = new FormData();
jQuery.each($('#uploadImage')[0].files, function(i, file) {
data.append('uploadImage-'+i, file);
data.append('x', $("#x").val());
data.append('y', $("#y").val());
data.append('w', $("#w").val());
data.append('h', $("#h").val());
});
$.ajax({
url: 'upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
popup('popUpDiv');
ias.cancelSelection();
ias.update();
}
});
};