jQuery: submit form on change - javascript

I'm trying to submit a form with a field element when a user clicks a button. I'm using the change function, which is called after a file has been chosen. The problem is that the form data is submitted without the field data. How can I make it submit the form after the field data is set?
The below code works fine if I call it with submit instead of change.
<form method="POST" action="public/index.php/students/edit/49" accept-charset="UTF-8" id="fileform" enctype="multipart/form-data">
<input type="button" onclick="document.getElementById('fileupload').click(); return false;" value="UPLOAD CV / RESUME" class="add" />
<input type="file" id="fileupload" style="visibility: hidden;" />
</form>
<script>
$('#fileupload').change(function()
{
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: "POST",
processData: false,
contentType: false,
url: "{{URL::action('StudentController#addDocument')}}",
data: formData,
});
request.done(function( msg ) {
console.log( msg );
});
request.fail(function( jqXHR, textStatus ) {
console.log(textStatus );
});
});
</script>

You can try
$.fn.serializefiles = function() {
var obj = $(this);
/* ADD FILE TO PARAM AJAX */
var formData = new FormData();
$.each($(obj).find("input[type='file']"), function(i, tag) {
$.each($(tag)[0].files, function(i, file) {
formData.append(tag.name, file);
});
});
var params = $(obj).serializeArray();
$.each(params, function (i, val) {
formData.append(val.name, val.value);
});
return formData;
};
then in function ajax
var request = $.ajax({
type: "POST",
processData: false,
contentType: false,
url: "{{URL::action('StudentController#addDocument')}}",
data: $('#fileform').serializefiles(),
});
You want to upload a file or some files by ajax, you have to write a function above

this in $('#fileupload').change( ... ) refers to input element, formData expects a form element, try this:
$('#fileupload').change(function () {
var formData = new FormData(this.form);
...
});
you also need to add name attribute to your file input.
Request then looks like:
...
Content-Disposition: form-data; name="file"; filename="FILE_NAME"
Content-Type: CONTENT_TYPE
...

Related

file upload with formData returns undefined file array

im getting undefined from print_r($_POST), it's posting on the same php page.
Array ( [file] => undefined )
Edited - added part where it calls the upload_banner function
HTML
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
</form>
JS
$('#submit_btn').click(function(e){
e.preventDefault();
var date = document.getElementById('datepicker').value;
var title = document.getElementById('title').value;
var content = document.getElementsByClassName('note-editable')[0];
if(date == "" || title == "") {
alert("Please fill in the required fields");
return false;
}
else {
var cfm = confirm("Confirm Submit Changes?");
if(cfm === true)
{
var editarea = content.innerHTML;
$.post ("functions/add_upcoming.php",{date: date,title: title,sm_content: editarea},
function(data) {
});
upload_banner();
}
else
{
return false;
}
}
});
function upload_banner() {
var form_data = new FormData($('#banner_form')[0]);
form_data.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: "upcomingevents.php?p=73",
contentType: false,
processData: false,
dataType: 'json',
data: form_data,
type: 'post',
success: function(data) { },
contentType: false,
processData: false
});
}
json as datatype cause im returning arrays from php side, did not post additional code cause im already getting issue at the file upload part
PHP
if(isset($_POST['file'])) {
print_r($_POST);
exit();
}
am i doing anything wrong here?
The FormData is set up incorrectly, should be :
var form_data = new FormData( );
form_data.append('file', $('input[type=file]')[0].files[0]);
Are you sure the url refered by the ajax is correct?
Why is there query param (?p=73) as you're doing post and not get.
Finaly, try to print the response through
success: function(data) { alert(JSON.stringify(data))},
You're function isn't even being called considering you don't have the submit button for the handler to run.
It should be like:
<form enctype="multipart/form-data" id="banner_form" class="form-horizontal" role="form" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input id="file" name="file" type="file" class="filestyle" accept="image/jpeg,image/gif,image/png">
<input type="submit" id="submit_btn"/>
</form>
Also you have a syntax error in your JS, there is no need for the second set of }); to close the click handler.
JSFiddle:
https://jsfiddle.net/sggf82am/2/

