Jquery detecting "enter" key press instead of mouse click - javascript

I have a problem which jquery detecting "enter" key press instead of mouse clicking on submit button when submitting a form.
On the first attempt,the submit button works well,after that it would work only with enter key.
Form codes
<a class="btn btn-xs btn-info" onclick="gModal(<?php echo $group['Group']['id'];?>,'<?php echo $group['Group']['name'];?>')"><?php echo __('Edit'); ?></a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<p id="groupId"></p>
<?php echo $this->Form->create('Group',array('class'=>'edit-group'));?>
<?php echo $this->Form->input('group_id',array('class'=>'group-id','type'=>'hidden'));?>
<?php echo $this->Form->input('name',array('class'=>'form-control group-name','type'=>'text'));?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<?php echo $this->Form->button('Save Changes',array('class'=>'btn btn-default'));?>
<?php echo $this->Form->end();?>
</div>
</div>
</div>
</div>
Jquery codes
//handle modal
function gModal(groupId,groupName){
console.log(groupId);
$('.group-name').empty();
$('.group-name').val(groupName);
$('.group-id').val(groupId);
$('#groupId').html(" ");
$('#groupId').append(groupId);
$('#myModal').modal('toggle');
}
//handle form submit
var request;
function editGroup(){
$('.edit-group').on('submit', function(event) {
console.log('clicked form');
event.preventDefault();
var $form = $(this).find("input");
var url = "<?php echo Router::url(array('plugin' => 'auth_acl','controller' => 'groups','action' => 'edit')); ?>";
var serializedData = $form.serialize();
request = $.ajax({
url: url,
type: 'post',
dataType: 'json',
data: serializedData,
});
request.done(function(data) {
console.log(data);
$('#myModal').modal('toggle');
$('#container').load('<?php echo $this->webroot; ?>auth_acl/groups');
});
request.fail(function(data) {
console.log(data);
});
});
}
$(document).ready(function($) {
editGroup();
});
I have no idea now.thanks for your time.

Replace
<?php echo $this->Form->button('Save Changes',array('class'=>'btn btn-default'));?>
This code with
<? echo $this->Form->button('Submit Form', array('class'=>'btn btn-default','type' => 'submit'));?>
Button Type should be Submit

I think you can use onchange event for representing enter event.
For example <button type="button" onchange="theFunction();">Submit</button>

Related

Why my ajax post is not working codeigniter? The page is refreshing

