image upload using jquery ajax php mysqli - php

using ajax to upload image url in database but i got error when submit form. I want upload image url im database without page refresh. Error is GET https://api.ciuvo.com/api/analyze?url=http%3A%2F%2Flocalhost%2F&version=2.1.3&tag=threesixty&uuid=C473346A-075C-48CD-A961-F4B68EFE2C4F 400 (Bad Request)
**html code**
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});
php code
<?php
$host="localhost";
$user="root";
$pass="";
$db="test";
$con=mysqli_connect($host,$user,$pass);
mysqli_select_db($con,$db);
if (isset($_FILES["file"]["type"])) {
$dir = "images/";
$imagelocation=$dir.basename($_FILES['txtimg']['name']);
$extension = pathinfo($imagelocation,PATHINFO_EXTENSION);
if($extension != 'jpg' && $extension != 'png' && $extension != 'jpeg')
{
echo"plzz upload only jpg,jpeg And png";
}
else
{
if(move_uploaded_file($_FILES['txtimg']['tmp_name'],$imagelocation) )
{
if(mysqli_query($con,"Insert into img (img_url) values($imagelocation')"))
{
echo"SUCCESSFULLY";
}
}
else {
echo"ERROR";
}
}
}
?>

You should not call FormData object inside ajax request,
html code
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>
**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
var fdata = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: fdata,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#message").html(data);
}
});
}));
});

Related

Why PHP and Ajax does not return responses?

file upload works with ajax and php, but does not return responses! in the upload.php page is displayed:
uploaded succesfully!
html:
<form action="upload.php" method="post" enctype="multipart/form-data" id="form">
<div style="padding: 15px;">
<input type="file" name="file" id="file">
</div>
<div style="padding: 15px">
<input type="submit" value="Upload" id="upload">
</div>
</form>
ajax:
$(document).ready(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (response) {
alert(response);
}
})
})
})
php:
if (isset($_FILES['file'])) {
$file_destination = "uploads/IMG-" . date("Y-m-d") . time() . ".jpg";
if (move_uploaded_file($_FILES['file']['tmp_name'], $file_destination)) {
echo "uploaded succesfully!";
}
}
issue exist on client side use this html and java script code hope your issue will be resolved
<form action="#" enctype="multipart/form-data" id="form">
<div style="padding: 15px;">
<input type="file" name="file" id="file">
</div>
<div style="padding: 15px">
<button value="Upload" id="upload">Submit</button>
</div>
</form>
js part
$(document).ready(function () {
$('#upload').on('click', function (e) {
e.preventDefault();
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
// cache: false,
processData: false,
success: function (response) {
alert(response);
}
});
}); });

Send php variable with jQuery AJAX

I´m using an image uploading jQuery script and a short php script. They´re both included inside of the mainsite.php file.
Everything is working fine expect the transfer of the php variable $usr_id.
How can I send the php variable $usr_id via AJAX to my server sided script correctly?
php code
$user = JFactory::getUser();
$usr_id = $user->get('id');
This is my try:
jQuery(function ($) {
$(document).ready(function () {
$("#but_upload").click(function () {
var fd = new FormData();
var files = $('#file')[0].files;
var userid = <?php echo $usr_id ?>;
if (files.length > 0) {
fd.append('file', files[0]);
fd.append('userid', userid);
$.ajax({
url: 'imageupload/upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function (response) {
if (response != 0) {
$("#img").attr("src", response);
} else {
alert('file not uploaded');
}
},
});
} else {
alert("Please select a file.");
}
});
});
})
Edit: this is the form field code
<form method="post" action="" enctype="multipart/form-data" id="myform">
<div >
<input type="file" id="file" name="file" />
<input type="button" class="button" value="Upload" id="but_upload">
</div>
</form>

Can't upload multiple files with different extension?

