Php Upload File With JavaScript - javascript

I Try to upload with javascript I send ajax but I can't find problem my code not work where is problem ?
index.php
<input type="file" id="photoUploadFile"/>
script js
var full_photo_name = document.getElementById('photoUploadFile').value;
var photo_name = full_photo_name.substr(full_photo_name.lastIndexOf("\\")+1, full_photo_name.length);
$.ajax({
type: "POST",
url: "register_photo.php",
data: { photo_name : photo_name },
success: function(data) {
}
});
register_photo.php
upload_photo($_POST['photo_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name, $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}

change your ajax like this
var formdata = new FormData();
formdata.append( 'file', input.files[0] );
$.ajax({
url: 'register_photo.php',
data: formdata,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
In register_photo.php Use move_uploaded_file to save

In your ajax request you can use something like this.
var file_data = $('#photoUploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file_name', file_data);
$.ajax({
url: "register_photo.php",
cache: false,
data: form_data,
type: 'post',
success: function(result){
alert(result);
}
});
In your PHP code
upload_photo($_FILES['file_name']); // i upload with this function but show me error: Sorry!
function upload_photo($file_name) {
global $Root_Directory;
$target_dir = $Root_Directory. 'uploads/';
$target_file = $target_dir. $file_name;
$uploadOk = 1;
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($file_name['tmp_name'], $target_file)) {
echo 'File: '. $file_name. ' has been uploaded.';
} else {
echo 'Sorry !';
}
}
}

The best way to send the file is to submit it using a form and then receiving it on server and then processing it with php or what ever language you are using.
You have to understand that the client and the server are two different entities and sending the file name in ajax will not help.
put the input element in form.
<form id="frmsendfile" method="post" target="fileprocess.php">
<input type="file" id="photoUploadFile"/>
</form>
Now we write a javascript function that will submit the form to your server after you have browsed the file. you can add validation. I am just going to give you an idea how you can do this.
<script type="text/javascript">
var submitFile = function(){
var frm = document.forms[0];
if(frm)
{
frm.submit();
}
};
you need to call submitFile() function to send the file.

Related

How to upload more than one file with jQuery and AJAX? [duplicate]

I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});

if use ajax call for contact form submitting, header(location:/path) not working

The issue is if try to ajax call for submitting my contact form. then header("location: /path); starts not working.
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
// header("location: /contact/thankyou.html");
}
} else {
echo "Invalid captcha! Please enter again. ";
}
And yes, because header redirect is not working. I comment it out. And tried to redirect page inside ajax call like below.
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'html',
data: form.serialize(),
beforeSend: function(){
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data){
response.html(data).fadeIn();
window.location.href ="/contact/thankyou.html";
},
error: function(e){
console.log(e)
}
});
});
});
But this time, it's only redirecting inside the .status div! like in the image Normally I am displaying a error message in that div...
Hey This is wrong practice if you are using ajax req then php not able to redirect to your destination all you need to redirect in ajax success response simple us
$data = array();
if ($response->success) {
$guest = mail($serverMail, $toAdmin, $mailMessageToServer, $headers);
$server = mail($email, $toGuest, $mailMessageToGuest, $headers);
if (($guest) && ($server)) {
$data['status'] = 1; // for true
$data['message'] = "your success message"; // for true
}
}
else {
$data['status'] = 0; // for false
$data['message'] = "your error message"; // for false
}
//define content type json if you never echo like echo 'ss' then no need to this
header('Content-Type: application/json');
echo json_encode($data);exit;
and get response in ajax request dataType Json to access json array obj
$(document).ready(function() {
var form = $('#mailformpro');
var response = $('.status');
form.on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'contactform/ajax/contact.php',
type: 'POST',
dataType: 'json',
data: form.serialize(),
beforeSend: function() {
response.fadeOut();
response.fadeIn();
response.html('Loading...');
},
success: function(data) {
if (data.status == 1) {
response.html(data.message).fadeIn();
window.location.href = "/contact/thankyou.html";
}
else{
// for error
response.html(data.message).fadeIn();
}
},
error: function(e) {
console.log(e)
}
});
});
});
You have to send header as Base64 string then decode it in the service / Backend.

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Codeigniter: Uploading image through Ajax and storing in db

I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.

Reading response text in Ajax using JQuery

function upload_file(){
var file =document.getElementById('computer_image').files[0];
if(file!==null){
if(file.type==='image/jpeg' ||
file.type==='image/png' ||file.type==='image/jpg'){
$('#progressbar').show();
var formData = new FormData();
formData.append("file1", file);
$.ajax({
url: 'file_upload/ImageUpload',
type: 'POST',
headers: {"abc": "aaaaaaaaa"},
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progressHandler, false);
}
return myXhr;
},
success: function( request,data, textstatus){
alert(textstatus.getResponseHeader('abc'));
},
error:errorHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
}
else {
alert('sorry we are not accepting file other than PNG , JPEG and JPG');
}
}
}
I am using CodeIgniter Framework .Below is my PHP code to Process a file .
function ImageUpload(){
$status="";
if (empty($_FILES["file1"]))
{
$status = "sorry Something went wrong";
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
if ($status !== "sorry Something went wrong")
{
//call a function to get path name
$path="./upload";
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size' ] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['remove_spaces']=TRUE;
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
/* If directory doesn't exist than create a new .*/
if (!file_exists($path) && !is_dir($path)) {
mkdir($path);
}
/* If there is any error during upload */
if ( ! $this->upload->do_upload('file1')){
$this->output->set_status_header('400');
echo "sorry Something went wrong";
}
/*Image has been successfully Uploaded */
else{
$var = $this->upload->data('','');
echo $path.'/'.$var["file_name"].'='.$var["image_width"].
'='.$var["image_height"];
}
}
I have tried multiple flavor to get Response text but didn't success . What should be after complete to read response text .
getting null as output .
In $.ajax()'s success method first parameter will give response
Example:
$.ajax({
success: function(response, textStatus, jqXHR ){
console.log(response);
alert(response.getResponseHeader('abc'));
},
});
Check this link. It will be useful to understand $.ajax() more clearly.

Categories

Resources