How to response specific submit button using jQuery/Ajax? - javascript

I have a web page where 4 submit button exist. These 4 submit button is calling same php page process.php using jQuery/Ajax. I am calling this php page using onClick event. Like following :
<div class="col-md-12">
<input type="hidden" name="_token" value="<?php echo $create_menu_token; ?>">
<a onclick="menu_creation(this,event);" href="#menudetails" data-toggle="tab" class="btn btn-booking next">NEXT STEP</a>
</div>
<div class="col-md-12">
<input type="hidden" name="_token" value="<?php echo $create_menu_token; ?>">
<a class="btn btn-booking btn-save-color back">BACK</a>
<a onclick="menu_creation(this,event);" href="#uploadimage" data-toggle="tab" class="btn btn-booking next">NEXT STEP</a>
</div>
<div class="col-md-12">
<input type="hidden" name="_token" value="<?php echo $create_menu_token; ?>">
<a class="btn btn-booking btn-save-color back">BACK</a>
<a onclick="menu_creation(this,event);" href="#date" data-toggle="tab" class="btn btn-booking next">NEXT STEP</a>
</div>
<div class="col-md-12">
<input type="hidden" name="_token" value="<?php echo "?key=".$create_menu_token; ?>">
<input type="hidden" name="chef_id" value="<?php echo $chef_id; ?>">
<a class="btn btn-booking btn-save-color back">BACK</a>
PREVIEW MENU
<input type="submit" name="submit" value="FINISH" onclick="menu_creation(this, event);" class="btn btn-booking">
</div>
I want to show a different message when user click on Finish button (last one). From php page, How can I know If user press this Finish button ?
JS Code :
function menu_creation (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: <?php echo "'menu-creation?key=$create_menu_token'"; ?>,
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$("#form-bottom").attr("disabled", true);
},
success: function (data) {
$('.menu-validation-message').html(data);
//$('.menu-validation-message').show().delay(3000).hide('slow');
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Update :
In php page now I am using following code to check if user press the FINISH BUTTON or not .
if(isset($_POST['submit']) && $_POST['submit'] == 'FINISH') {
echo 'Hello Finish';
} else {
echo 'Not detecting';
}
But not detecting...

Use this example as a reference....
$( "#target" ).click(function() {
alert( "Handler for .click() called." ); //do your code here
});
AND one thing don't forget to add id having "target" on that button

You can use Jquery to solve this
First you need to specified id or class to your finish button
In this case, I will use id
<input id="finish_button" type="submit" name="submit" value="FINISH" class="btn btn-bookingt">
function menu_creation (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: <?php echo "'menu-creation?key=$create_menu_token'"; ?>,
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$("#form-bottom").attr("disabled", true);
},
success: function (data) {
$('.menu-validation-message').html(data);
//$('.menu-validation-message').show().delay(3000).hide('slow');
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
$("input#finish_button").click(function(e){
alert("HELLO FINISH");
menu_creation(this, e);
});

Related

AJAX add to cart code gives no error but not running with PHP MYSQL

I am trying hard to find the problem, here is my ajax code
$(document).ready(function(){
$(document).on("click", "#addItem", function(e){
e.preventDefault();
var form = $(this).closest(".form-submit");
var id = form.find(".pid").val();
var name = form.find(".pname").val();
var price = form.find(".pprice").val();
var image = form.find(".pimage").val();
var code = form.find(".pcode").val();
$.ajax({
url: "action.php",
method: "post",
data: {pid:id, pname:name, pprice:price, pimage:image, pcode:code},
success:function(response){
$(".alert-message").html(response);
window.scrollTo(20,2);
load_cart_item_number();
}
});
});
load_cart_item_number();
function load_cart_item_number() {
$.ajax({
url: "action.php",
method: "get",
data: {cartItem: "cart_item"},
success:function(response){
$("#cart-item").html(response);
}
});
}
});
and HTML form :
<form>
<input type="hidden" class="pid" value="<?php echo $row['product_id'] ?>">
<input type="hidden" class="pname" value="<?php echo $row['product_name'] ?>">
<input type="hidden" class="pprice" value="<?php echo $row['product_price'] ?>">
<input type="hidden" class="pimage" value="<?php echo $row['product_image'] ?>">
<input type="hidden" class="pcode" value="<?php echo $row['product_code'] ?>">
<button id="addItem" class="btn add-to-cart">Add To Cart</button>
</form>
the only problem is add to cart button is not working and there is no error in console showing.

How to get the ID of a dynamically generated button using jQuery?

I need some help. I have a page where I display database records as a bootstrap button pill in a display div. I also have an Ajax Submit input that saves new records to the database and dynamically creates a button pill for the new record using the db record id for the button id. The jQuery below allows me to click on the new dynamically created button but it always displays ID = 1 and not the ID shown in view source.
Can someone please explain what I am doing wrong here?
Code of Button Pills created from PHP:
<div class="row">
<div class="col-md-8 col-sm-10 mx-auto mb-3">
<div class="decision-box">
<div class="decision-icon bg-orange-grad"><img src="../assets/img/logos/Sparck-Logo-Icon-Lg-White.png" alt="Sparck-Logo-Icon-Lg" width="40" height="40" /></div>
<div class="decision-text">
<form id="accolorform">
<input type="hidden" name="action" value="colorsave">
<input type="hidden" name="interesttype" value="Favorite Color">
<input type="hidden" name="userid" value="<?php echo $_SESSION['userid']; ?>">
Favorite Color:
<input type="text" class="form-control-inline col-auto no-border no-shadow" id="ac_color" name="interest" placeholder="Type something" autocomplete="off" style="min-width: 200px;">
<span class="float-right" style="margin-right: 15px;">
<button type="submit" class="btn btn-light" id="colorbtn">Add</button>
</span>
</form>
</div>
</div>
<div id="color_pills">
<?php if(!empty($resultlist) && isset($resultlist)){
foreach($resultlist as $r){
if($r['interesttype'] = "Favorite Color"){ ?>
<button id="btn<?php echo $r['id']; ?>" class="btnpill" title="Are you sure you want to delete <?php echo $r['interest']; ?>?"><?php echo $r['interest']; ?> <i id="<?php echo $r['id']; ?>" class="fal fa-minus-circle delete"></i></button>
<?php }
}
}?>
</div>
</div>
</div>
Code of jQuery aJax that creates dynamic button
$("#accolorform").validate({
rules: {
ac_color: {
required: true
}
},
messages: {
ac_color: {
required: 'Please select a Color'
}
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $(form).serialize(),
success: function(id){
//alert("Color Added");
var name = $("#ac_color").val();
var newpill = '<button id="btn'+id+'" class="btnpill" title="Are you sure you want to delete '+name+'?">'+name+' <i id="'+id+'" class="fal fa-minus-circle delete"></i></button>';
$("#color_pills").append(newpill);
$("#accolorform")[0].reset();
},
error: function(){
alert("Error");
}
});
}
});
Code of Ajax Delete where I am trying to grab dynamic button id:
$(document).on('click', '.delete', function(){
var id = $(this).attr('id');
var title = $('#btn'+id).attr('title');
var string = 'source=interests&id='+ id ;
if (confirm(title)) {
$.ajax({
type: "POST",
url: "ajaxdelete.php",
data: string,
cache: false,
success: function(){
$('#btn'+id).remove();
}
});
}
return false;
});
The above code looks like it should work and view source shows a button tag that is formatted like the ones created by PHP that work perfectly.
I appreciate any help!

