I'm using form steps with jquery steps and jquery validate. But when i try to upload image, it show "Undefined Index: picture". When i try without both of jquery, it works.
register.php
<form class="form-contact contact_form" id="register" enctype="multipart/form-data">
<input name="remarks" id="remarks" type="hidden" value="SMP">
<div class="row">
<h3> Profil </h3>
<section>
<div class="col-md-3">
<p class="katapen">NISN</p>
</div>
<div class="col-md-9">
<input class="form-control required number" name="nisn" id="nisn" type="text" placeholder='Please enter your NISN'>
</div>
<div class="col-md-3">
<p class="katapen">School Status</p>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="A" id="primary-radio" required>
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">A</p>
</div>
</div>
<div class="col-md-4">
<div class="switch-wrap d-flex justify-content-between">
<div class="primary-radio">
<input type="radio" name="schoolstatus" value="B" id="primary-radio">
<label for="primary-radio"></label>
</div>
<p class="spasidrradio">B</p>
</div>
</div>
</section>
<h3> Personal Data </h3>
<section>
<div class="col-md-3">
<p class="katapen">Full Name</p>
</div>
<div class="col-md-9">
<input class="form-control required" name="fullname" id="fullname" type="text" placeholder='Please enter your fullname' required>
<div class="col-md-3">
<p class="katapen">Picture</p>
</div>
<div class="col-md-9">
<input class="form-control" name="picture" id="picture" type="file">
</div>
</section>
test.js
var former = $("#register");
former.validate
({
errorPlacement: function errorPlacement(error, element)
{
element.before(error);
},
rules:
{
}
});
former.children("div").steps
({
headerTag: "h3",
bodyTag: "section",
transitionEffect: "slideLeft",
onStepChanging: function (event, currentIndex, newIndex)
{
former.validate().settings.ignore = ":disabled,:hidden";
return former.valid();
},
onFinishing: function (event, currentIndex)
{
former.validate().settings.ignore = ":disabled";
return former.valid();
},
onFinished: function (event, currentIndex)
{
studentregister();
}
});
function studentregister()
{
var remarks = document.getElementById('remarks');
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: $('#register').serialize(),
dataType: 'json',
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};
base_url + "register/" + remarks.value will be route to saveregister and remarks.value as uri2
This is my adm.php
public function saveregister()
{
$uri1 = $this->uri->segment(1);
$uri2 = $this->uri->segment(2);
$uri3 = $this->uri->segment(3);
$uri4 = $this->uri->segment(4);
//var post from json
$p = json_decode(file_get_contents('php://input'));
$_log = array();
if($uri2 == "SD")
{
}else if($uri2 == "SMP"){
$p = $this->input->post();
$folder = "./upload/register/";
$allowed_type = array("image/jpeg", "image/jpg", "image/png", "image/gif",
"audio/mpeg", "audio/mpg", "audio/mpeg3", "audio/mp3", "audio/x-wav", "audio/wave", "audio/wav","video/mp4", "application/octet-stream", "application/pdf", "application/doc");
$file_name = $_FILES['picture']['name'];
$file_type = $_FILES['picture']['type'];
$file_tmp = $_FILES['picture']['tmp_name'];
$file_error = $_FILES['picture']['error'];
$file_size = $_FILES['picture']['size'];
$ekstensi = explode("/", $file_type);
$time = date("Yhsms");
$filename= $this->db->escape($p['nisn'])."_".$time .".".$ekstensi[1];
#move_uploaded_file($file_tmp, $folder .$filename);
}else{
}
}
If you look at the jquery serialize() Documentation, it says the data from file select elements is not serialized. You could use FormData to send file input through ajax :
function studentregister()
{
var remarks = document.getElementById('remarks');
var form = $("#register")[0]; // use the form ID
var formData = new FormData(form);
$.ajax
({
type: "POST",
url : base_url + "register/" + remarks.value,
data: formData,
dataType: 'json',
contentType: false, // required
processData: false, // required
success: function(data)
{
if(data.log.status == '1')
{
swal
({
title: "",
type: "success",
text: data.log.ket,
confirmButtonClass: "btn-success",
confirmButtonText: "Con"
},function(){
});
}else{
swal
({
title: "",
type: "error",
text: data.log.ket,
confirmButtonClass: "btn-default",
confirmButtonText: "Back"
},function(){
});
}
$("#register")[0].reset();
},
error: function(ts)
{
alert(ts.responseText);
}
});
return false;
};
Related
Help, try upload a image from a form with js, using Ajax,FormData
MODAL FORM,
FORM USED TO COLLECT THE INFORMATION AND THE IMAGE
<div id="modal-editar" style="display: none">
<form id="pais-editar" >
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Nombre Empresa</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[pais]" id="pais-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">MONEDA (Abreviatura)</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="text" name="conf[moneda]" id="moneda-ed" required="">
</span>
</div>
</div>
<div class="Listar-table">
<div class="Listar-table-dato">
<span class="">Bandera</span>
</div>
<div class="Listar-table-dato">
<span class="Forms-table">
<input type="file" name="bandera" accept="image/x-png,image/gif,image/jpeg" />
</span>
</div>
</div>
<div id="mensaje-editar">
</div>
<div class="Contendedor-filtro-der Contener-btn" style="text-align: center;">
<input type="submit" class="Btn-naranja-auto" name="" value="Guardar Pais">
</div>
</form>
</div>
JS FUNCTION, THIS TAKES THE INFORMATION FROM THE FORM AND SEND IT USING AJAX
$('body').on('submit', '#pais-editar', function(e) {
e.preventDefault();
$('#modal-editar').iziModal('startLoading');
var data = new FormData();
$.each($('#bandera'), function(i, obj) {
$.each(obj.files, function(j, file) {
data.append('bandera', file);
});
});
otradata = $('#pais-editar').serializeArray();
$.each(otradata, function(key, input) {
data.append(input.name, input.value);
});
data.append('conf[id]', pais_id);
data.append('conf[opc]', 'pais-editar');
$.ajax({
url: 'libs/ac_configuracion',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
dataType: 'json',
success: function(data) {
$('#modal-editar').iziModal('stopLoading');
if (data.status == true) {
$('#modal-editar').iziModal('resetContent');
iziToast.success({
title: 'Correcto',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
lista_paises(1);
} else {
iziToast.error({
title: 'Error',
message: data.msg,
position: 'center',
overlay: true,
displayMode: 1,
target: '#mensaje-editar',
pauseOnHover: false
});
}
}
});
});
and finally this is my php code that receives the data, uploads the image and edits the information
$codigo = explode('-', $data['id']);
#$nombre_adjunto = $_FILES['bandera']['name'];
#$tmp_adjunto = $_FILES['bandera']['tmp_name'];
$folder_gastos = '../banderas';
$trozo1=explode(".", $nombre_adjunto);
$nombre_archivo= 'bandera_'.($data['pais']).'.'.end($trozo1);
#$target_path = $folder_gastos.'/'.$nombre_archivo; //Indicamos la ruta de destino, así como el nombre del archivo
move_uploaded_file($tmp_adjunto, $target_path);
$dats = ['nombre_pa' => $data['pais'], 'moneda_pa' => $data['moneda'] , 'bandera' => $nombre_archivo];
$nuevo = $db
->where('Id_pa', $codigo[1])
->update('paises', $dats);
if ($nuevo) {
$msg['status'] = true;
$msg['msg'] = 'País Editado';
} else {
$msg['status'] = false;
$msg['msg'] = 'No se ha podido editar el país';
}
echo json_encode($msg);
it's supposed to work, the text information arrives but the image does not
i am a begineer of laravel and ajax i can do the system well in core php. i just converted to laravel.
i creating simple crud using laravel with ajax but i don't know how call the path through ajax request. what i tried so fat i attached below.pls give me the solution for it.
Screen shot of folder structure
this is view part. i name it
list.blade.php
div class="row">
<div class="col-sm-4">
<form class="card" id="frmProject">
<div class="form-group" align="left">
<label class="form-label">First name</label>
<input type="text" class="form-control" placeholder="first_name" id="first_name" name="first_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Last name</label>
<input type="text" class="form-control" placeholder="last_name" id="last_name" name="last_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div class="card" align="right">
<button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
</div>
</form>
</div>
Ajax Call
function addProject() {
if ($("#frmProject").valid())
{
var _url = '';
var _data = '';
var _method;
if (isNew == true) {
_url = '/student';
_data = $('#frmProject').serialize();
_method = 'POST';
}
else {
_url = '/student',
_data = $('#frmProject').serialize() + "&project_id=" + project_id;
_method = 'POST';
alert(project_id);
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
data: _data,
beforeSend: function () {
$('#save').prop('disabled', true);
$('#save').html('');
$('#save').append('<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i>Saving</i>');
},
success: function (data) {
$('#frmProject')[0].reset();
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Add');
get_all();
var msg;
console.log(data);
if (isNew)
{
msg="Brand Created";
}
else{
msg="Brand Updated";
}
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
Student Controller
class StudentController extends Controller
{
public function index()
{
$data['students'] = Student::orderBy('id','desc')->paginate(5);
return view('student.list',$data);
}
public function create()
{
}
public function store(Request $request)
{
$student = new Student([
'first_name' => $request->post('first_name'),
'last_name'=> $request->post('lastname'),
'address'=> $request->post('address')
]);
]);
$student->save();
return Response::json($student);
}
routes
Route::get('/', [App\Http\Controllers\StudentController::class, 'index']);
Route::get('student', [App\Http\Controllers\StudentController::class, 'index']);
Route::post('student', [App\Http\Controllers\StudentController::class, 'store'])->name('student.store');
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("#email").val();
var pswd = $("#pwd").val();
var address = $("#address").val();
$.ajax({
url: "url",
type:'POST',
data: {_token:_token, email:email, pswd:pswd,address:address},
success: function(data) {
printMsg(data);
}
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
console.log(msg.success);
$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
Please use csrf token
i want to upload a profile image of a user to the server and i'm stuck at ajax upload of image
all my form data are posting to database including the image name but the file is not uploading to the server
my view is
//form
<form id="example-form" method="post" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="row">
<div class="col m12">
<div class="row">
<div class="input-field col m12 s12">
<input id="name" name="name" type="text" placeholder="Full Name" class="required validate">
</div>
<div class="input-field col s12">
<input id="email" name="email" type="email" placeholder="Email" class="required validate">
</div>
<div class="input-field col s12">
<input id="phone_number" name="phone_number" type="tel" placeholder="Phone Number" class="required validate">
</div>
<div class="input-field col m6 s12">
<input id="address" name="address_city_village" type="text" placeholder="Address City Village">
</div>
<div class="input-field col m6 s12">
<input id="state" name="address_state" type="text" placeholder="State">
</div>
<div class="input-field col s12">
<input id="password" name="password" type="password" placeholder="Password" class="required validate">
</div>
<div class="input-field col s12">
<input id="confirm" name="confirm" type="password" placeholder="Confirm Password" class="required validate">
</div>
<div class="file-field input-field col s12">
<div class="btn teal lighten-1">
<span>Image</span>
<input type="file" name="image">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="waves-effect waves-green btn blue">Submit</button>
</div>
</form>
//ajax
$(document).on("click", ".agent-add", function () {
var agent_id = $(this).data('id');
$('form').submit(function(event) {
event.preventDefault();
$.ajax
({
url: '{{ url('/agents') }}',
type: 'POST',
data: {
"_method": 'POST',
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"phone_number": $('input[name=phone_number]').val(),
"address_city_village": $('input[name=address_city_village]').val(),
"address_state": $('input[name=address_state]').val(),
"image": $('input[name=image]').val(),
"password": $('input[name=password]').val()
},
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
});
my controller is
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
User::create($request->all());
return redirect('agents')->with('Success', 'Agent Added');
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
}
}
}
i guess i'm missing something in ajax posting, but i couldn't figure it out
i dd($request->all());
the result is
array:9 [▼
"_token" => "heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM"
"name" => "fwe"
"email" => "sanjiarya2112#gmail.com"
"phone_number" => "4444422555"
"address_city_village" => "sgf"
"address_state" => "gfdgsdf"
"password" => "ffffff"
"confirm" => "ffffff"
"image" => UploadedFile {#208 ▼
-test: false
-originalName: "Screenshot (8).png"
-mimeType: "image/png"
-size: 135920
-error: 0
path: "C:\wamp\tmp"
filename: "php47F2.tmp"
basename: "php47F2.tmp"
pathname: "C:\wamp\tmp\php47F2.tmp"
extension: "tmp"
realPath: "C:\wamp\tmp\php47F2.tmp"
aTime: 2017-01-24 06:14:40
mTime: 2017-01-24 06:14:40
cTime: 2017-01-24 06:14:40
inode: 0
size: 135920
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\wamp\tmp\php47F2.tmp"
}
]
i checked the C:\wamp\tmp\php47F2.tmp enen there i din't find the image
looking forward for much needed help
thank you
Try using the FormData in ajax while you upload a file.
Just try this
$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
OR
You can try with this jQuery library
https://github.com/malsup/form
EDIT
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
$user=User::create($request->all());
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using the array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
$user->image= public_path().'/uploads/'. $name;
$user->save();
}
return redirect('agents')->with('Success', 'Agent Added');
}
}
Try something like this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'route_url',
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
});
Just me or does your <input type="file"> not have a "name" attribute? Therefore the server is not receive the file data from the post?
EDIT:
After you insert the record into the database, you then handle the file uploading - but you never then update the record with the files name.
*Just confirm that the file was uploaded.
I will explain using a simple example.
HTML:
<form id="header_image_frm" method="POST" action="">
<input type="file" name="header_image" id="header_image" value="Upload Header Image">
</form>
JS: (Properties of ajax called contentType, processData must)
<script>
$(document).ready(function() {
$('#header_image').change(function() {
let formData = new FormData($('#header_image_frm')[0]);
let file = $('input[type=file]')[0].files[0];
formData.append('file', file, file.name);
$.ajax({
url: '{{ url("/post/upload_header") }}',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType: false,
processData: false,
cache: false,
data: formData,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
});
</script>
Laravel / PHP:
public function upload(Request $request) {
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = public_path() . '/images/' . $filename;
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/' . $filename;
} else {
echo = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
}
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);
},
});
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! :)