Ajax success function not working on the second time - javascript

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..

Related

Unique comment section per dynamic modal

I have a webpage with dynamically loaded cards that pop up into individual modals to display more data. These modals all have their unique id in order to pop up the correct one.
I am attempting to put a unique comment section for each modal. What I have implemented works only for the first modal & doesnt even show the comments on the second modal onwards.
I would appreciate some direction in how to make them display per modal & how to make them unique. I am assuming I echo $test[id] just like I used for the modals. Need a little assistance in script side of things.
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
</div>
</div>
<script>
var data = 1;
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment').html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
UPDATE:
Going with the response received, I made certain changes & noticed that even though the comment form is visible on all modals, the posted comments itself
only appear on the first modal. With a bit of hardcoding I am able to tell that the display_comment(id) in html & script needs to be same. The HTML id updates as per console, but I am unable to pass the correct id to $('#display_comment'+myData1).html(data); (it is always 1).
<div id="myModal<?php echo $test['id']; ?>" class="modal">
<div class="modal-content">
<div class="container">
<form method="POST" id="comment_form">
<input type="hidden" id="id" name="id" value="<?php echo $test['id']; ?>">
<div class="form-group">
<input type="text" name="comment_name" id="comment_name" class="form-control" placeholder="Enter Name" />
</div>
<div class="form-group">
<textarea name="comment_content" id="comment_content" class="form-control" placeholder="Enter Comment" rows="5"></textarea>
</div>
<div class="form-group">
<input type="hidden" name="comment_id" id="comment_id" value="0" />
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
<span id="comment_message"></span>
<br />
<div id="display_comment<?php echo $test['id']; ?>"></div>
</div>
<div id="dom-target" style="display: none;" data-id="<?php echo htmlspecialchars($test['id']);?>">
<?php
echo htmlspecialchars($test['id']);
?>
</div>
</div>
<script>
$(document).ready(function(){
$('#comment_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:"add_comment.php",
method:"POST",
data:form_data,
dataType:"JSON",
success:function(data)
{
if(data.error != '')
{
$('#comment_form')[0].reset();
$('#comment_message').html(data.error);
$('#comment_id').val('0');
load_comment();
}
}
})
});
load_comment();
function load_comment()
{
var myData1 = $("#dom-target").data("id");
console.log('#display_comment'+myData1);
$.ajax({
url:"fetch_comment.php",
method:"POST",
success:function(data)
{
$('#display_comment'+myData1).html(data);
}
})
}
$(document).on('click', '.reply', function(){
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
$('#comment_name').focus();
});
});
</script>
I have also tried the following & simply receive undefined as the value in console for myData2:
$.ajax({
url:"fetch_comment.php",
method:"POST",
data: {
myData2: $("#dom-target").data("id")
},
you should loop all the content according to your $test['id'].
each loop will generate each $test['id'], modals, form.
therefore, you will have multiple form according to each modals.
regarding the name of the input box (name="comment_id","comment_name" etc), just use the same name, as this will affect your backend on how you will process those input ($_POST['']).
this shouldn't be an issue if you area using same input name as user can only submit 1 form on each request.
just the value will be changing based on the form.

My AJAX login form in codeigniter always chooses the else statement, even if the conditions are met. How to solve these?

So I looked all across google and stackoverflow to find solution for this problem, but hadn't seen a specific solution. So here's the problem:
Everytime I submit my login form, whether credentials is correct or incorrect, ajax request always chooses the else statement.
Here's my HTML code and Ajax request.
<div class="modal fade" id="modal-section" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<img id="logoonly" src="<?php echo base_url() ?>img/cslogo5.png" />
</div>
<form action="#" id="frm_login" class="form-horizontal" method="POST">
<div class="modal-body">
<div class="form-group">
<div id="error_msg" class="alert alert-danger" class="col-md-12" style="text-align: center; display: none">
Incorrect Student number or Password.
</div>
<label for="numbers" class="col-sm-4 control-label">Student No.</label>
<div class="col-sm-6">
<input name="stud_id" id="stud_id" type="number" class="form-control" placeholder="Enter Student No." required="required" />
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-4 control-label">Password</label>
<div class="col-sm-6">
<input name="password" id="password "type="password" class="form-control" placeholder="Enter Password" data-toggle="password" required="required"/>
</div>
</div>
</div>
<div class="modal-footer" >
<p style="float: left; position: absolute; margin-top: 13px"><font size="1">Copyright 2017 &copy BulSU CS Online Portal.</font>
</p>
<a type="submit" value="Login" ><button type="submit" class="btn btn-primary" id="login_btn">Submit</button></a>
<button type="reset" class="btn btn-default" >Clear</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#frm_login').submit(function(event) {
event.preventDefault();
$.ajax({
url: '<?php echo base_url('user/do_login'); ?>',
type: 'POST',
data: {
username: $("#stud_id").val(),
password: $("#password").val(),
},
success:function(data)
{
if(data== 'Yes')
{
alert("Success!");
}
else if(data== 'No')
{
$('.alert').show().fadeIn("400");
}
},
});
});
});
</script>
Here's my controller
public function do_login() {
if(isset($_POST['username']))
{
$students = $this->db->get_where("student", array("stud_id ="=>$_POST['username'],"password ="=>$_POST['password']))->result();
if(empty($students))
{
echo "No";
}
else
{
echo "Yes";
}
}
}
Ajax passes the if statement and always chooses the else condition in my Ajax code.
I tried removing ajax, my code is working, I think my problem is with Ajax's condition. I think I just incorrectly written some code, of I lacking a simple line of code.
Thanks for the help!
In your controller try like this..
1.Use $this->input->post() instead of $_POST[] in codeigniter.
2.Your array inside where condition is wrong.So
Change
array("stud_id ="=>$_POST['username'],"password ="=>$_POST['password']);//remove = when from keys of your array
TO
array("stud_id"=>$this->input->post('username'),"password"=>$this->input->post('password'))
Finally
public function do_login() {
if(isset($this->input->post('username')))
{
$students = $this->db->get_where("student", array("stud_id"=>$this->input->post('username'),"password"=>$this->input->post('password')))->result();
if(count($students)>0)
{
echo "Yes";
}
else
{
echo "No";
}
}
}
Your form is storing the username as 'stud_id':
<input name="stud_id" ...>
But in your controller your trying to get from the post 'username':
if(isset($_POST['username']))
Just change that line to use the same value you used in the form:
if(isset($_POST['stud_id']))