Multiple file upload is not working if all files are not the same extension !! If I chose two png files , it works . But choosing two different file extensions (png,pdf) got empty array in $_FILES !
index.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js" > </script>
</head>
<body>
<form>
<input name="file[]" type="file" multiple/>
<input type="button" value="Upload" />
</form>
<progress></progress>
<script>
$(':button').on('click', function() {
$.ajax({
// Your server script to process the upload
url: 'upload.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
</script>
</body>
</html>
upload.php
<?php var_dump($_FILES); ?>
Result image
Hope to help you.
demo.php
<?php
if(isset($_FILES)&&!empty($_FILES)){
for($i=0;$i<count($_FILES);$i++){
echo "File ".($i+1)." is ".$_FILES["file-".$i]['name']."\n";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Updated part
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
// Full Ajax request
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'demo.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
<body>
</html>
I think you can use following code :-
<button id="upload">Upload</button>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploads.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the PHP script
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
});
});
</script>

How to pass file object with multiple attribute via jQuery ajax

I am trying to pass a file object with multiple attribute via AJAX in my WordPress application but not being able to capture them in the process function.
HTML:
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input type="file" multiple" id="photo_upload" name="photo_upload[]" class="files-data" />
<input type="button" value="Submit" onclick="uploadPhoto();" />
</form>
JS:
var formData = new FormData();
formData.append('album_title', jQuery('#album_title').val());
formData.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('.files-data'), function(i, obj) {
jQuery.each(obj.files, function(j, file){
formData.append('files[' + j + ']', file);
});
});
jQuery.ajax({
url: 'mbAlbumUploader.ajax_url,'
type: 'post',
data: formData,
dataType: 'json',
processData: false,
contentType: false,
success: function(response) {
alert(response.files);
}
});
PHP function:
function uploadPhoto() {
$fileName_str = '';
foreach($_FILES['photo_upload']['name'] as $f=>$name) {
$extension = pathinfo($name, PATHINFO_EXTENSION);
$fileName_str .= $name . ', ';
}
die(wp_json_encode(array(
'files' => $fileName_str;
)));
}
What I am doing wrong?
Try to run ajax request by click event or submit event. I made few changes this is script below. Assuming your button has update class.
HTML
<form enctype="multipart/form-data" method="post">
<input type="text" id="album_title" name="album_title" />
<input id="file" name="file[]" type="file" multiple/>
<input class="update" type="submit" />
</form>
JavaScript
$(".update").click(function(e) {
// Stops the form from reloading
e.preventDefault();
$.ajax({
url: 'upload.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('album_title', jQuery('#album_title').val());
data.append('security', mbAlbumUploader.ajax_nonce);
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
data.append('body' , $('#body').val());
data.append('uid', $('#uid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
$('#picture').val('');
$('#body').val('');
});
PHP (upload.php)
You can Access your files from $_FILES global.

Ajax Upload image

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something.
On submit doesn't do anything at all.
Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.
Here is JS.
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault()
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:$(this).serialize(),
cache:false
});
}));
and the HTMl with php.
<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
<input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
<input type="submit" name="upload" value="Upload" />
<img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>
first in your ajax call include success & error function and then check if it gives you error or what?
your code should be like this
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
$("#ImageBrowse").on("change", function() {
$("#imageUploadForm").submit();
});
});
HTML Code
<div class="rCol">
<div id ="prv" style="height:auto; width:auto; float:left; margin-bottom: 28px; margin-left: 200px;"></div>
</div>
<div class="rCol" style="clear:both;">
<label > Upload Photo : </label>
<input type="file" id="file" name='file' onChange=" return submitForm();">
<input type="hidden" id="filecount" value='0'>
Here is Ajax Code:
function submitForm() {
var fcnt = $('#filecount').val();
var fname = $('#filename').val();
var imgclean = $('#file');
if(fcnt<=5)
{
data = new FormData();
data.append('file', $('#file')[0].files[0]);
var imgname = $('input[type=file]').val();
var size = $('#file')[0].files[0].size;
var ext = imgname.substr( (imgname.lastIndexOf('.') +1) );
if(ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif' || ext=='PNG' || ext=='JPG' || ext=='JPEG')
{
if(size<=1000000)
{
$.ajax({
url: "<?php echo base_url() ?>/upload.php",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
if(data!='FILE_SIZE_ERROR' || data!='FILE_TYPE_ERROR' )
{
fcnt = parseInt(fcnt)+1;
$('#filecount').val(fcnt);
var img = '<div class="dialog" id ="img_'+fcnt+'" ><img src="<?php echo base_url() ?>/local_cdn/'+data+'"></div><input type="hidden" id="name_'+fcnt+'" value="'+data+'">';
$('#prv').append(img);
if(fname!=='')
{
fname = fname+','+data;
}else
{
fname = data;
}
$('#filename').val(fname);
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
}
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('SORRY SIZE AND TYPE ISSUE');
}
});
return false;
}//end size
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );//Its for reset the value of file type
alert('Sorry File size exceeding from 1 Mb');
}
}//end FILETYPE
else
{
imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('Sorry Only you can uplaod JPEG|JPG|PNG|GIF file type ');
}
}//end filecount
else
{ imgclean.replaceWith( imgclean = imgclean.clone( true ) );
alert('You Can not Upload more than 6 Photos');
}
}
Here is PHP code :
$filetype = array('jpeg','jpg','png','gif','PNG','JPEG','JPG');
foreach ($_FILES as $key )
{
$name =time().$key['name'];
$path='local_cdn/'.$name;
$file_ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array(strtolower($file_ext), $filetype))
{
if($key['name']<1000000)
{
#move_uploaded_file($key['tmp_name'],$path);
echo $name;
}
else
{
echo "FILE_SIZE_ERROR";
}
}
else
{
echo "FILE_TYPE_ERROR";
}// Its simple code.Its not with proper validation.
Here upload and preview part done.Now if you want to delete and remove image from page and folder both then code is here for deletion.
Ajax Part:
function removeit (arg) {
var id = arg;
// GET FILE VALUE
var fname = $('#filename').val();
var fcnt = $('#filecount').val();
// GET FILE VALUE
$('#img_'+id).remove();
$('#rmv_'+id).remove();
$('#img_'+id).css('display','none');
var dname = $('#name_'+id).val();
fcnt = parseInt(fcnt)-1;
$('#filecount').val(fcnt);
var fname = fname.replace(dname, "");
var fname = fname.replace(",,", "");
$('#filename').val(fname);
$.ajax({
url: 'delete.php',
type: 'POST',
data:{'name':dname},
success:function(a){
console.log(a);
}
});
}
Here is PHP part(delete.php):
$path='local_cdn/'.$_POST['name'];
if(#unlink($path))
{
echo "Success";
}
else
{
echo "Failed";
}
You can use jquery.form.js plugin to upload image via ajax to the server.
http://malsup.com/jquery/form/
Here is the sample jQuery ajax image upload script
(function() {
$('form').ajaxForm({
beforeSubmit: function() {
//do validation here
},
beforeSend:function(){
$('#loader').show();
$('#image_upload').hide();
},
success: function(msg) {
///on success do some here
}
}); })();
If you have any doubt, please refer following ajax image upload tutorial here
http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/
Image upload using ajax and check image format and upload max size
<form class='form-horizontal' method="POST" id='document_form' enctype="multipart/form-data">
<div class='optionBox1'>
<div class='row inviteInputWrap1 block1'>
<div class='col-3'>
<label class='col-form-label'>Name</label>
<input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
</div>
<div class='col-3'>
<label class='col-form-label'>File</label>
<input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
</div>
<div class='col-3'>
<span class='deleteInviteWrap1 remove1 d-none'>
<i class='fas fa-trash'></i>
</span>
</div>
</div>
<div class='row'>
<div class='col-8 pl-3 pb-4 mt-4'>
<span class='btn btn-info add1 pr-3'>+ Add More</span>
<button class='btn btn-primary'>Submit</button>
</div>
</div>
</div>
</form>
</div>
$.validator.setDefaults({
submitHandler: function (form)
{
$.ajax({
url : "action1.php",
type : "POST",
data : new FormData(form),
mimeType: "multipart/form-data",
contentType: false,
cache: false,
dataType:'json',
processData: false,
success: function(data)
{
if(data.status =='success')
{
swal("Document has been successfully uploaded!", {
icon: "success",
});
setTimeout(function(){
window.location.reload();
},1200);
}
else
{
swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
}
},
error:function(data)
{
swal ( "Ops!" , "error in document upload." , "error" );
}
});
}
});
$('#document_form').validate({
rules: {
"name[]": {
required: true
},
"file[]": {
required: true,
extension: "jpg,jpeg,png,pdf,doc",
filesize :2000000
}
},
messages: {
"name[]": {
required: "Please enter name"
},
"file[]": {
required: "Please enter file",
extension :'Please upload only jpg,jpeg,png,pdf,doc'
}
},
errorElement: 'span',
errorPlacement: function (error, element) {
error.addClass('invalid-feedback');
element.closest('.col-3').append(error);
},
highlight: function (element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function (element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than 2 MB');
$(document).on('change', '#photo', function() {
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
var url = './services/userProfile.php';
if (jQuery.inArray(image_extension, ['jpg', 'jpeg', 'png']) == -1) {
$('#msg').html('Invalid image file');
return false;
}
var form_data = new FormData();
form_data.append("file", property);
$.ajax({
url: url,
method: 'POST',
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
$('#msg').html('Loading......');
},
success: function(data) {
const obj = JSON.parse(data);
$('.image').attr('src', 'upload/' + obj['data']);
$('#msg').html(obj['msg']);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form" action="" method="post" enctype="multipart/form-data">
<img src="upload/imag.jpg" class="mx-auto img-fluid img-circle d-block image" alt="avatar">
<h6 class="mt-2">Upload a different photo</h6>
<label class="custom-file">
<input type="file" id="photo" name="profilePicture" class="custom-file-input">
<span class="custom-file-control">Choose file</span>
</label>
<span id="msg" style="color:red"></span>
</form>
Here is simple way using HTML5 and jQuery:
1) include two JS file
<script src="jslibs/jquery.js" type="text/javascript"></script>
<script src="jslibs/ajaxupload-min.js" type="text/javascript"></script>
2) include CSS to have cool buttons
<link rel="stylesheet" href="css/baseTheme/style.css" type="text/css" media="all" />
3) create DIV or SPAN
<div class="demo" > </div>
4) write this code in your HTML page
$('.demo').ajaxupload({
url:'upload.php'
});
5) create you upload.php file to have PHP code to upload data.
You can download required JS file from here
Here is Example
Its too cool and too fast And easy too! :)

Categories