Am trying to upload an image to images folder using ajax but its not working
when i choose an image then the image should upload to my folder in local hard drive and further i will use that.
Please help me
My Code is :
SCRIPT
$(document).ready(function() {
$('#pathAbout,#path,#pathWork').change(function(){
if($(this).val() !=""){
$.ajax({
type: "POST",
url: "imageLoad.php",
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
success: function(msg){
alert(msg);
}
});
}
});
});
</script>
HTML
<form method="POST" action="tabs.php?page=HOME" enctype="multipart/form-data">
<table>
<tr>
<td><label>Choose Image</label></td>
<td><input type="file" id ="pathAbout" name="imgPath" /></td>
</tr>
</table>
</form>
PHP
if(!empty($_POST)) {
if((isset($_POST['name']) && $_POST['name'] != '') || (isset($_POST['type']) && $_POST['type'] != '') ||(isset($_POST['tmp_name']) && $_POST['tmp_name'] != ''))
{
$name = $_POST['name'];
$type = $_POST['type'];
$tmp_name = $_POST['tmp_name'];
$extension = strtolower(substr($name, strpos($name , '.') +1));
if(($extension == 'png' || $extension == 'jpeg' || $extension == "jpg")&&($type == "image/png" || $type == "image/jpeg" || $type == "image/jpg"))
{
$location = 'images/';
if(move_uploaded_file($tmp_name,$location."$name"))
{
echo "Loaded";
} else {
echo "Error occured";
}
} else {
echo "Unsupported file format";
}
} else {
echo "Please choose a file";
}
} else {
echo "No Information found";
}
This is my code but nothing is happening when i choose a file
If you want you can use Uploadify here you can also see demo and for sample code for eg-
$(function() {
$("#file_upload").uploadify({
'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onUploadStart' : function(file) {
$("#file_upload").uploadify("settings", "someOtherKey", 2);
}
});
});
$("#image_upload2").uploadify(uploadifyBasicSettingsObj);
uploadifyBasicSettingsObj.onUploadSuccess = function(file, data, response)
{
$('.tempImageContainer2').find('.uploadify-overlay').show();
/* Here you actually show your uploaded image.In my case im showing in Div */
$('.tempImageContainer2').attr('style','background- image:url("../resources/temp/thumbnail/'+data+'")');
$('#hidden_img_value2').attr('value',data);
}
The HTML code:
<div class="boxWrapper tempImageContainer2" data-image-container-id="2">
<input type="file" accept="gif|jpg" name="image2" style="" id="image_upload2"/>
<input type="hidden" value="" name="image[]" id="hidden_img_value2">
<input type="hidden" name="upload_path" value="" id="upload_path2" class="upload_path">
<div class="uploadify-overlay">Change</div>
<a class="remove-pic-link" href="javascript:void(0)" style="display:none">Remove</a>
</div>
It is not possible to upload an image directly using AJAX, but there are some libraries that create dynamic iframes to accomplish this.
Check out this one, which I have used in several projects: valums.com/ajax-upload. It even comes with example serverside code for several PHP application frameworks.
You can't upload file using AJAX , you need to use a trick consisting a 'iframe' and the web form , also some javascript.
This link may help you.
HTML
<div class="field">
<label class="w15 left" for="txtURL">Logo:</label>
<img id="logoPreview" width="150px" height="150px" src='default.jpg' />
<input class="w60" type="file" name="txtURL" id="txtURL" />
</div>
JQuery
$('#txtURL').on('change', function(){
$.ajaxFileUpload({
type : "POST",
url : "ajax/uploadImage",
dataType : "json",
fileElementId: 'txtURL',
data : {'title':'Image Uploading'},
success : function(data){
$('#logoPreview').attr('src', data['path']);
},
error : function(data, status, e){
alert(e);
}
});
});
Ajax controller:
public function uploadImage()
{
$status = "";
$msg = "";
$filename='';
$file_element_name = 'txtURL';//Name of input field
if (empty($_POST['title'])){
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error"){
$targetPath = ''.date('Y').'/'.date('m').'/';
if(!file_exists(str_replace('//','/',$targetPath))){
mkdir(str_replace('//','/',$targetPath), 0777, true);
}
$config['upload_path'] = $targetPath;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 150000;
$config['file_name']=time(); //File name you want
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($file_element_name)){
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else{
$data = $this->upload->data();
$filename = $targetPath.$data['file_name'];
}
//#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg,'path'=>$filename));
}
Add Ajaxfileupload.js
You can't upload an image directly using AJAX
The answer is in response to this:
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
Related
I am trying to upload a pic for which I have used the following code.
HTML:(I want that pic to be uploaded without submitting the form.)
<form id="chapThumb" method="post" action="<?php echo base_url();?>index.php/Admin/createChapter" enctype="multipart/form-data">
<input type="file" name="thumbpic" id="thumbpic">
<p class="FS12">Upload a thumbnail Image for the Chapter</p>
<input type="text" class="form-control" name="chname" placeholder="Enter chapter name"><br>
<input type="button" class="form-control" name="thumb" value="Upload" id="thumb">
<input class="dp-btn2" type="submit" value="Create" name="submit">
</form>
JQuery:
$(document).ready(function(){
$("#thumb").on('click',function(){
var x = $("#thumbpic").val();
console.log('x:'+x);
jQuery.ajax({
type: 'POST',
dataType: "json",
url: "<?php echo base_url();?>index.php/Admin/createChapterThumb",
data: {"thumbpic":x},
success:function(response){
console.log("response"+response);
var msg = response.message;
var stat = response.status;
var da = response.da;
console.log('msg:'+msg+',stat:'+stat+',da:'+da);
if(stat == 'success'){
//some code
}
else{
//some code
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus); console.log("Error: " + errorThrown);
}
});
});
});
Controller:
public function createChapterThumb(){
if($this->input->is_ajax_request()) {
$this->load->model('DPModel');
$config['upload_path'] = 'uploads/chapters/thumbs/temp';
$config['file_name'] = 'chapThumb';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('thumbpic'))
{
$data['status'] = 'error';
$data['message'] = $this->upload->display_errors();
echo json_encode($data);
}
else
{
$data['status'] = 'success';
$data['message'] = $this->upload->data();
echo json_encode($data);
}
exit;
}
//$res = $this->customerModel->insertChapter();
}
When upload button is clicked am getting the following error in console:
msg:You did not select a file to upload.,stat:error
Change the line $config['upload_path'] = 'uploads/chapters/thumbs/temp'; in controller function to below.
$config['upload_path'] = './uploads/chapters/thumbs/temp/';
Also, set the file permission of the folder to 777.
I have created a jQuery/AJAX script for file uploading and I handle the upload with PHP. It works perfectly with a progress bar and validations. There is one issue however, I cannot get any response text that I have set in PHP and encoded it using json_encode();, but don't get any response and get this instead:
<div class="upload-div">
<form method="post" enctype="multipart/form-data" class="upload_form" >
<label for="file" id="file_label" class="file-label"><i class="fa fa-plus"></i> إضافة صور<input type="file" name="files[]" id="file" multiple="" accept="image/*" /></label>
<input type="submit" id="upload_files" name="submitUpload" value="رفع الصور" />
</form>
<div class="progress">
<div class="bar"></div>
</div>
<div class="status-message"></div>
<div class="images-previews"></div>
<div id="next_step"></div>
<span class="submit-buttons">
<i class="fa fa-arrow-right"></i> الرجوع
<form method="post"><input type="submit" name="submitNoPics" value="التقدم بدون صورة" /></form>
</span>
</div>
<script src="js/upload.js"></script>
<script src="js/jquery.form.min.js"></script>
{"message":"Successfully uploaded 1 files!"}
As you can see the message I want to display is on the last line of code but it doesn't show alone. It shows with the whole HTML document. I will post my HTML and PHP code below, because I am new to Ajax and I am struggling. Please help me if you can and explain because I don't just want to get it done, I want to actually understand how and why this is not working. Thank you.
PHP:
<?php
//file upload
$extensions = array('jpeg', 'jpg', 'png', 'gif');
$dir = 'user-uploads/';
$count = 0;
$imgCounter = 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files'])){
for($x = 1; $x <= 8; $x++){
unlink('user-uploads/img'.$listingID.'-'.$x.'.jpg');
unlink('user-uploads/img'.$listingID.'-'.$x.'.png');
unlink('user-uploads/img'.$listingID.'-'.$x.'.gif');
}
mysqli_query($connectionDB, "DELETE FROM ad_image_tbl WHERE ad_id = $listingID");
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name ){
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
/* skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;
*/
switch($_FILES['files']['type'][$i]){
case 'image/jpeg' : $ext = '.jpg'; break;
case 'image/png' : $ext = '.png'; break;
case 'image/gif' : $ext = '.gif'; break;
default : $ext = '';
}
if($ext == ''){
echo errorMessage('<li>الملف المرفق لا يعتبر صورة</li>');
$error_message = 'الملف المرفق لا يعتبر صورة';
$message = array('message'=>'Attached file is not a valid image file.');
exit();
}
else{
// now we can move uploaded files
if($count <= 7 ){
$listingImage = $dir.'img'.$listingID.'-'.$imgCounter.$ext;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $listingImage))
mysqli_query($connectionDB, "INSERT INTO ad_image_tbl VALUES('$imgCounter', '$listingID', '$listingImage')");
$imgCounter++;
$count++;
}
}
}
$message = array('message'=>'Successfully uploaded '.$count.' files!');
echo json_encode($message);
}
?>
jQuery/AJAX:
$(function() {
/* variables */
var fileInput = document.getElementById('file');
var fileCount = fileInput.files.length;
if(fileCount > 8){
fileCount = 8;
}
var bar = $('.bar');
var progress = $('.progress');
/* submit form with ajax request using jQuery.form plugin */
$('.upload_form').ajaxForm({
/* set data type json */
dataType:'JSON',
/* reset before submitting */
beforeSend: function() {
bar.width('0%');
progress.css('display', 'block');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
},
/* complete call back */
complete: function(message){
// var responseMessage = $.parseJSON(data.responseText);
progress.css('display', 'none');
document.getElementById('next_step').innerHTML = '<form method="post"><input type="submit" name="uploadSubmit" value="الانتهاء" /></form>';
console.log(message)
}
});
});
Why could you use a plugin to handle upload.
dropzone.js
You can get response as below
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
alert(response);
}
};
});
I wanna update profile picture of user that has logged in to my website.
I use ajax, jquery, php to update data, in order to update data without refresh the page.
This code just working to upload image into folder, but when I use this code to update image from database, it only sent null into database.
jquery and ajax script
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
And it's the php syntax
upload.php
<?php
require_once 'koneksi.php';
if($_POST)
{
$id_user= $_POST['id_user'];
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif', 'bmp'); // valid extensions
$path = '../images/ava/'; // upload directory
try {
// get uploaded file's extension
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
// can upload same image using rand function
$final_image = rand(1000,1000000).$img;
// check's valid format
if(in_array($ext, $valid_extensions))
{
$path = $path.strtolower($final_image);
if(move_uploaded_file($tmp,$path))
{
echo "<img src='$path' />";
}
else
{
echo 'invalid';
}
$update = $db_con->prepare("UPDATE tb_users SET image=:img WHERE id_user=:id_user");
$update->bindparam(":id_user", $id_user);
$update->bindparam(":img", $image);
$update->execute();
$count = $update->rowCount();
if($count>0) {
echo "success";
}else {
echo "can't update!";
}
}
}catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
HTML syntax
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<form id="form-ava" action="../config.inc/upload.php" method="post" enctype="multipart/form-data">
<input type="hidden" id="id_user" name="id_user" value="<?php echo $row->id_user;?>">
<input id="ava-img" type="file" name="image" value="<?php echo $row->image;?>"/>
<input id="button" type="submit" value="Simpan" name="update"></br>
</i> Batal
</form>
<div id="err"></div>
<script type="text/javascript">
$("#form-ava").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "../config.inc/upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview-ava").html(data).fadeIn();
$("#form-ava")[0].reset();
$("#hidden-list").hide();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
</script>
I found two errors in your code in proses.php
<?php include 'koneksi.php';
$foto = #$_POST['foto'];
$id = #$_POST['id'];
$update = $db->prepare("UPDATE tb_users SET foto=:foto WHERE id=:id");
$update>bindParam(":id", $id);
$update->bindParam(":foto", $foto);
$update->execute();
if($update->rowCount() > 0) {
echo "success";
}
?>
the error messages would be very helpful, but at the very least you are missing a - in $update>bindParam(":id", $id);, so it should be $update->bindParam(":id", $id);
you did the same thing again with $update>rowCount() should be $update->rowCount()
update: I see you edited your question to fix those, but still haven't posted the errors you're receiving. Were those tpyos in your question, or are you progressively fixing your code?
still, it looks like you're missing a closing curly brace } in this statement:
if($update>rowCount() > 0) {
echo "success";
?>
also, why are you silencing notices with #$_POST? if those values are empty, then do you really want to be updating the table?
I have an ajax upload script which i will post below. It will upload any file with any extention. I want it to only upload .png files but i dont know how to do that.
Here are my files:
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
PHP:
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Sorry, i'm new and code blocks wont work for me. If someone could update, that would be great.
Client side
change your input file field this only works for modern browsers IE10+
Google Chrome 8.0+ and Firefox 4.0+
<input type="file" size="60" name="myfile" accept="image/png" />
PHP
$ext = pathinfo( $file_name , PATHINFO_EXTENSION );
if(strtolower($ext) == 'png' && $_FILES["file"]['type'] == "image/png")
{
// upload file
} else{
// not allowed
}
You can check file extension or mime type at server side.
// check extension
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
// return error
}
// or check file mime type
if (mime_content_type($_FILES['myfile']['name']) !== 'image/png') {
// return error
}
Example php:
$output_dir = "uploads/";
$upload_name = $_POST['upload_name'];
if(isset($_FILES["myfile"])) {
// Check upload errors
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
return;
}
// Check extensions
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
echo "Error: Only .png files are allowed";
return;
}
// Upload file
$file_name = $upload_name . $info->getExtension();
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $file_name);
echo "Uploaded File :" . $file_name;
}
I am wondering that , why my page is getting refresh while i am using ajax to upload image, i tried to debug the problem, but did'nt find,
Here is the Controller function,
public function uploadImage() {
if(isset($_FILES['header_image'])) {
$config['upload_path'] = 'public/images/global/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'b_'.random_string('alnum', 5);
$this->upload->initialize($config);
if($this->upload->do_upload('header_image')) {
echo json_encode(array('status'=>"1", 'image_url'=>$this->upload->file_name));
} else {
$upload_error = array('error' => $this->upload->display_errors());
echo json_encode(array('status'=>"0",'upload_error'=>strip_tags($upload_error['error'])));
}
exit;
}
$this->template->render();
}
While my view uploadImage.php is look like,
$(document).ready(function() {
$('#header_image').on('change', function(){
$("#frm_global").ajaxForm({
success: function(data) {
res = $.parseJSON(data);
if(res.status == 1){
var html = "<img src='<?=base_url();?>path/"+res.image_url+"' class='preview' width='100' height='100' />";
html+= "<input type='hidden' id='image_url' name='image_url' value='"+res.image_url+"' >";
$("#preview").html(html);
$("#frm_global").ajaxFormUnbind();
}
if(res.status == 0){
$("#frm_global").ajaxFormUnbind();
}
}
}).submit();
});
});
<form name="frm_global" id="frm_global" enctype="multipart/form-data">
<div id="preview" style="float:left">
</div>
<div style="float:left">
<div style="margin-top:25px">
<input type="file" name="header_image" id="header_image"/>
<input style="margin-left:100px" onclick="" type="image" id="upload_header" src="any path" />
</div>
</div>
</form>
Sorry i think i didn't get your question properly.
But for submitting you can try like this
$("#theForm").ajaxForm({
url: 'server.php',
type: 'post',
success:function(data)
{
//do what you want to
}
});
may it helps you