Onclick event not opening Bootstrap modal - javascript

I am trying to open a bootstrap modal on button click but it appears my code is not running. Here is my code snippet:
<button type="button" class="btn btn-xs btn-default" onclick="openViewUserModal(<?= $users['userid']; ?>); return false;">
<span class="glyphicon glyphicon-eye-open"></span>
</button>
function openViewUserModal(id) {
var data = {
"id": id
};
jQuery.ajax({
url: "includes/viewUser.php",
method: "POST",
data: data,
success: function(data) {
jQuery('body').append(data);
jQuery('#viewUserModal').modal({
backdrop: 'static',
keyboard: false,
show: true
});
}
});
}
Clicking on the button does not elicit a response. What am I doing wrong?

this should work, mark the echo statement. i think its a typo.
<button type="button" class="btn btn-xs btn-default" onclick="openViewUserModal('<?php echo $users['userid']; ?>');">
<span class="glyphicon glyphicon-eye-open"></span>
</button>

Assuming that the output of <?= $users['userid']; ?> is a string then you'll need to wrap it in quotes:
onclick="openViewUserModal('<?= $users['userid']; ?>'); return false;"
That being said, using inline event handlers is a very outdated method which should be avoided possible. Use unobtrusive event handlers instead. You can provide arguments to that event handler through data attributes, something like this:
$('.btn').click(function() {
$.ajax({
url: "includes/viewUser.php",
method: "POST",
data: {
"id": $(this).data('userid')
},
success: function(data) {
$('body').append(data);
$('#viewUserModal').modal({
backdrop: 'static',
keyboard: false,
show: true
});
}
});
});
<button type="button" class="btn btn-xs btn-default" data-userid="<?= $users['userid']; ?>">
<span class="glyphicon glyphicon-eye-open"></span>
</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

How to get $_SESSION value updated when jscript confirm and call PHP by AJAX

After lots of trying, I need help. After a click event, i perform checking on data exist in my database and use jscript to pop a confirmation box.
How to get it works as I click cancel, its not showing any value I set on confirm.php?
Confirm with OK and Cancel
jscript code:
if($row_count2 > 0)
{
if ($row2["Status"] == "REJECTED")
{
<script type="text/javascript">
if (!confirm('Lot No has been REJECTED before.. Double confirm to add the Lot No!!')) {
var option = "NO";
$.ajax({
type: "POST",
url: "confirm.php",
data: "value="+option,
success: function (data) {
alert(data);
}
});
}
</script>
}
}
$ll = $_SESSION['Confirm'];
echo "<script type='text/javascript'>alert('$ll');</script>";
if ($row_count2 < 1 || ($_SESSION['Confirm'] = "YES"))
{
//my insert query is here...
}
And this is inside confirm.php:
<?php
session_start();
$xx = $_REQUEST["value"];
$_SESSION['Confirm'] = $xx;
echo "<script type='text/javascript'>alert('$xx');</script>";
?>
I'm expecting to get $_SESSION['Confirm'] value as NO
By default $_SESSION['Confirm'] value is YES
alert(data) shows that $xx is NO but when I put alert for $_SESSION['Confirm'] value on if condition
before my insert query $_SESSION['Confirm'] value still remain YES
Instead of using JScript alert which is really troublesome.. I end up using modal popup alert..
<div class="modal-content">
<div class="modal-header bg-secondary">
<button type="button" class="close" data-dismiss="modal"></button>
<h4 class="modal-title text-white ">Confirmation</h4>
</div>
<div class="modal-body">
<div class="box-body">
<form class="form-signin">
<label for="txtLotNo" class="mr-sm-2 ml-sm-4">Lot No : '.$lotNo.' has been REJECTED before.. Double confirm to add the Lot No!!</label>
<br>
<div class="text-center">
<button type="button" id="getAdd" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myAdd" data-id="YES'.$lotNo.$newLotNo.'" >YES</button>
<button type="button" id="getAdd" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myAdd" data-id="NO" >NO</button>
</div>
</form>
</div>
</div>
</div>
Then I call a php file using JScript which can handle the data-id perfectly..
<script>
$(document).on('click','#getAdd',function(e){
e.preventDefault();
var per_id=$(this).data('id');
//alert(per_id);
$('#add-data').html('');
$.ajax({
url:'addLot_func.php',
type:'POST',
data:'id='+per_id,
dataType:'html'
}).done(function(data){
$('#add-data').html('');
$('#add-data').html(data);
}).fail(function(){
$('#add-data').html('<p>Error</p>');
});
});
</script>
In addLot_func.php:
if(isset($_REQUEST['id'])){
$id=intval($_REQUEST['id']);
$reject = $_REQUEST['id'];
}
else $reject = "";
if(substr($reject,0,3) == "YES")
{
...
}
else
{
...
}

