Upload image using ajax and form submitting - javascript

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.

Related

upload image from multiple form with ajax and php

in PHP page with multiple form tag to register user information.
using ajax to collect data and post to register PHP page now i want to upload image to server folder but i failed.
my html code:
<label for="upimage" class="btn btn-sm btn-primary mb-75 mr-75">Upload Image</label>
<input type="file" id="upimage" hidden accept="image/*" name="image"/>
Javascript Code:
let data1 = document.getElementById('data1').value,
data2 = document.getElementById('data1').value,
data3 = document.getElementById('data1').value,
upimage = document.getElementById('upimage').value;
$.ajax({
url:"././newregister.php",
method:"POST",
data:{action:'newregister', data1:data1, data2:data2,
data3:data3, upimage:upimage},
success:function(data){
alert(data);
}
});
newregister php code:
$uploads_dir = './uploads';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
echo "Sucsess";
}
else
{
echo "Error" . $_FILES["file"]["error"] ;
}
ERR: Undefined index: file in .... on line ....
Given by POST method uploads
Be sure your file upload form has attribute enctype="multipart/form-data" otherwise the file upload will not work.
Your current solution lacks enctype, that's why your file is not getting uploaded to the server and therefore isn't in the superglobal variable $_FILES.
As ferikeem already said. Wrap your data in a FormData Object and send it that way.
See: https://stackoverflow.com/a/5976031/10887013
JavaScript
let fd = new FormData();
fd.append("you_file_key_here", $("#upimage")[0].files[0]);
fd.append("data1", $("#data1")[0].value);
fd.append("data2", $("#data2")[0].value);
fd.append("data3", $("#data3")[0].value);
$.ajax({
url: "././newregister.php",
method: "POST",
data: fd,
processData: false,
contentType: false,
success: function(data){
alert(data);
}
});
$_FILES["file"], here is your problem.
In $_FILES array key "file" doesn't exists. As I see you need to change $_FILES["file"] with $_FILES["upimage"].

Receiving HTML post from cropit with Python Flask

I am new to web development and have a small web app where I need a user to upload a cropped image. My issue is that I cannot fetch the image that is send in the jQuery post request.
My Javascript and HTML looks like this:
function sendImage(imageData) {
var info = {}
info.upload = imageData
info.gender = gender.value
info.ageGroup = ageGroup.value
$.ajax({
type: "POST",
url: "/uploadToS3",
data: info,
enctype: 'multipart/form-data',
dataType: "json",
success: console.log("image written")
});
}
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<button class="export">Export</button>
</div>
Here is the python code handling the post request
#app.route('/uploadToS3', methods = ['POST'])
def uploadToS3():
username = session.get('username')
image = request.files.get('upload')
gender = request.form['gender']
ageGroup = request.form['ageGroup']
fileName = getNewFileName()
print(image)
return redirect('/')
image prints as 'None', the issue seems to be in the line where I request the upload parameter. The data being posted to Flask (taken from the form data) is upload:data:image/png;base64 and a very long string. So it looks like it posting correctly.
Any hints would be greatly appreciated
According to the answers to this question you can't just use an simple object as data when passing files.
For that purpose you have to do the following:
var formData = new FormData();
formData.append("gender",gender.value); // And so on...
formData.append("upload",$("#file")[0].files[0]); // When your file input has id="file"
$.ajax({
type: "POST",
url: "/uploadToS3",
data: formData,
enctype: 'multipart/form-data',
// And so on...
});

jQuery FormData and files

I'm attempting to do ajax file upload. When i check the variable form_data it is blank?
<form action='ajax_image_upload/process.php' method='post' enctype='multipart/form-data' class='upload_form'>
<textarea name='description' placeholder='Type Default Video Description'></textarea>
<span>
Channel Image: <input type='file' name='image' />
</span>
<input name='__submit__' type='submit' value='Upload'/>
</form>
var container = $(".upload_form");
var form_data = new FormData();
form_data.append('image', container.find("form > span").children("input[name='image']"));
var post_url = container.children("form").attr("action"); //get action URL of form
//jQuery Ajax to Post form data
$.ajax({
url : post_url,
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
mimeType: "multipart/form-data"
}).done(function(res){
});
How can I solve this?
The issue is because you need to append the binary data from the file input to the FormData, not the jQuery object. Try this:
var fileData = container.find("form > span").children("input[name='image']")[0].files[0];
form_data.append('image', fileData);
Obviously, if there are multiple inputs, or multiple files within the input, you'll need to loop through them and append them individually.

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

$_FILES["sendImageFile"]["name"] return null value [duplicate]

This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 6 years ago.
I want to upload image without page loading, here sendImageFile is the value of file field. Now when I trying to upload any file from file_upload_to_user.php but every time $_FILES["sendImageFile"]["name"] returns null value.
<form enctype="multipart/form-data" method="post" name="img_upload_form" id="img_upload_form" action="file_upload_to_user.php">
<input name="sendImageFile" id="sendImageFile" type="file" accept=".png, .jpg, .jpeg"/>
<input type="submit" name="photoUploadToSend" id="photoUploadToSend" style="display:none" />
</form>
JS
var frm = $('#img_upload_form');
frm.submit(function (ev) {
var sendImageFile = document.getElementById("sendImageFile").value;
var to_hash = "000000000";
var dataString = 'sendImageFile='+sendImageFile+"&to_hash="+to_hash;
$.ajax({
type:"POST",
url:"file_upload_to_user.php",
data:dataString,
cache:false,
success: function(info) { alert(info);}
});
}
document.getElementById("sendImageFile").onchange = function change(){
// Upload image
document.getElementById("photoUploadToSend").click();
}
If you want to upload a file with ajax then you have to do it with FormData. And to send a formData with jQuery you need to send two other properties to to disable sending wrong stuff. so it's just easier to use fetch...
var form = document.getElementById("img_upload_form")
var fd = new FormData(form)
fetch("file_upload_to_user.php", {method: 'POST', body: fd})
To send a formdata with jQuery ajax you have to set this two:
processData: false,
contentType: false,
You need to use formData
var formData = new FormData();
formData.append('file', $('#sendImageFile')[0].files[0]);
formData.append('to_hash',"000000000");
$.ajax({
url : 'file_upload_to_user.php',
type : 'POST',
data : formData,
processData: false,//prevent automatic processing
contentType: false,//do not set any content type header
success: function(info) { alert(info);}
});

Categories