how can page reload disabled when data get using ajax success function in javascript codeigniter php?

I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<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">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}

ajax stop bootstrap modal box from closing when user clicks submit

This is a bit of a tricky problem to explain but here goes:
I would like to display results inside a bootstrap modalbox, doing the following:
Selectbox1-->populates-->SelectBox2-->populates-->Selectbox3
Get values from selectboxes when user clicks submit
Query database with selectbox values
Display result in modal box
My problem
Everything is working however when user clicks submit the modalbox closes, when I open the modalbox again the result is inside the modalbox
HOW CAN I GET THE MODALBOX TO NOT CLOSE WHEN USER CLICKS SUBMIT?
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<script type="text/javascript">
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'functionTest.php',
data: formData,
type: 'post',
success: function(data) {
$('#resultForm').replaceWith(data);
}
});
});
</script>
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
</head>
<body>
<center>
<div>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
include('connect.php');
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
if(isset($_POST['submit'])){
echo $tour = $_POST['tournament'];
echo $round = $_POST['round'];
}
It seems that you're missing a "return false;" in your form submit event handler:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'functionTest.php',
data: formData,
type: 'post',
success: function(data) {
$('#resultForm').replaceWith(data);
}
});
//Return false to cancel submit
return false;
});
Try to remove the class close from the button
I haven't tested your solution, but try putting e.stopPropagation(); before e.preventDefault();
UPDATE
Why is your Modal in the <head> part ?