// save new employee record
$('#saveEmpForm').submit('click',function(){
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
});
<form id="saveEmpForm" method="post">
<div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add New Employee</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-md-2 col-form-label">Jenis</label>
<div class="col-md-10">
<input type="text" name="jenis" id="jenis" class="form-control" required>
<input type="hidden" id="input_id" name="input_id" class="form-control " value="{$input_id}">
</div>
</div>
<div class="form-group row">
<label class="col-md-2 col-form-label">Jarak</label>
<div class="col-md-10">
<input type="text" name="jarak" id="jarak" class="form-control" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
Save function in controller file
public function save(){
$data=$this->inputs_model->saveEmp();
echo json_encode($data);
}
Save function in Model
public function saveEmp(){
$data = array(
'input_id' => $this->input->post('input_id'),
'jenis' => $this->input->post('jenis'),
'jarak' => $this->input->post('jarak'),
'created_at' => date("Y-m-d h:i:sa"),
'updated_at' => date("Y-m-d h:i:sa")
);
$result=$this->db->insert('input_jenis_industri',$data);
return $result;
}
The code are as stated above, my ajax function to save the data is not working. It is not saving the data in the db. What can cause the problem?
My ajax function calls the InputPembangunan/save to save the data, then the controller try to the save data using the save() function. It is saved using the model saveEmp()
The following is incorrect, there is no click involved in a submit event
$('#saveEmpForm').submit('click',function(){
Change to
$('#saveEmpForm').submit(function(event){
event.preventDefault()// prevent normal form submit
without refreshing the page you have to call event.preventDefault() method after submit event.
replace this
$('#saveEmpForm').submit('click',function(){
with
$('#saveEmpForm').on('submit',function(){
event.preventDefault()
Change this
<button type="submit" class="btn btn-primary">Save</button>
to
<button type="button" class="btn btn-primary">Save</button>
You can onlick() method. Actually I used like this;
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" onclick="save()" class="btn btn-primary">Save</button>
</div>
than add jquery
function save() {
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
URL: "<?php echo site_url('InputPembangunan/save')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
success: function(data) {
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else {
//do something
}
},
error: function(jqXHR, textStatus, errorThrown) {
//do error form
}
});}
Use the following way,
$( "#saveEmpForm" ).submit(function( event ) {
event.preventDefault();
/** Your Existing Code ***/
var empInputId = $('#input_id').val();
var empJenis = $('#jenis').val();
var empJarak = $('#jarak').val();
$.ajax({
type : "POST",
url : "InputPembangunan/save",
dataType : "JSON",
data : {input_id:empInputId, jenis:empJenis, jarak:empJarak },
success: function(data){
$('#jenis').val("");
$('#jarak').val("");
$('#addEmpModal').modal('hide');
alert('Successfully called');
listEmployee();
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
return false;
/** Your Existing Code ***/
});
Also, you can check the jQuery reference from this link:
https://api.jquery.com/submit/#submit
Replace
$('#saveEmpForm').submit('click',function(){
with
$(document).off('submit','#saveEmpForm').on('submit','#saveEmpForm',function(event) {
event.preventDefault(); //to prevent default submit action
...rest of the code
})
also check for any errors on the browser dev tool

javascript functions stop working after writing another function in the same script

Im doing am employee leave management system. The approve and disapprove buttons were working fine in the beginning. But after writing the code to show employee details in the same modal, the approve and disapprove buttons stopped working. Now it gives error. Does anyone have an idea on whats wrong?
controller
//admin approve leave
public function approveLeave() {
$id = $this->input->post('id');
$result = $this->Admin_Model->approve($id);
if(!$result){
// something went wrong
$data = array(
"value" => $id,
"error" => true,
"msg" => "something went wrong"
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
return;
}
// approved leave
$data = array(
"value" => $id,
"error" => false,
"msg" => "successfully updated"
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
modal
<!-- Modal -->
<div class="modal fade" id="pendingLeaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Leave Request</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="leave_details" >
<p> </p>
</div>
<div class="modal-footer">
<input type="hidden" name="current_leave_id" id="current_leave_id" value="" />
<button type="button" id="declinebtn" class="btn btn-secondary" data-dismiss="modal">Decline</button>
<button type="button" id="approvebtn" class="btn btn-primary">Approve</button>
</div>
</div>
</div>
</div>
javascript
<script>
$(function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
$('#pendingLeaveRequest').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget);
var current_leave_id = button.data('id');
var modal = $(this);
modal.find('input[name="current_leave_id"]').val(current_leave_id);
});
//approve button
$('#approvebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/approveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been approved!');
}
});
});
//disapprove button
$('#declinebtn').click(function(){
var id = $('input[name="current_leave_id"]').val();
$.post(BASE_URL + 'admin/AdminDashboardController/disapproveLeave',
{'id': id},
function(result){
console.log(result);
if(result.error){
alert('try again');
}else{
alert('Leave has been disapproved!');
}
});
});
});
//show leave details on modal
$('.detailButton').on('click', function(){
var BASE_URL = "http://localhost/employeemgt/index.php/";
var leave_id = $(this).val();
var i;
$.ajax({
type: 'POST',
dataType: "JSON",
data:{leave_id:leave_id},
url: BASE_URL + 'admin/AdminDashboardController/viewRequest',
success:function(data){
console.log(data);
$('#leave_details').html("<p>" + "Name: " + data[0].user_name + "</p>" +
"<p>" + "Leave Type: " + data[0].leave_type + "</p>" +
"<p>" + "Start Date: " + data[0].leave_start + "</p>" +
"<p>" + "End Date: " + data[0].leave_end + "</p>");
$('#pendingLeaveRequest').modal('show');
},
error:function(error){
alert(error);
}});
});
</script>
view
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != "1")
{
echo '
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1">'.$row->user_name.'</h5>
<p class="mb-0 mt-0">'.$row->leave_start.' to '.$row->leave_end.'</p>
<p class="mt-0">'.$row->leave_type.'</p>
<button type="button" class="detailButton" href="<?php echo $id; ?>" data-id="'.$row->id.'" data-name="'.$row->user_name.'" data-toggle="modal" value="'.$row->id.'">View Request</button>
</div>
</li>
</ul>
';
}
}
?>
</div>
Use
$(document).on('click','#declinebtn',function(){}) instead of $('#declinebtn').click(function(){}) .
change your view code like this :
<div id="showleave">
<h4 class="mb-4">Pending Requests</h4>
<?php
foreach ($leave as $row) {
if($row->status != 1)
{
?>
<ul class="list-unstyled">
<li class="media border-bottom border-top py-3">
<img class="mr-3" src="http://via.placeholder.com/64x64" alt="Generic placeholder image">
<div class="media-body">
<h5 class="mt-0 mb-1"><?= $row->user_name ?></h5>
<p class="mb-0 mt-0"> <?= $row->leave_start.' to '.$row->leave_end ?></p>
<p class="mt-0"><?= $row->leave_type ?></p>
<button type="button" class="detailButton" href="<?php echo $row->id; ?>" data-id="<?= $row->id ?>" data-name="<?= $row->user_name ?>" data-toggle="modal" value="<?= $row->id ?>">View Request</button>
</div>
</li>
</ul>
<?php
}
}
?>
By this I think your problem will be solve
Try this.
$(document).on("click", "#approvebtn", function(event){
// your code here
});
And you can also try triggering your btn from browser console to check if it works.

Modal hide trobleshooting

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.

How do i pass the ID of row to Modal?

I have Edit button on each row. If I press Edit button on selected row I need pass ID of this row to Modal and use it in sql query to call rest of data. P.S. I tried many ways, no one of them helped and based on bootstrap.
Here is my code with Modal
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div class="table-responsive">
<table class="table" id="myTable">
<thead>
<tr class="header">
<th>#</th>
<th>Müştərinin Nömrəsi</th>
<th>Götürülən Ünvan</th>
<th>Gədilən Ünvan</th>
<th>Zəng Vaxtı</th>
<th>Sürücünün Tabel Kod</th>
<th>Təhfil aldı</th>
<th>Təhfil verdi</th>
<th>Maşın Nömrəsi</th>
<th>Qiymət</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
while($data=mysql_fetch_array($result)) // цикл вывода
{
$id = $data['id'];
echo "<tr>
<td></td>
<td>".$data['MUSHTERINOMRE']."</td>
<td>".$data['MUSHTERIHARDAN']."</td>
<td>".$data['MUSHTERIHARA']."</td>
<td>".$data['ZENGVAXTI']."</td>
<td>".$data['TABELKOD']."</td>
<td>".$data['TEHFILALDI']."</td>
<td>".$data['TEHFILVERDI']."</td>
<td>".$data['MASHINNOMRE']."</td>
<td>".$data['QIYMET']."</td>
<td><button class=\"btn btn-success\" onclick='getValue(".$id.");' data-toggle=\"modal\" data-target=\"#myModal\" contenteditable=\false\" value=".$id.">EDIT </button></td>
"; ?>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true" class="">? </span><span class="sr-only">Close</span>
</button>
<!--Here I am trying to echo ID
<h4 class="modal-title" id="myModalLabel"><?php //echo $id."ID OFaa"; ?></h4>-->
</div>
<div class="modal-body">
<?php echo $id."I NEED TO GET ID HERE "; ?>
<?php
$link = mysql_connect('localhost', 'user', 'psw');
$db_selected = mysql_select_db('my_db', $link);
$query = mysql_query("Select * from my_table where id = $id");
//var_dump($pt);
$row = mysql_fetch_array($query);
$number = $row['num'];
?>
<div class="form-group">
<label for="name" class="control-label">Müştəri Nömrə:</label>
<input type="text" class="form-control" id="num" name="num" value="<?php echo $number; ?>" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The most important thing to remember is that PHP won't execute client-side, so populating the dialog with id and editable values must be performed by the client-side language - javascript. Your only option for further server-side involvement during the editing process is to make AJAX call(s).
You will find the process a lot simpler with a "promisified" modal dialog. Rather than write something yourself, you can install install, bootStrapModal, giving you a modal that is much like the standard Bootstrap modal but behaves as an asynchronous resource.
HTML:
<script src="js/bsBetterModal.js"></script>
Build the table rows as follows :
while($data=mysql_fetch_array($result)) { // цикл вывода
$id = $data['id'];
echo "<tr data-id=\".$id.\">
<td></td>
<td class=\"mushterinomre\">".$data['MUSHTERINOMRE']."</td>
<td class=\"mushterihardan\">".$data['MUSHTERIHARDAN']."</td>
<td class=\"mushterihara\">".$data['MUSHTERIHARA']."</td>
<td class=\"zengvaxti\">".$data['ZENGVAXTI']."</td>
<td class=\"tabelkod\">".$data['TABELKOD']."</td>
<td class=\"tehfilaldi\">".$data['TEHFILALDI']."</td>
<td class=\"tehfilverdi\">".$data['TEHFILVERDI']."</td>
<td class=\"mashinnomre\">".$data['MASHINNOMRE']."</td>
<td class=\"qiymet\">".$data['QIYMET']."</td>
<td><button class=\"btn btn-success edit\">EDIT</button></td>
</tr>";
} ?>
...
Write the dialog's header as follows :
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true" class="">? </span><span class="sr-only">Close</span></button>
<h4 class="modal-title dlg-element" data-element="id"></h4>
</div>
Write each of the dialog's inputs (x8) as follows :
<label class="control-label">Müştəri Nömrə:</label>
<input type="text" class="dlg-element" data-element="mushterinomre" value="" />
Write the dialog footer as follows :
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary ok">Save changes</button>
</div>
The EDIT buttons' click handler is a little complicated. It comprises some preamble followed by a promise chain. I've made it as simple as I can by unloading the fiddly bits into a bunch of helper utilities.
jQuery(function($) {
// *** start: click handler ***
$('#myTable').on('click', '.edit', function(e) {
e.preventDefault(); // in case button attempts form submission
var $button = $(this).prop('disabled', true);
var $row = $(this).closest('tr');
var idHash = { 'id': $row.data('id') }; // <<<<<< HERE'S THE ID - expressed as a js plain object.
// From here on, everything is asynchronous, therefore performed within a promise chain.
fetchValues(idHash) // Fetch current values (onscreen values may be stale)
.then(function(valuesHash) {
return betterModal.run($('#myModal'), $.extend(valuesHash, idHash))// Open modal window, populated with current field values.
.then(function($dialog) {
// The dialog was accepted.
// `$dialog` holds a jQuery object of the dialog.
return saveValues($.extend(dialogToHash($dialog), idHash)); // Pass hash of editable field values, plus idHash, to saveValues()
})
.then(function() {
// New values were successfully saved.
// valuesHash is still in scope
updateHtmlTableRow($row, valuesHash); // Update the HTML table row with the edited values.
}, function(err) {
// Save failed
// Provide warning to user ...
return err;
})
})
.then(null, function(err) {
console.log(err);
$button.prop('disabled', false);
})
.always(function() {
$button.prop('disabled', false);
});
});
// *** end: click handler ***
var fields = ['mushterinomre', 'mushterihardan', 'mushterihara', 'tabelkod', 'tehfilaldi', 'tehfilverdi', 'mashinnomre', 'qiymet']; // 'zengvaxti' omitted
// *** start: helper utility functions ***
function fetchValues(idHash) {
return $.getJSON({
'url': 'api.php', // replace with actual url
'method': 'get',
'data': idHash
});
}
function saveValues(values) {
return $.ajax({
'url': 'api.php', // replace with actual url
'method': 'put',
'data': values
});
}
function dialogToHash($dialog) {
var hash = {};
fields.forEach(function(f) {
hash[f] = $('.'+f, $dialog).val();
});
return hash;
}
function updateHtmlTableRow($row, valuesHash) {
fields.forEach(function(f) {
$('.'+f, $row).text(valuesHash[f]),
});
}
// *** end: utility functions ***
});
Untested and sketchy in places so will need debugging. Some server-side stuff also needs to be addressed.
Hope this gives you some direction
function getValue(id)
{
$.ajax({
url:'filename.php',
method:'get',
data:'id='+id,
success: function(ret)
{
// add the returned value into the modal body
$('#modalBody').html(ret);
// show the modal
$('#myModal').show();
}
});
}

j query updating div of drop-down after inserting data

I have a drop down which i am filling from database (ss and source attached)
<div id="divmedium">
<label>Medium:</label> <a data-toggle="modal" role="button" href="#medium_m">[Add New Medium]</a>
<select data-placeholder="Select Medium" class="select-full" tabindex="2" id="media" name="media">
<option value=""></option>
<?php
$quee = 'SELECT `media_id` , `mediatype` FROM `media` WHERE `bus_id_fk` = "'. $_SESSION['bus_id_fk'].'" order by `mediatype` asc';
$rs=$DBH->query($quee);
while($row = $rs->fetch_assoc()){
echo "<option value=$row[media_id]>$row[mediatype]</option>";
}
?>
</select>
</div>
if i click on [Add New Medium] , a model appears in which i can add value.
<div id="medium_m" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="icon-paragraph-justify2"></i> Add New Medium </h4>
</div>
<!-- Form inside modal -->
<form action="#" role="form" id="med1">
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<label>First Medium</label>
<input type="text" name="fname" placeholder="Eugene" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
<button type="submit" id = "m_btn" class="btn btn-primary">Submit form</button>
</div>
</form>
</div>
</div>
click on submit form (AJAX)
$(document).ready(function(){
$('#med1').submit(function(){
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'addmedium.php',
//data: formData.serialize()
data: $(this).serialize()
})
.done(function(data){
$('#response').html(data);
if(data.status == 'success'){
$("#divmedium").html(data);
}else if(data.status == 'error'){
alert("Error on query!");
}
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
addmedium.php
<?php
session_start();
INCLUDE './config/databases.php';
header('Content-type: application/json');
$loc= $_POST['fname'];
$busid=$_SESSION['bus_id_fk'];
$sql = "INSERT INTO media (mediatype,bus_id_fk)VALUES ( '$loc','$busid' )";
//echo $sql;
if ($DBH->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $DBH->error;
}
$response_array['status'] = 'success';
echo json_encode($response_array);
exit;
?>
Now the problem is
data getting inserted in the database but i am unable to refresh the
div,
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
after clicking on Submit form , the div divmedium is disappearing.
Let me know what i am doing wrong.
I'll start from the end, if you won't mind.
after clicking on Submit form , the div divmedium is disappearing.
In your AJAX code $("#divmedium").html(data); you are replacing divmedium content with json_encode($response_array);
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
I don't see any code that should close it. Try to add data-dismiss="modal"
data getting inserted in the database but i am unable to refresh the div
Same stuff as in 3rd question, check this and edit your AJAX success callback.

Categories

Resources