Sending file and multiple field values in ajax - javascript

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

Related

array changes to string from javascript to php

In HTML I have:
<input name="feature[1]" value="1" type="hidden">
<input name="feature[2]" value="1" type="hidden">
<input name="feature[3]" value="1" type="hidden">
And in Javascript I have:
features = $.map($('#add-place [name^="feature"]'), function(item, index)
{
if($(item).val()=='1')
{
return $(item).attr('name').replace(/[^0-9]/g, '');
}
});
When I console.log(features) it returns an array but when I send it through ajax with new FormData in PHP I will have an string containing the numbers in the features array so if they are [1, 3] I will get 1,3 as string in PHP.
What causes this?
EDIT
form = new FormData();
features = $.map($('[name^="feature"]'), function(item, index){if($(item).val()=='1'){return $(item).attr('name').replace(/[^0-9]/g, '');}});
form.append('features', features);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
enctype: 'multipart/form-data',
cache: false,
processData: false,
contentType: false,
data: form,
complete: function(response)
{
//
}
});
Try to set processData to false on ajax query:
$.ajax({
url: '',
data: formData,
processData: false
});

file and form upload with ajax and jquery

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");
}
});

How to submit checkbox through jquery ajax?

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(){...})

Uploading data and files in one form using Ajax PHP?

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

submit a form via ajax

I have this form:
<form id="ugaForm" method="POST" action="/url/upload" target="myFrame"
enctype="multipart/form-data">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submitF()" value="upload" />
</form>
when submitting normally it works perfectly.
I need an ajax post to imitate this exact form submission.
This code doesnt work:
function submitF() {
debugger;
var mfile = $("form#ugaForm")[0].file;
var fd = new FormData();
fd.append( 'file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({ 'objectData' : fd}),
cache: false,
contentType : false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
If you are submitting something through AJAX then why are you putting it into the form. Just remove the form and keep the other things which were inside it so that it would become like this:
<div id="ugaForm">
Please select a file to upload : <input id="file" type="file" name="file" />
<input type="button" onclick="submit()" value="upload" />
</div>
And the JS would be this:
function submitF() {
debugger;
var mfile = $("#ugaForm")[0].file;
var fd = new FormData();
fd.append('file', mfile);
$.ajax({
url: 'http://localhost/url/upload/',
data: JSON.stringify({
'objectData': fd
}),
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (data) {
alert(data);
}
});
}
Hope it helps.

Categories

Resources