Show hidden div after login error: JQuery and AJAX

I'm using Jquery AJAX to catch login error,
but when i submit a bad login i can't see the div loginError
i searched on http://api.jquery.com
i used this example http://hayageek.com/jquery-ajax-form-submit
Here is my js:
$().ready(function() {
$("#loginForm").validate({
rules: {
email: {
required: true
},
password: {
required: true,
minlength: 6,
maxlength: 20
}
},
messages: {
email: {
required: "Please provide an email"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 6 characters long",
maxlength: "Your password must be at most 20 characters long"
}
}
});
$("#loginForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
error: function(jqXHR, textStatus, errorThrown) {
$("#loginError").show();
}
});
e.preventDefault();
});
When i remove the e.preventdefault(); i can see briefly this div but my page reload and
the div disappear !
And Here is my form:
<form class="cmxform form-signin" id="loginForm" method="POST" action="">
<fieldset>
<div class="login-wrap">
<h2 class="form-signin-heading"><?php echo lang('login.title')?></h2>
<div id="loginError" class="alert alert-warning" hidden="hidden">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<strong>Oh snap!</strong> <?php echo lang('login.error')?>
</div>
<div class="form-group ">
<label class="control-label" for="femail">Email:</label>
<input class="form-control" type="email" id="femail" name="email" placeholder="<?php echo lang('login.email') ?>" autofocus required>
</div>
<div class="form-group ">
<label class="control-label" for="fpassword">Password:</label>
<input class="form-control" type="password" id="fpassword" name="password" placeholder="<?php echo lang('login.password') ?>" required>
</div>
<label class="control-label checkbox" for="frememberme">
<input type="checkbox" id="frememberme" name="rememberme" value="rememberme"><?php echo lang('login.rememberme')?>
<span class="pull-right"> <?php echo lang('login.forget') ?></span>
</label>
<button class="btn btn-lg btn-block btn-login" type="submit"><?php echo lang('login.login')?></button>
<button type="button" class="btn btn-lg btn-block btn-register"><?php echo lang('login.register')?></button>
<div class="login-social-link">
<p><?php echo lang('login.joinus') ?></p>
<a href="index" class="facebook">
<i class="icon-facebook"></i>Facebook</a>
<a href="index" class="twitter">
<i class="icon-twitter"></i>Twitter</a>
</div>
</div>
</fieldset>
</form>
maybe it come from my CodeIgniter code.
Thank's in advance !
try something like this
$("#loginForm").submit(function(e)
{
e.preventDefault();
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax( {
url : formURL,
type: "POST",
data : postData,
error: function(jqXHR, textStatus, errorThrown) {
$("#loginError").show();
}
});
});
Try this:
$("#loginForm").submit(function (e) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (response) {
if (response) {
//do stuff if login is correct
} else {
$("#loginError").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
//$("#loginError").show();
}
});
e.preventDefault();
});
Note: Get the response from server side after database operation. and make changes in IF/ELSE condition as per your requirement

Categories