how can i upload file to server using FormData? - javascript

I try to file upload to spring server using FormData object. And I hide input for type="file". However, when I submit form, it is not working. I don't know where is incorrect.
This is part of html. when some button is clicked, saveFiles() is called.
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="fileForm" id="fileForm" method="post" enctype="multipart/form-data">
<input style="display:none" type="file" id="fileSelector" name="fileSelector" multiple="" />
<input type="hidden" id="docId" value="${doc.id}" />
<div id="files"></div>
</form>
(function (global, $) {
...
initFilehandler();
...
}
function initFilehandler() {
document.querySelector('#fileSelector').addEventListener('change', handleFileSelect, false);
selDiv = document.querySelector("#files");
}
function saveFiles() {
$("form#fileForm").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
console.log(formdata);
$.ajax({
url: "/rd/file/save",
type: "POST",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert("success");
}
});
});
}

You can't just use formdata for uploading files. There's a lot of options for this one. But Im giving you a less complicated one.
Try using this plugin:
jQuery Form
I've been using that for years especially multiple file uploads. Good thing.. these plugin has callback for upload progress.. you can make a progress bar or something out of it..

Related

Uploading image with editable div

Hello I am trying to upload data to the database suing ajax call I have created a script but the problem is that I had a textarea but for some reasons i CHANGED that textarea to and editable div now my question is how do i get data from that div
<form method="POST" action="" id="post" enctype="multipart/form-data" onsubmit="return false;">
<ul>
<li>
<i class="fa fa-photo"></i> Upload A Photo / Document
<input type="file" name="image" />
</li>
</ul>
<div id='display'></div>
<div id="contentbox" contenteditable="true" name="post_dt">
</div>
<input type="submit" id="sb_art" class="btn_v2" value="Start Discussion" />
</form>
And this is my ajax script created for uploading data
$(document).ready(function(e) {
$("#post").on('submit', (function(e) {
$(document).ajaxStart(function(){
$("#load").css("display", "block");
});
$(document).ajaxComplete(function(){
$("#load").css("display", "none");
});
var form = this;
var content = $("#contentbox").html();
$.ajax({
url : "url/demo/forums/post_forum",
type : "POST",
data : {new FormData(this), content: content},
contentType : false,
cache : false,
processData : false,
success : function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
form.reset();
}
});
}));
});
You're using the correct method to get the content from the editable element: html(). Your issue is how you're sending the data. When sending binary data through FormData you cannot place that inside an object to be encoded. Instead, the additional data must be added to the FormData using append(). Try this:
$("#post").on('submit', function(e) {
$("#load").show();
var form = this;
var formData = new FormData(this);
formData.append('content', $("#contentbox").html());
$.ajax({
url: "http://tfsquare.com/demo/forums/post_forum",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
$("#data_update").prepend($(data).fadeIn('slow'));
form.reset();
$("#contentbox").empty();
},
complete: function() {
$("#load").hide();
}
});
});
Also note that I changed your use of ajaxStart() and ajaxComplete() to use the complete method. Defining new global AJAX handlers on every submit of the form is rather redundant.

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

Formdata append file upload is not working in codelgniter,Getting error

All I am trying to do is upload files using ajax to my CodeIgniter based website.But i cannot get file field value in controller.I am getting message like "Undefined index: 'file_1'"
How to solve this issue?
Form
<form method="post" enctype="multipart/form-data">
<input type="file" id="file_1" name="file_1" value="" class="field1" />
<input type="button" onclick="up_img()" value="Upload" />
</form>
Javascript:
<script type="text/javascript">
function up_img()
{
formdata = false;
var imgfile = document.getElementById("file_1");
formdata = new FormData();
formdata.append("file_1",imgfile.files[0]);
$.ajax({
url: "<?php echo base_url(); ?>index.php/save_project_upload/",
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
}
Controller:
function save_project_upload()
{
echo $upfile_name = $_FILES['file_1']['name'];
}
If you do a print_r( $_FILES ) are you getting any content?
Also, be aware that this is not supported by IE8 and earlier.
You could also try to do:
var formData = new FormData($('#yourformID')[0]);
EDIT:
formData.append('file_1', $('input[id="file_1"]')[0].files[0]);
Might also solve your problem, by adding [0] to the DOM element.

Upload image using ajax and form submitting

I want to upload an image to the server using Ajax, but there is a problem. Would somebody please help me what is wrong here. I could submit the image using submit form but not ajax.
here is my code:
html:
<div id="uploadPic" onclick="getFile()">
Select a photo to upload
</div>
<form name="myForm" id="avatar_form" enctype="multipart/form-data" method="post" action="">
<div style='height: 0px;width:0px; overflow:hidden;'>
<input id="upfile" class="botpic" type="file" name="avatar" value="upload" required="" onchange="sub1()">
</div>
</form>
javascript:
function getFile(){
document.getElementById("upfile").click();
}
function sub1(){
var photo = document.getElementById("upfile");
var file = photo.files[0];
data = new FormData();
data.append('file', file);
$.ajax({
url: 'url',
data: data
enctype: 'multipart/form-data',
processData: false, // do not process the data as url encoded params
contentType: false, // by default jQuery sets this to urlencoded string
type: 'POST',
success: function ( output ) {
document.getElementById('picTmp').innerHTML = output;;
}
});
}
PHP code:
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
.......
}
The first thing I notice is that you're missing a comma after the data parameter declaration. That might be your only issue.
$.ajax({
url: 'url',
data: data,
enctype: 'multipart/form-data',
//etc...
What's the name of your PHP script? That's what you should specify as 'url':
url: 'script_name.php',
Maybe this plugin could help you
Jquery Form
I had a lot of problem making from myself and with this plugin everething works, just try, this
$('form').ajaxForm(function() {
alert("Thank you for your comment!");
});
I would guess that without using preventDefault() method in your script,
you submit the form to the same page using action="" and method="post", thus never entering your $.ajax();
I've done something like this
$('#query_projects').submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
var request = $.ajax({
type: 'POST',
url: 'query_tab_projets.php',
mimeType:'application/json',
dataType:'json',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert(JSON.stringify(data,null,4));
},
error: function(msg){
alert(JSON.stringify(msg,null,4));
}
});
});
where #query_projects is my form id
Finally I found where the problem is. Maybe it is useful for others struggling with ajax uploading a file.Now it is working perfectly.
The solution is:
In the php code, all the ["avatar"] should be replaced with ["file"] as we are sending the file specified as file in ajax.

Javascript pass input file to PHP

I don't want to upload a file using Javascript, I just want to pass by Ajax the file to a PHP file, and in the PHP make the validations I want, plus use the move_uploaded_file function. Is it possible?
$('#the_button').on("click", function(){
var image = $('#image').val() == "" ? null : $('#image').files;
$.ajax({
type: "POST",
url: "insert.php?type=image",
data: image,
enctype: 'multipart/form-data',
success: function(data) {
alert(data);
}
});
}
This returns 'undefined' for the #image.
$('#image').files[0] also returns undefined.
$('#image')[0].files returns [object FileList] -> is it correct?
try this plugin
http://blueimp.github.io/jQuery-File-Upload/
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
}
});
You can not upload files via AJAX.
Usual way is to set the target of your form to a hidden iframe.
Something like this.
<form target="myHiddenIframe" method="post" enctype="multipart/form-data">
//your form elements here.
</form>
<iframe name="myHiddenIframe" id="myHiddenIframe" style="display: none;" />
Submit the form to achieve what you want.

Categories