UPDATE form modal bootstrap in codeigniter using AJAX

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.

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<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="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

php script mailer modal bootstrap

Hi I submit my form using modal in bootstrap
How can I make this work with dismissal message and not closing the modal?
HTML
<div class="modal fade bs-example-modal-lg" id="myModal" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header modal-header-custom">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body text-center">
<form class="form-inline requestaccessForm" role="form" name="requestaccessForm">
<div class="form-group">
<label class="sr-only" for="First Name">First Name</label>
<input type="text" class="form-control" id="request_first_name" placeholder="First Name">
</div>
<div class="form-group">
<label class="sr-only" for="Last Name">Last Name</label>
<input type="text" class="form-control" id="request_last_name" placeholder="Last Name">
</div>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<input type="email" class="form-control" id="request_email" placeholder="Email">
</div>
<button type="submit" id="requestformSubmit" class="btn btn-green">Submit</button>
</form>
</div>
</div>
</div>
</div>
PHP
<?php
$myemail = 'dummyemail#email.com';
if (isset($_POST['request_first_name'])) {
$request_first_name = strip_tags($_POST['request_first_name']);
$request_last_name = strip_tags($_POST['request_last_name']);
$request_email = strip_tags($_POST['request_email']);
echo "<span class=\"alert alert-success\" >Your message has been received. Thanks!
Here is what you submitted:</span><br><br>";
echo "<stong>Name:</strong> ".$request_first_name."<br>";
echo "<stong>Name:</strong> ".$request_last_name."<br>";
echo "<stong>Email:</strong> ".$request_email."<br>";
$to = $myemail;
$email_subject = "Contact form submission: $request_first_name";
$email_body = "You have received a new message. ".
" Here are the details:\n Name: $request_first_name \n ".
"Email: $request_email\n";
$headers = "From: $myemail\n";
$headers .= "Reply-To: $request_email";
mail($to,$email_subject,$email_body,$headers);
}?>
Javascript
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
alert("success");
},
error: function(){
alert("failure");
}
});
});
});
Thank you
To achieve that you have to take some steps first..
Add a div inside the modal which will serve as the success message container.
Before closing the <div class="modal-body text-center"> add the following code:
...
<div id="successMessage"/></div>
...
Change the success handler of the $.ajax request to add the dismissal/success message into the div created in the previous step.
Add the following code to your $.ajax success handler:
...
success: function(msg){
$("#successMessage").html(msg);
},
...
Prevent default actions from the button click so that the modal will not be closed after the request.
Add the following line at the end of your jQuery click function:
return false;
So your jQuery code will look something like this:
$(document).ready(function () {
$("button#requestformSubmit").click(function(){
$.ajax({
type: "POST",
url: "process.php", //
data: $('form.requestaccessForm').serialize(),
success: function(msg){
$("#successMessage").html(msg);
},
error: function(){
alert("failure");
}
});
return false;
});
});
Hope this helps you out

Categories

Resources