<a href="#" data-toggle="modal" data-target="#contact_dialog">
Change Picture
</a>
Here is my form
<form id="picture_change" class="form-horizontal" action="include/picture_change.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="vals">
<h5 style="padding-top:5px; padding-bottom:5px;">Change Picture</h5>
<input type="file" name="proimg" class="file">
<div class="input-group col-xs-12">
<span class="input-group-addon"><i class="glyphicon glyphicon-picture"></i></span>
<input type="text" class="form-control input-sm" name="proimg" disabled placeholder="Upload Image">
<span class="input-group-btn">
<button class="browse btn btn-primary input-sm" type="button"><i class="glyphicon glyphicon-search"></i> Browse</button>
</span>
</div>
</div>
</form>
Close
<script>
/* must apply only after HTML has loaded */
$(document).ready(function () {
$("#picture_change").on("submit", function(e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#contact_dialog .modal-header .modal-title').html("Result");
$('#contact_dialog .modal-body').html(data);
$("#submitForm").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#picture_change").submit();
});
});
</script>
picture_change.php
$imgFile = $_FILES['proimg']['name'];
$tmp_dir = $_FILES['proimg']['tmp_name'];
$imgSize = $_FILES['proimg']['size'];
if(!empty($imgFile))
{
$upload_dir = '../images/profile_picture/'; // upload directory
$images = $ob->imageupload($imgFile,$tmp_dir,$imgSize,$upload_dir);
if($images['ermsg'] == '')
{
$ob->upddata("update tbl_safety_pros_signup set image='".$images['userpic']."' where id='".$_SESSION['user_id']."'");
}
else {
echo $msgs=$images['ermsg'];
}
}
I try to upload a picture using bootstrap modal but file not uploaded
Other input field values are posted on action page, how to solve this problem.
Please help me.
<script>
$( '#picture_change' ).submit ( function ( event ) {
event.preventDefault ( );
event.stopPropagation ( );
var $scriptUrl = $( '#picture_change' ).attr ( 'action' );
var $postData = new FormData($('#picture_change')[0]);
$.ajax ( {
method : 'POST',
url : $scriptUrl,
data : $postData,
cache : false,
processData: false,
contentType: false,
dataType : 'json',
success : function ( data, textStatus, jqXHR ) {
if ( data.success === true ) { alert ('success'); }
else { alert ('failure'); }
},
error : function ( jqXHR, textStatus, errorThrown ) {
alert ( jqXHR.responseText );/*This returns the empty array*/
}
} );
} );
</script>
Related
I use a form that posts comments. It is short with the fields Name, Mail and Comment. However, when the site is open, through another language, for example from German, it is opened in English website.com - Duith version, website.com/en/ - english version. I get a problem and the form gives an error: "An error occurred while processing the form"
Once I debugged it turned out that there was some "redirect" from 302 to 200, how can I solve the problem with this redirection and not get this problem anymore?
POST - https://website.com/?do=comments
Status - 302 Found
GET - https://website.com/en/?do=comments
Status - 200 OK
This is my HTML
<form action="/?do=comments" method="post" id="f5feafacf21681" class="b-comment_form" data-ajax="true">
<div class="form-group form-group-25">
<div class="form">
<label class="required">Name:</label>
<input type="text" name="name" required autocomplete="name" />
</div>
<div class="form">
<label class="required">E-mail:</label>
<input type="text" name="email" placeholder="E-mail" required autocomplete="email" />
</div>
</div>
<div class="form">
<textarea name="text" rows="5" placeholder="Comment" required></textarea>
</div>
<div class="form">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="module" value="news" />
<input type="hidden" name="module_id" value="10707" />
<button type="submit" class="btn btn-primary submit">Save</button>
</div>
</form>
This is my JS
// Class for submitting forms
var Form = function() {
this.init();
};
Form.prototype = {
init: function() {
var _this = this;
$(document).on('submit', 'form[data-ajax]', function(e) {
e.preventDefault();
if ( ! $(this).hasClass('form-loading') ) {
_this.submit( $(this).attr('id') );
}
});
},
submit: function(form_id, callback) {
if ( ! form_id ) form_id = 'form';
var form = $('#' + form_id), url = form.attr('action'), btn = form.find('*[type="submit"]');
if ( form.attr('enctype') == 'multipart/form-data' ) {
var str = new FormData(form[0]),
multipart = true;
str.append('form_id', form_id);
str.append('utm_url', this_url);
str.append('utm_title', this_title);
} else {
var str = form.serialize() + '&form_id=' + form_id + '&utm_url=' + this_url + '&utm_title=' + this_title,
multipart = false;
}
$.ajax({
url: url,
type: 'POST',
data: str,
dataType: 'json',
contentType: ( multipart ) ? false : 'application/x-www-form-urlencoded; charset=UTF-8',
processData: ( multipart ) ? false : true,
beforeSend: function() {
form.addClass('form-loading');
btn.addClass('process');
},
success: function(data) {
if ( data == 'error' ) return false;
if ( callback && typeof(callback) === "function" ) {
callback(form_id, data);
} else {
if ( data.answer == 'stop' ) {
error( data.error );
} else {
if ( data.success ) success( data.success );
}
if ( data.eval ) eval( data.eval );
}
},
error: function() {
error( 'An error occurred while processing the form' );
},
complete: function() {
form.removeClass('form-loading');
btn.removeClass('process');
if ( form.find('#captcha') ) reload();
}
});
}
}, $(document).ready(function() {
Form = new Form
});
I am creating the form with checkbox, like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form7" method="POST">
<li>
<label for="Produto">Estado Resguardo</label>
<ul class="flex-outer">
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo1" name="Resguardo[]" value="Cheiro"> <span class="label-text"> Cheiro</span>
</label>
</div>
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo2" name="Resguardo[]" value="Deteriorado"> <span class="label-text">Deteriorado</span>
</label>
</div>
<div class="form-check">
<label class="toggle">
<input type="checkbox" id="Resguardo3" name="Resguardo[]" value="Molhado/Sujo"> <span class="label-text">Molhado/Sujo</span>
</label>
</div>
</ul>
</li>
<li style="float: right">
<button type="button" class="btn btn-danger btn7" data-dismiss="modal">Cancelar</button>
<button class="btn btn-success" onclick="inserir_registo6()">Gravar</button>
</li>
</form>
I am sending the data this way:
function inserir_registo6()
{
var dadosajax = {
'Resguardo' : $("#Resguardo").val()
};
$.ajax({
url: './registosobremesa',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$('.form7')[0].reset();
}
});
}
In the script with php I have as follows:
$Colaborador = $_SESSION['usuarioId'];
if (isset($_POST["Resguardo"])) {
$optionArray = $_POST["Resguardo"];
$teste = implode(',', $optionArray);
for ($i=0; $i<count($teste); $i++) {
$query = 'INSERT INTO RegistoResguardos (``Resguardo`, `Colaborador`) VALUES ( ?, ?)';
$stmt = $conn->prepare( $query );
$stmt->bind_param("ss", $teste, $Colaborador);
$stmt->execute();
}
Returns no error in the browser console, but also does not insert into the database table.
I also tried this on ajax:
function inserir_registo6()
{
var dadosajax = {
'Resguardo' : $("input[name=Resguardo]").val()
};
$.ajax({
url: './registosobremesa',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
},
success: function(result)
{
$('.form7')[0].reset();
}
});
}
But I still have the same problem of not inserting into the database.
I solved the problem by doing this:
(function ($) {$(document).ready(function(){
$("#form7").submit(function(e){
e.preventDefault();
var Utente = form7.Utente.value;
var Quantidade1 = form7.Quantidade1.value;
if (!Utente) {
alert('Preencha o campo com o Utente');
form7.Utente.focus();
return false;
}
if (!Quantidade1) {
alert('Preencha o campo com a Quantidade');
form7.Quantidade1.focus();
return false;
}
$.ajax({
type: "POST",
url: "./registoresguardos",
data: $("#form7").serialize(), // serializes the form's elements.
dataType: "json",
success: function (data)
{
$(".success_messages").removeClass('hide'); // success message
},
error: function(data){
$(".error_message").removeClass('hide'); // error message
},
complete: function()
{
$('.form7')[0].reset();
}
});
});
});
})(jQuery);
i have file upload form field,i select one gif','png' ,'jpg' means it will work,and i am select any other file .mp3,.php file it will give error like this **SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 73 of the JSON data**.i want to file type check and file size after that i want to insert the value,but don't know how to do this,i think my PHP code should be wrong...
<?php
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new_name= md5($filename.time()).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "horoscope/".$new_name)) {
// FILE TYPE CHECKING
$allowed = array('gif','png' ,'jpg');
if(!in_array($extension,$allowed) ) {
$newuser = array('photoname' => $new_name, "message" => "error");
if($_FILES['file']['size'] > 2459681 ){
$newuser = array('photoname' => $new_name, "message" => "filesize is to large");
}else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}
else{
$newuser = array('photoname' => $new_name, "message" => "success");
}
echo json_encode($newuser);
}else{
//echo "Error";
$newuser = array("message" => "file is not moving");
echo json_encode($newuser);
}
?>
<script type="text/javascript">
$(document).ready(function(){
$("#user-submit").click(function(event){
event.preventDefault();
if($("form#newUserForm").valid()){
var formData = new FormData();
var formData = new FormData($('#newUserForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
return false;
}else{
console.log("false");
}
});
});
</script>
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload</label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file" value="" aria-required="true" required="" data-msg-required="Please select your file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
Using xhr() could solve your problem... for example :-
var formData = new FormData($('#newUserForm')[0]);
$.ajax({
url: 'horoscope-check.php',
type: 'POST',
data: formData,
async: false,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
//if you want progress report otherwise you can remove this part from here to
myXhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = (evt.loaded / evt.total) * 100 ;
percentComplete = Math.round(percentComplete);
$("#progress").text(percentComplete + " %");
}
}, false);
//here
return myXhr;
},
cache: false,
contentType: false,
processData: false,
success: function (data) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
},
});
Does anyone with knowledge of OpenCart 2.0.1.1 know how I could implement the following addAttachment function found in system/libary/mail.php:
public function addAttachment($filename) {
$this->attachments[] = $filename;
}
into catalog/controller/information/contact.php - so that the default contact form can also include an attachment upload feature? I tried this but no dice.
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
unset($this->session->data['captcha']);
$mail = new Mail($this->config->get('config_mail'));
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->request->post['email']);
$mail->setSender($this->request->post['name']);
$mail->setSubject(sprintf($this->language->get('email_subject'), $this->request->post['name']));
$mail->setText(strip_tags($this->request->post['enquiry']));
$mail->addAttachment($this->request->post['file']);
$mail->send();
$this->response->redirect($this->url->link('information/contact/success'));
}
You can not directly pass file to $mail->addAttachment($this->request->post['file']);
First you need to upload file
//catalog/view/theme/default/template/information/contact.tpl
<div class="form-group">
<label class="col-sm-2 control-label" for="input-file">File</label>
<div class="col-sm-10">
<button type="button" id="button-upload" data-loading-text="Uploading.." class="btn btn-default btn-block"><i class="fa fa-upload"></i> <?php echo 'Upload'; ?></button>
<input type="hidden" name="file" value="" id="file"/>
</div>
</div>
Now we need upload script to upload file
//before footer in catalog/view/theme/default/template/information/contact.tpl
<script>
$('button[id^=\'button-upload\']').on('click', function() {
var node = this;
$('#form-upload').remove();
$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');
$('#form-upload input[name=\'file\']').trigger('click');
timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);
$.ajax({
url: 'index.php?route=tool/upload',
type: 'post',
dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$(node).button('loading');
},
complete: function() {
$(node).button('reset');
},
success: function(json) {
$('.text-danger').remove();
if (json['error']) {
$(node).parent().find('input').after('<div class="text-danger">' + json['error'] + '</div>');
}
if (json['success']) {
alert(json['success']);
$(node).parent().find('input').attr('value', json['code']);
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
}, 500);
});
</script>
Finally now you can pass attachment file to mail function
//catalog/controller/information/contact.php
if($this->request->post['file']){
$this->load->model('tool/upload');
$upload_info = $this->model_tool_upload->getUploadByCode($this->request->post['file']);
$phyname = DIR_UPLOAD.$upload_info['filename'];
$temp_name = DIR_UPLOAD.$upload_info['name'];
copy($phyname,$temp_name);
$mail->AddAttachment($temp_name);
}
$mail->send();
if(isset($temp_name)){
unlink( $temp_name );
}
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! :)