files do not post when javascript submits form

I have an image upload form which is submitted by a javascript but the file data is not being submitted. I have looked at examples of how to fix this with ajax but cannot find any examples that address it with the javascript submit that I am using.
<td>New Photo<br>
<div id="editphoto">
<form id="editphoto" enctype="multipart/form-data" method="post" action="editphoto.php">
<input type="hidden" name="employeeid" value="<?php echo $listing[$k]["employeeid"] ?>">
<input type="file" name="file2">
<input type="submit" value="Submit">
</form></div></td>
<script>
$('#editphoto form').submit(function(){
var data=$(this).serialize();
$.post('editphoto.php', data , function(returnData){
$('#editphoto').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
Files cannot be serialized. You can use FormData To submit a file using jQuery.
$('#editphoto form').submit(function(){
var formData = new FormData();
formData.append('file2', $('input[type=file]')[0].files[0]);
// append other form-data to formData object
var otherData = $(this).serialize();
$.each( otherData , function(key, field){
formData.append(field.name, field.value);
});
// post form
$.ajax({
url: 'editphoto.php',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function( returnData ) {
$('#editphoto').html( returnData)
}
});
return false; // stops browser from doing default submit process
})

send file using ajax with other type of input

i already had a form which uses ajax to save the the data to the database. so i have this sample
Html code
<input id="product_name" type="text" >
<input id="product_description"/>
<input id="product_img" type="file" accept="image/*"/>
<button id="btnSave">Save</button>
Javascrip Code
$("#btnSave").click(function(){
p_name = $("#product_name").val();
p_des = $("#product_description").val();
p_image = $("#product_img").prop('files')[0];
data = {
'product_name':p_name,
'product_description':p_des
}
$.post('url_here',data,function(response){
console.log(response);
});
});
i do have this info Jquery input.files equivalent but i cant make it passed as a $_FILE for php.Please give me some example codes combining the input type text and file without using the form tag and using jquery ajax.
You can use FormData:
document.getElementById('btnSave').addEventListener('click', function() {
var fd = new FormData();
fd.append('product_name', document.getElementById('product_name').value);
fd.append('product_description', document.getElementById('product_description').value);
fd.append('product_name', document.getElementById('product_img').files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url_here');
xhr.addEventListener('load', function(e) {
console.log(xhr.responseText);
});
xhr.send(fd);
});
UPDATE
Since you want to use jQuery AJAX (I have no idea why, since it was not prepared to use XHR2), you can workaround by telling it to not process the data parameter, e.g:
$('#btnSave').click(function() {
p_name = $('#product_name').val();
p_des = $('#product_description').val();
p_image = $('#product_img').prop('files')[0];
var data = new FormData();
data.append('product_name', p_name);
data.append('product_description', p_des);
data.appned('product_img', p_image);
$.ajax({
url: 'url_here',
data: data,
processData: false,
contentType: false,
type: 'POST',
success: function(response){
console.log(response);
}
});
});

Preventing jQuery AJAX call from sending form data twice

I'm having some trouble in preventing jquery's ajax call from submitting form data twice.
The form has two fields:
<form id="calendarform_id" method="post" onsubmit="find_schedule()" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
</form>
The javascript that makes the ajax call is:
function get_form_data_uid($form){
var form_data_array = $form.serializeArray();
var form_array = {};
$.map(form_data_array, function(n, i){
form_array[n['name']] = n['value'];
});
form_array['uid'] = localStorage.getItem('uid');
return form_array;
}
function find_schedule()
{
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
$(formId).submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
}
Looking at the requests made to the server I see that there is no uid field. I have also tried placing the code retrieving the form data and the user id (uid) as well as the request variable inside the submit handler, but the uid is still not submitted.
Why?
Edit:
I've removed the onsubmit field from the form and moved the submit handler outside the function:
Updated javacript code:
$("#calendarform_id").submit(function(e){
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
// Prevent implicit submit
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
Edit #1:
I've added the uid as a hidden field to the form:
<form id="calendarform_id" method="post" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
<input id="user_id" type="hidden" name="uid" value="<token_from_local_storage>">
</form>
For some reason apparently I cannot debug code that is within the .submit handler; a simple alert isn't shown either.

javascript formdata via ajax

I am trying to upload a file via AJAX and PHP. I have a HTML form as below:
<form method="post" id="sectiononeform" name="sectiononeform" enctype="multipart/form-data">
<div class="clearfix">
<input type="text" name="customHeading1" id="customHeading1" class="span10" value=""/>
</div>
<!-- Gets replaced with TinyMCE, remember HTML in a textarea should be encoded -->
<div class="clearfix">
<textarea id="elm1" name="elm1" rows="15" class="xxlarge" cols="80" style="width: 80%">
</textarea>
</div>
<div class="clearfix">
<input type="file" name="file1" id="file1" class="span10" />
</div>
<div class="clearfix">
<div class="actions">
<input type="submit" id="saveSection1" name="saveSection1" value="Submit" />
<input type="reset" name="resetSection1" value="Reset" />
</div>
</div>
</form>
My jquery code is as follows:
$(document).ready(function(){
$("#saveSection1").click(function(e){
e.preventDefault();
var formdata = false;
/*function showUploadedItem (source) {
var list = document.getElementById("image-list"),
li = document.createElement("li"),
img = document.createElement("img");
img.src = source;
li.appendChild(img);
list.appendChild(li);
} */
if (window.FormData) {
formdata = new FormData();
//document.getElementById("btn").style.display = "none";
}
var len = document.getElementById("file1").files.length, img, reader, file;
for (var i = 0 ; i < len; i++ ) {
file = document.getElementById("file1").files[i];
if (!!file.type.match(/image.*/)) {
if (window.FileReader ) {
reader = new FileReader();
/*reader.onloadend = function (e) {
showUploadedItem(e.target.result, file.fileName);
};*/
reader.readAsDataURL(file);
}
if (formdata) {
alert("form data");
formdata.append("customHeading1", document.getElementById("customHeading1").value);
formdata.append("elm1", document.getElementById("elm1").value);
formdata.append("custsection1", 1);
formdata.append("venue_id", document.getElementById("venue_id").value);
formdata.append("images[]", file);
alert(formdata);
}
}
}
var params = $("form#sectiononeform").serialize();
//alert("params" + params);
params = params + "&custsection1=1&venue_id=" + $("#venue_id").val() + "&formdata=" + formdata;
//alert(params);
$.ajax({
type: 'POST',
url: 'saveCustomSectionData.php',
data: formdata,
success: function(data){
alert(data);
}
});
});
});
My issue is that when I don't use the file input type, I can just serialize the form values and send it through AJAX. Since I am using file input type, I am using formdata and appending information to it. Is this the right way to send data. I am not getting any response back from php, neither can i see any request in firebug. Instead I get some vague error as "Illegal operation on WrappedNative prototype object". Any suggestions?
You can use AJAX to send files. Using new FormData() and the $.ajax method with contentType: false, processData: false.
Check this out:
<script type="text/javascript">
$(document).ready(function()
{
$("#ajax").hide();
$("#botonancho").click(function()
{
if ($("#ficherocsv").val() =="")
{
alert(" Seleccione 1º el archivo ");
}
else
{
var data = new FormData();
data.append( 'file', $( '#ficherocsv' )[0].files[0] );
$("#botonancho").val("Por favor... espere.");
$("#ajax").html("<img src='imagenes/ajax-indicator.gif' alt='Indicador Actividade Ajax' />").show();
$.ajax({
url: 'importacion.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data)
{
$("#ajax").html("");
$("#ajax").html(data).fadeIn("slow",function()
{
$("#ajax").delay(1500).fadeOut("slow",function()
{
$("#botonancho").val("IMPORTAR Alumnos CSV (codificación UTF-8)");
$("#ficherocsv").val("");
$("#ajax").hide();
});
});
}
});
}
});
});
</script>
Regards.
so far as i know this is not possible due to security reasons.
but it is possible to use something like jquery.form.js (available from http://jquery.malsup.com/form/) and is quite easy to implement.
they do also provide some nice examples for you to try aswel.

Categories