How do I stop ajax call from refreshing my page?

<form id="review" method="post">
{% csrf_token %}
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<span class="icon text-white-50">
<i class="fas fa-poll-h"></i>
</span>
<span class="text">Fetch Reviews</span>
</button>
</form>
This is my html form on a Django rendered page
<script type="text/javascript">
$(document).on('submit','#review'.function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
type:'POST',
URL:'/reviews/',
data:{
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
beforeSend:function() {
$('#loader').removeClass('hidden');
},
complete : function() {
$('#loader').addClass('');
}});
return false;
});
This is the ajax function on the page.
The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both
e.preventDefault()
and
e.stopPropagation()
but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you!
To make this work change this part of code:
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
Like that:
<button type="button" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<button type="submit" id="submit_sbtn" class="d-none">
The submit button is not necessary.
Then change your script to send an ajax request to $('#sbtn') click event. And then submit your form.
$(document).on('submit','#review', function() {
$('#loader').removeClass('hidden');
$.ajax({
method: "POST",
type: "POST",
url: "/reviews/",
data: {
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
}
}).done( function( msg ) {
$('#loader').addClass('');
console.log(msg)
}).fail( function(error) {
console.log(error)
})
return false;
})

Re-execute php loop with ajax

I am using laravel 5.4.
I have many clinics in my database. I just want to retrieve all the clinics and put a delete button on each clinic. Whenever a user clicks the delete button the the clinic should be removed from the database and clinics should be updated in the front end.
This is my code.
#foreach($doctor->clinics as $clinic)
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
#endforeach
I don't want to reload the page whenever a clinic is removed. So, how can I re-execute this loop, whenever a clinic is successfully removed using ajax.
A better way to approach this might be to just remove the row using javascript. In the same function where you hide the loader, you can also remove the form from the dom.
Like so:
#foreach($doctor->clinics as $clinic)
<div id="clinic{{$clinic->id}}">
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
// Fade out and remove the form element
$("#clinic{{$clinic->id}}").fadeOut(300, function() {
$(this).remove();
});
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
</div>
#endforeach
This way you don't have to write another ajax function.

x-editable resetting fields

i have the following html/php code (php tag ommited)
$user = array(
'name' => Null,
'address' => Null
);
<div id="user">
<a href="#" id="cust_name" data-type="text"
data-pk="'.$user['ag_id'].'" title="Enter customer name">'.$user['name'].'</a>
<a href="#" id="cust_addr" data-type="text"
data-pk="'.$user['ag_id'].'" title="Enter customer address">'.$user['address'].'</a>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="ResetButton">Reset</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="SaveButton"
data-dismiss="modal">Save changes</button>
</div>
</div>
could you please complete my resetbutton script, the purpose is to assign null to cust_name and cust_addr after the click.. here's the script
<script>
$.fn.editable.defaults.mode = 'inline';
$(function(){
$('#user a').editable({
url: 'post.php'
});
});
$("#SaveButton").click(function() {
$.ajax({
url: 'db.php',
type: 'POST',
data: {}
});
});
$('#ResetButton').click(function() {
// $('#cust_name').editable('setValue', null); // did not worked
// didn't worked even i added class="myeditable" in my <a> tag
/*
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
*/
});
</script>
This seemed to work.
http://jsfiddle.net/U33kT/
I'm not sure the difference, except that I chose all editables (JS line 6):
$('#user a').editable('setValue', null);
But, I tried with single items:
$('#cust_name').editable('setValue', null);
and it seemed to work as well.
Hope this helps.

Categories

Resources