This question already has answers here:
jQuery Ajax File Upload
(27 answers)
Closed 3 years ago.
I am having problem with uploading file with JavaScript Popup. This is my first experience to upload file with such JavaScript popup. I don't know how to pass the input[type:file] to the ajax function and then send to the php file for uploading.
This is the button which calls the popup:
<a class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadDocument">Upload Document</a>
<div class="modal fade" id="uploadDocument" role="dialog">
<div class="modal-dialog" style="top: 20%;">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header" style="background-color: #367FA9">
<h4 class="modal-title" id="myModalLabel" style="color:white">Upload Document</h4>
</div>
<!-- Modal Body -->
<div class="modal-body" style="padding-top: 20px; padding-right: 40px; padding-left: 40px;">
<!-- <img src="police/images/new.jpg" width="120px" height="100px"> -->
<p id="uploadMD"></p>
<form role="form" id="uploadForm" >
<div class="form-group">
<input type="hidden" name="" id="rowid" value="<?php echo $id; ?>">
</div>
<div class="form-group">
<label>Document Name</label>
<input type="text" name="" id="documentName" class="form-control">
</div>
<div class="form-group">
<label>Document</label>
<input type="file" class="form-control" placeholder="Please Select File" id="documentFile">
</div>
<div class="form-group text-center">
<button type="button" class="btn btn-primary submitBtn block" style="background-color: #367FA9" onclick="uploadDocument()" style="width: 100%;">Upload Document</button>
</div>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The javascript code is as follows:
<script>
function uploadDocument(){
var rowid = $('#rowid').val();
var documentName = $('#documentName').val();
var documentFile = $('#documentFile').val();
if(documentName.trim() == '' ){
alert('Please write file name');
$('#documentName').focus();
return false;
}else if(documentFile.trim() == '' ){
alert('Please Select File');
$('#documentFile').focus();
return false;
}else {
$.ajax({
method:'POST',
url:'upload.php',
enctype: 'multipart/form-data',
data:'&rowid='+rowid+'&documentName='+documentName+'&documentFile='+documentFile,
success: function(result){
$('#uploadForm').trigger('reset');
if(result == '1'){
$('#uploadMD').html('<span style="color:green;">Your File is uploaded. Thank you</span>');
setTimeout(function(){ window.location.reload() }, 5000);
}
else{
$('#uploadMD').html('<span style="color:red;">Uploading Problem</span>').fadeIn().delay(5000).fadeOut();
}
}
});
}
}
</script>
and the upload.php file is here:
<?php
$rowid = $_POST['rowid'];
$documentName = $_POST['documentName'];
$file_name = $_FILES['documentFile']['name'];
$file_move = move_uploaded_file($file_tmp,"../uploads/ps/".$file_name);
include "../include/configs.php";
if ($file_move) {
$q2 = "UPDATE requests SET support_doc='$file_name' WHERE slug='$id'";
$query = mysqli_query($con, $q2);
if ($query) {
echo $success = 1;
}
}
?>
Thanks in advance.
Try formdata to pass in php file ajax call
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
Thanks
Related
Im making an inventory system in laravel and I want to upload an image every products that I have. My problem is I cant upload an image. I tried my old code in uploading photo and it is not working in my current project. The upload code you see in the controller is in a laravel collective form. But now, I am using a modal and an ajax request to save the inputs into the database. Can someone know what should I do about this? Btw, my modal doesnt have a form tag because I thought forms will not work in modals. Thanks in advance!
Modal Create.
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p style="font-weight: bold;">Name </p>
<input type="text" class="form-control" id="product_name"/>
<p style="font-weight: bold;">Description </p>
<input type="text" class="form-control" id="description"/>
<p style="font-weight: bold;">Price </p>
<input type="text" class="form-control" id="currentprice"/>
{{-- <input style="text-transform:uppercase" type="text" class="form-control" id="supplier_id"/> --}}
<p style="font-weight: bold;">Supplier </p>
<select class="form-control" id="supplier_id" >
#foreach ($suppliers as $supplier)
<option value="{{$supplier->id}}">{{$supplier->name}}</option>
#endforeach
</select>
<p style="font-weight: bold;">Picture </p>
<input type="file" class="form-control" id="picture"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="add_product">Add</button>
</div>
</div>
</div>
</div>
Controller
public function store(Request $request)
{
$data = $request->all();
$data['product_name'] = ($data['product_name']);
$data['description'] = ($data['description']);
$data['supplier_id'] = ($data['supplier_id']);
$data['price'] = ($data['price']);
if ($request->hasFile('image')){
//Add new photo
$image = $request->file('image');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/' . $filename);
Image::make($image)->resize(300,300)->save($location);
$oldFilename = $products->image;
//Update DB
$products->image = $filename;
//Delete the old photo
// Storage::delete($oldFilename);
}
Product::create($data);
return response()->json($data);
}
Ajax
$(document).ready(function(){
//add
$('#add_product').click(function(e){
e.preventDefault();
var name = $('#product_name').val();
var description = $('#description').val();
var price = $('#currentprice').val();
var supplier_id = $('#supplier_id').val();
var image = $('#picture').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ url('/product') }}",
method: 'post',
data:{
product_name: name,
description: description,
price: price,
supplier_id: supplier_id,
image: image,
},
success: function (res){
console.log(res);
window.location.href = '{{route("products")}}'
}
});
});
//add
Model
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'product_name', 'quantity', 'description' ,'supplier_id', 'price', 'image',
];
public function supplier()
{
return $this->hasOne('App\Supplier');
}
}
I Can’t add a comment, that is dumb ...
Your also going to likely need to encode the image data in the json.
See How do you put an image file in a json object?
(Fixed wording)
I am posting a value on a modal dialog box and then some database operations. Now I am returning a value through
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
Is this a right way? All the database operations are performed correctly but console.log(result) does not show anything on the calling script. Something's wrong with the couple of lines above. It would be very helpful if somebody points out the error.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
And my browser tool shows,
Loading failed for the <script> with source “http://localhost/project/js/compatibility.js”.
studyChapterpdf.php:54
Use of captureEvents() is deprecated. To upgrade your code, use the DOM 2 addEventListener() method. For more help http://developer.mozilla.org/en/docs/DOM:element.addEventListener
studyChapterpdf.php:240:36
ReferenceError: fakewaffle is not defined[Learn More]
studyChapterpdf.php:492:3
Warning: Setting up fake worker.
pdf.js:1489:5
progress
Object { loaded: 131072, total: 551963 }
bootstrap-pdf-viewer.js:563:9
progress
Object { loaded: 551963, total: 551963 }
bootstrap-pdf-viewer.js:563:9
page=1 - getOperatorList: time=522ms, len=755
Found out the reason for it. There was an uncommented line left in one of the included files. So, the response was having the whole commented line as well as the actual return status==active. Fixed it. Thanks everyone for guiding.
I am working on a module where a dropdown modal has to appear after a duration of 3 mins on the page. It has an input field where digits has to be entered by the user and when he clicks on 'save', the modal should hide. Although I am getting the modal at correct time and when the digits are entered the values are being saved too but only the modal does not hides. I am just unable to figure out the reason behind it as the modal implementation is correct up to my knowledge. I am new to jquery and javascript so need suggestions and expertise of community. I am putting my code here, please have a look and any help or suggestion will be highly appreciated.
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation PIN:</p>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Save</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
// $("#spinner").show();
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
//dataType:'json',
success: function(result){
if(result == 'active')
{
$("#bt").html(result) ;
jQuery('#myModal').modal('hide');
}
else if(result == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And the ajax request being made for success,
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
echo trim('active');
Please try console.log your result, you need to know the respond.
console.log(result);
here is the problem: if(result == 'active')
Remove echo trim('active');
change to : header('Content-Type: application/json', true, 200);
echo json_encode('active')); exit();
i hope you get it.
so this is my controller:
User_Authentication_Controller:
public function login_user(){
$username = $this->input->post('txt_login_username');
$password = md5($this->input->post('txt_login_password'));
$result=$this->LogIn_Model->login($username,$password);
redirect('Pages_Controller/homepage');
}
LogIn_Model:
public function LogIn($username,$password){
$data = array(
'username' => $username,
'password' => $password
);
$query = $this->db->get_where('user_account',$data);
return $query->result_array();
}
LOGIN MODAL:
<section id="login_modal" class="modal fade" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header"></div>
<div class="modal-body" id="forms">
<div class="loginmodal-container">
<h1>Login to Your Account</h1><br>
<form class="form-horizontal" id="form_login" action="" method="POST">
<div class='error_msg'></div>
<input autofocus="autofocus" type="text" id="txt_login_username" name="txt_login_username" class="form-control" />
<input type="password" id="txt_login_password" name="txt_login_password" class="form-control" />
<button class="btn btn-primary" type="submit" name="btnLogin">Login</button>
Forgot Password?
</div>
</form>
</div>
<div class="modal-footer">
<center><button type = "submit" id="login_user" class="btn btn-danger" data-dismiss="modal" >CLOSE</button></center>
</div>
</div>
</div>
</section>
VIEW:
Login
AJAX:
$(function(){
$('#login_user').submit(function(event){
var user = $('#txt_login_username').val();
var pass = $('#txt_login_password').val();
$.ajax({
type: 'POST',
url: 'User_Authentication_Controller/login_user',
data: {
'user': user,
'pass': pass
},
dataType: 'html',
success: function(results){
if(user != user){
$('.error_msg').html('error msg');
return false;
}
}
});
});
});
ALL I WANT IS IF THERE IS AN ERROR! THE will work and the modal will not close! how will I do that with CI? Is there any possible way that just put the LogIn_Model->login(); in AJAX? please help! I need this thing badly! And in addition I want that what the user inputs and if he got it wrong when he submitted the username will still be at the textbox! how will I do that also? THank you so much for help!
Been struggling with this for about few hours. I'm attempting to have a modal drop down (Twitter bootstrap modal) that contains a form to choose a category of user. This is built in CodeIgniter. But when i try to save form's value using AJAX, the SUCCESS function won't run without alert(). I'm sorry for my bad grammar, i hope you can understand what i mean.
i need for your help...
view (kasir_halaman.php):
<div id="editModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Ubah Kasir</h3>
</div>
<div class="modal-body">
<form action="#" id="editform" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label> <span class="error" id="report1"></span>
<input type="text" id="editnama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="editemail" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" id="editkategori" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Simpan</button>
</form>
</div>
</div>
</div>
</div>
controller (kasir.php):
public function updatePetugas($id)
{
$nama_petugas = $this->input->post('nama');
$email_petugas = $this->input->post('email');
$kategori_petugas = $this->input->post('kategoripetugas');
$data = array('nama'=>$nama_petugas, 'email'=>$email_petugas, 'kategori'=>$kategori_petugas);
$update = $this->Crud->update(array('idpetugas'=>$id), 'petugas', $data);
if($update){
echo 1;
}else{
echo 2;
}
}
javascript (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/kasir/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
$(".edit").click(function(){
id = $(this).attr('id');
$.ajax({
url:'kasir/getData/'+id,
data:{send:true},
success:function(data){
$("#editnama").val(data['nama']);
$("#editemail").val(data['email']);
$("#editkategori").val(data['kategori']);
}
});
});
$("#editform").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:'kasir/updatePetugas/'+id,
data:formData,
type:'POST',
contentType: false,
processData: false,
success:function(data){
if(data==1){
$("#editModal").hide();
window.location.reload(true);
}else if(data==2){
alert('gagal');
}
}
});
alert("success!"); // if i remove this alert, the success function won't run or executed
});
});
you can solve this a few ways, what is actually happening is that you are submitting the data via ajax as well as submitting the form itself.
using e or the event
$("#editform").submit(function(e){
e.preventDefault();
or by returning false on submit
});
//alert("success!"); we can comment this out because it will work now without the alert holding the page
return false;
});
in either case you can remove your alert.