I have some problem with uploading image with bootsrap modal. The problem is that even if I have selected an image, I always get the validation error "Your upload form is empty".
Here's my form sript on view
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">User Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal" enctype="multipart/form-data">
<input type="hidden" value="" name="id_berita"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Judul Berita</label>
<div class="col-md-9">
<input name="judul_berita" placeholder="Judul Berita" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Isi Berita</label>
<div class="col-md-9">
<textarea name="isi_berita" placeholder="Isi Berita Ini" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Foto Berita</label>
<div class="col-md-9">
<input type="file" name="foto_berita" class="form-control">
<span class="help-block"></span>
</div>
</div>
<input type="hidden" value="<?php echo $id_ses; ?>" name="id_user"/>
<input type="hidden" value="<?php $tgl=date("Y-m-d");echo $tgl;?>" name="postdate"/>
<input type="hidden" value="<?php date_default_timezone_set('Asia/Taipei');$jam=date("H:i:s");echo $jam;?>" name="waktu"/>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
the javascript :
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function() {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('databerita/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_berita(){
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Berita'); // Set Title to Bootstrap modal title
}
function edit_berita(id){
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('databerita/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id_berita"]').val(data.id_berita);
$('[name="judul_berita"]').val(data.judul_berita);
$('[name="isi_berita"]').val(data.isi_berita);
$('[name="id_user"]').val(data.id_user);
$('[name="postdate"]').val(data.postdate);
$('[name="waktu"]').val(data.waktu);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Berita'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table(){
table.ajax.reload(null,false); //reload datatable ajax
}
function save(){
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('databerita/ajax_add')?>";
} else {
url = "<?php echo site_url('databerita/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
function delete_berita(id){
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('databerita/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
the controller
public function ajax_add()
{
$this->_validate();
$nmfile = "file_".time(); //nama file saya beri nama langsung dan diikuti fungsi time
$config['upload_path'] = './assets/images/'; //path folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp'; //type yang dapat diakses bisa anda sesuaikan
$config['max_size'] = '2048'; //maksimum besar file 2M
$config['max_width'] = '1288'; //lebar maksimum 1288 px
$config['max_height'] = '768'; //tinggi maksimu 768 px
$config['file_name'] = $nmfile; //nama yang terupload nantinya
$this->load->library('upload',$config);
if($_FILES['foto_berita']['name']){
if ($this->upload->do_upload('foto_berita')){
$berita = $this->upload->data();
$data = array(
'judul_berita' =>$this->input->post('judul_berita'),
'isi_berita' =>$this->input->post('isi_berita'),
'foto_berita' =>$berita['file_name'],
'id_user' =>$this->input->post('id_user'),
'postdate' =>$this->input->post('postdate'),
'waktu' =>$this->input->post('waktu'),
);
$insert = $this->m_databerita->save($data);
echo json_encode(array("status" => TRUE));
}
}
}
Thank you for your help.
Here is an example on how I used a iFrame in my modal window to upload a picture, by doing it this way I avoided having to reload the page. I do not know if you can do it with ajax, but here is a different approach.
First inside the modal body add the iFrame, notice the src is the view that contains the iframe information:
<iframe id="photo_uploader" src="/image_form" class="picture-upload-iframe"></iframe>
This is the src view for the iframe, the header.php and footer.php are in case you use multiple iframes for different purposes and they share the header and footer:
<? include('header.php');?>
<?= form_open_multipart('items/item_image_upload');?>
<input id="upload-btn" name="userfile" type="file" class="upload" />
<button class="btn btn-primary" name="submit" type="submit" class="btn">
</form>
<? include('footer.php');
Now in your controller, this is just a sample function, you can add all the other fields in the iFrame if you need to submit them when you upload the picture then do what you need to do. I just return true or false just to see if the upload was successful or not.
public function item_image_upload()
{
$data['file_name'] = false;
$data['error'] = false;
$config['allowed_types'] = 'gif|jpg|png';
$config['upload_path'] = $this->img_full;
$config['encrypt_name'] = true;
$config['remove_spaces'] = true;
$this->load->library('upload', $config);
if ( $this->upload->do_upload())
{
$upload_data = $this->upload->data();
return true;
}
return false;
}
Related
**Hi, a newbie here on Stack overflow. Uhm my submit button does not read the java script file i created and goes straight to the php file instead of validating the input fields first on the java script file. I'm not quite sure what's wrong i've been stuck here for hour.
I created the files separately. And i put the link to my javascript file at the end of my html file.
Here is my html code:
<!-- Add Student Modal-->
<div class="modal fade" id="addUserModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-md">
<div class="modal-content">
<form class="form-horizontal" id="submitUserForm" action="action/createUser.php" method="POST">
<div class="modal-header">
<div class="div-action pull pull-right" >
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div> <!-- /div-action -->
<h4 class="modal-title"> Add User</h4>
</div>
<div class="modal-body" style="max-height:650px; overflow:auto;">
<div id="add-user-messages"></div>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="full_name" name="full_name" placeholder="Full Name" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control" id="username" name="username" placeholder="Username" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="new_password" name="new_password" placeholder="Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<input type="password" class="form-control" onCopy="return false" onCut="return false" id="confirm_password" name="confirm_password" placeholder="Confirm Password" autocomplete="off" />
</div>
</div> <!-- /form-group-->
<div class="form-group">
<div class="col-sm-12">
<select class="form-control" name="level" id="level">
<option value="">~~Level~~</option>
<option value="Admin">Admin</option>
<option value="User">User</option>
</select>
</div>
</div> <!-- /form-group-->
</div> <!-- /modal-body -->
<div class="modal-footer">
<button type="submit" id="createUserBtn" name="createUserBtn" data-loading-text="Loading..." class="btn btn-success"><i class="fa fa-check"></i> Save</button>
<button type="reset" class="btn btn-danger" onClick="resetUserForm()"><i class="fa fa-eraser"></i> Reset Form</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
My Javascript Code:
$("#addUserModalBtn").unbind('click').bind('click', function() {
$("#submitUserForm")[0].reset();
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
$("#submitUserForm").unbind('submit').bind('submit', function() {
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
var full_name = $("#full_name").val();
var username = $("#username").val();
var level = $("#level").val();
var new_password = $("#new_password").val();
var confirm_password = $("#confirm_password").val();
const pasteBox = document.getElementById("#confirm_password");
pasteBox.onpaste = e => {
e.preventDefault();
return false;
};
if(full_name == "") {
$("#full_name").after('<p class="text-danger">Full name field is required.</p>');
$('#full_name').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#full_name").find('.text-danger').remove();
// success out for form
$("#full_name").closest('.form-group').addClass('has-success');
} // /else
if(username == "") {
$("#username").after('<p class="text-danger">Username field is required.</p>');
$('#username').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#username").find('.text-danger').remove();
// success out for form
$("#username").closest('.form-group').addClass('has-success');
} // /else
if(level == "") {
$("#level").after('<p class="text-danger">Please select user level.</p>');
$('#level').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#level").find('.text-danger').remove();
// success out for form
$("#level").closest('.form-group').addClass('has-success');
} // /else
if(new_password == "") {
$("#new_password").after('<p class="text-danger">Password field is required.</p>');
$('#new_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#new_password").find('.text-danger').remove();
// success out for form
$("#new_password").closest('.form-group').addClass('has-success');
} // /else
if(confirm_password == "") {
$("#confirm_password").after('<p class="text-danger">Confirm password field is required.</p>');
$('#confirm_password').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#confirm_password").find('.text-danger').remove();
// success out for form
$("#confirm_password").closest('.form-group').addClass('has-success');
} // /else
if(full_name && level && username && new_password) {
var form = $(this);
var formData = new FormData(this);
$.ajax({
url : form.attr('action'),
type: form.attr('method'),
data: formData,
dataType: 'json',
cache: false,
contentType: false,
processData: false,
success:function(response) {
if(response.success == true) {
// submit loading button
$("#createUserBtn").button('reset');
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
setTimeout(function(){window.location = window.location}, 1000);
// shows a successful message after operation
$('#add-user-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
// remove the mesages
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
// reload the manage student table
manageUsersTable.ajax.reload(null, true);
// remove text-error
$(".text-danger").remove();
// remove from-group error
$(".form-group").removeClass('has-error').removeClass('has-success');
} else if(response.success == false) {
// reload the manage member table
manageUsersTable.ajax.reload(null, true);
// reset the form text
$("#submitUserForm")[0].reset();
$("html, body, div.modal, div.modal-content, div.modal-body").animate({scrollTop: '0'}, 100);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#add-user-messages').html('<div class="alert alert-danger">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-danger").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // if
} // /success function
}); // /ajax function
} // /if validation is ok
return false;
}); // /submit product form
}); // /add product modal btn clicked
And my PHP code:
<?php
require_once 'core.php';
$valid['success'] = array('success' => false, 'messages' => array());
if($_POST) {
$full_name = $_POST['full_name'];
$username = $_POST['username'];
$new_password = md5($_POST['new_password']);
$confirm_password = md5($_POST['confirm_password']);
$level = $_POST['level'];
$status = "0";
if($new_password == $confirm_password) {
$sql = "INSERT INTO `users`(`full_name`, `username`, `password`, `level`, `status`) VALUES ('$full_name','$username','$new_password','$level', $status)";
if($connect->query($sql) === TRUE) {
$valid['success'] = true;
$valid['messages'] = "Successfully added user account.";
}else{
return false;
}
}else{
return false;
}
$connect->close();
echo json_encode($valid);
} // /if $_POST
?>
You can use one of two solutions here:
1 Prevent default
You can prevent the submit button from executing the default event action. Instead of doing this:
$("#submitUserForm").unbind('submit').bind('submit', function() {
Do it like this:
$('#submitUserForm').submit(function (event) {
event.preventDefault();
//the rest of the submittion logic goes here
}
2 Button without the submit type
You actually don't have to create a button with the submit type, to send your form data (as you use $.ajax anyway). You can create a simple button with onClick event just like this:
<button onclick="submitForm()"><i class="fa fa-check"></i> Save</button>
And then the whole function that is under the
$("#submitUserForm").unbind('submit').bind('submit', function() {
can be extracted to the new submitForm method
So this is my brand.php file
And it portrays the edit part of the brand
so in this part we can probably see how the thing will look like
<!-- edit brand -->
<div class="modal fade" id="editBrandModel" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="editBrandForm" action="php_action/editBrand.php" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><i class="fa fa-edit"></i> Edit Brand</h4>
</div>
<div class="modal-body">
<div id="edit-brand-messages"></div>
<div class="modal-loading div-hide" style="width:50px; margin:auto;padding-top:50px; padding-bottom:50px;">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>
<div class="edit-brand-result">
<div class="form-group">
<label for="editBrandName" class="col-sm-3 control-label">Brand Name: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="editBrandName" placeholder="Brand Name" name="editBrandName" autocomplete="off">
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="editBrandStatus" class="col-sm-3 control-label">Status: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="editBrandStatus" name="editBrandStatus">
<option value="">~~SELECT~~</option>
<option value="1">Available</option>
<option value="2">Not Available</option>
</select>
</div>
</div> <!-- /form-group-->
</div>
<!-- /edit brand result -->
</div> <!-- /modal-body -->
<div class="modal-footer editBrandFooter">
<button type="button" class="btn btn-default" data-dismiss="modal"> <i class="glyphicon glyphicon-remove-sign"></i> Close</button>
<button type="submit" class="btn btn-success" id="editBrandBtn" data-loading-text="Loading..." autocomplete="off"> <i class="glyphicon glyphicon-ok-sign"></i> Save Changes</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
<!-- /edit brand -->
> --this one is the end part
And this is the fetching part, wherein once you click the button from the row(example row 1), a modal(Edit Modal will likely appear), but the thing is, once the modal appear, the data that is supposed to be fetched from the row is not on that modal ;-;
<?php
require_once '../../includes/connection.php';
$brandId = $_POST['brandId'];
$sql = "SELECT brand_id, brand_name, brand_active, brand_status FROM brands WHERE brand_id = $brandId";
$result = $connect->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
?>
Now the JScript part
This part is the filler part(like getting the data and now portraying the data and filling the input boxes etc..)
function editBrands(brandId = null) {
if(brandId) {
// remove hidden brand id text
$('#brandId').remove();
// remove the error
$('.text-danger').remove();
// remove the form-error
$('.form-group').removeClass('has-error').removeClass('has-success');
// modal loading
$('.modal-loading').removeClass('div-hide');
// modal result
$('.edit-brand-result').addClass('div-hide');
// modal footer
$('.editBrandFooter').addClass('div-hide');
$.ajax({
url: 'fetchSelectedBrand.php',
type: 'post',
data: {brandId : brandId},
dataType: 'json',
success:function(response) {
// modal loading
$('.modal-loading').addClass('div-hide');
// modal result
$('.edit-brand-result').removeClass('div-hide');
// modal footer
$('.editBrandFooter').removeClass('div-hide');
// setting the brand name value
$('#editBrandName').val(response.brand_name);
// setting the brand status value
$('#editBrandStatus').val(response.brand_active);
// brand id
$(".editBrandFooter").after('<input type="hidden" name="brandId" id="brandId" value="'+response.brand_id+'" />');
// update brand form
$('#editBrandForm').unbind('submit').bind('submit', function() {
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var brandName = $('#editBrandName').val();
var brandStatus = $('#editBrandStatus').val();
if(brandName == "") {
$("#editBrandName").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandName').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#editBrandName").find('.text-danger').remove();
// success out for form
$("#editBrandName").closest('.form-group').addClass('has-success');
}
if(brandStatus == "") {
$("#editBrandStatus").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandStatus').closest('.form-group').addClass('has-error');
} else {
// remove error text field
$("#editBrandStatus").find('.text-danger').remove();
// success out for form
$("#editBrandStatus").closest('.form-group').addClass('has-success');
}
if(brandName && brandStatus) {
var form = $(this);
// submit btn
$('#editBrandBtn').button('loading');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
console.log(response);
// submit btn
$('#editBrandBtn').button('reset');
// reload the manage member table
manageBrandTable.ajax.reload(null, false);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#edit-brand-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // /if
}// /success
}); // /ajax
} // /if
return false;
}); // /update brand form
} // /success
}); // ajax function
} else {
alert('error!! Refresh the page again');
}
} // /edit brands function
Can you check the Network tab to see the result from server? You can debug your app by seeing that result.
By the way, there're two things that you may need to edit:
1/ If brandId is interger, you need to get it from $_GET by intval($_POST['brandId']) to prevent SQL Injection.
2/
if($result->num_rows > 0) {
$row = $result->fetch_array();
}
else {
$row = array();
}
your code need to return empty array if sql result is empty to avoid Undefined variable error.
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.
Aim: Continue to display any form validation errors through json callback
Problem: When I submit on the form with invalid input it shows an error message in a div element. If all inputs are valid it will process the ajax request and show a success message in a div element. After which, the form resets but the modal remain open. When I try to again validate the input in doesn't show any error message. When I try to test the valid input still the same no message shown.
In short: Ajax success function not working on the second time.
Here's my code:
Bootstrap Modal (where my form inputs placed)
<div class="modal fade" id='frmModal'>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class='close' data-dismiss='modal'>×</button>
<h4 class='title'>Add new data</h4>
</div>
<div class="modal-body">
<?php echo form_open('Employee/save',array('id'=>'frm', 'class'=>'form-horizontal')); ?>
<div id="message"></div>
<div class="form-group">
<label for='fname' class='col-md-3 control-label'>First Name:</label>
<div class="col-md-9">
<input type="text" name="fname" id='fname' class='form-control' placeholder='First Name...'>
</div>
</div>
<div class='form-group'>
<label for='lname' class='col-md-3 control-label'>Last Name:</label>
<div class="col-md-9">
<input type="text" name="lname" id='lname' class='form-control' placeholder='Last Name...'>
</div>
</div>
<div class='form-group'>
<label for='age' class='col-md-3 control-label'>Age:</label>
<div class="col-md-9">
<input type="text" name="age" id='age' class='form-control' placeholder='Age...'>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary action" type='submit'><i class='glyphicon glyphicon-floppy-disk'></i> Save Data</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
Jquery Code:
$(document).on('submit','#frm',function(e){
e.preventDefault();
var form = $('#frm');
$.ajax({
url: form.attr('action'),
type: 'POST',
dataType: 'json',
encode: true,
data: form.serialize(),
success: function(data) {
if (!data.success) {
if (data.errors) {
$('#message').html(data.errors).addClass('alert alert-danger');
}
} else {
reloadData();
$('#message').html("<span class='glyphicon glyphicon-ok'></span> " + data.message).removeClass('alert alert-danger').addClass('alert alert-success');
setTimeout(function() {
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).remove();
});
}, 3000);
$('#frm')[0].reset();
}
}
});
});
CodeIgniter Controller:
$this->form_validation->set_rules('fname','First Name', 'required|trim');
$this->form_validation->set_rules('lname','Last Name', 'trim|required');
$this->form_validation->set_rules('age','Age', 'trim|numeric|required');
if($this->form_validation->run()===FALSE)
{
$info['success'] = false;
$info['errors'] = validation_errors();
}
else
{
$info['success'] = true;
$data = array(
"firstname" => $this->input->post('fname'),
"lastname" => $this->input->post('lname'),
"age" => $this->input->post('age'),
);
$this->Employee_model->save('ci_table', $data);
$info['message'] = 'Successfully saved data';
}
$this->output->set_content_type('application/json')->set_output(json_encode($info));
}
I think I understand... The form still works but the messages do not appear? If so then try the below...
You are removing the #message element instead of clearing it... try:
$("#message").fadeTo(500, 0).slideUp(500, function() {
$(this).empty();
This way you are emptying the #message element instead of removing it completely..
Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});