Form inside while loop working on only the 1st result - javascript

I have a from inside of a while loop. I am processing it with ajax. Its working only on the first from and not on the other results. Please have a look.
<?php while($a = $stmt->fetch()){ ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $mbs_id; ?>" class="memid">
<select class="validity" class="upgrade-valsel">
<?php while($mv = $mval->fetch()){ extract($mv); ?>
<option value="<?php echo $mv_id; ?>"><?php echo $mv_validity; if($mv_validity == 1){ echo " month"; }else{ echo " months"; } ?></option>
<?php } ?>
</select>
<input type="submit" value="Upgrade" class="submit">
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
</form>
<?php } ?>
When I click on submit button on the first result it process the result. But when I click on other buttons then its just refreshing the page. I tried replacing all the IDs with CLASS but after that not even the 1st one is working. Please help me.
Script
$(document).ready(function() {
$(".submit").click(function() {
var dataString = {
memid: $(".memid").val(),
validity: $(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to <?php echo $mbs_name; ?>?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
return false;
});
});

As #Alive to Die and Jeff try to explain it, you use selector which returns several objects so when you use a function on this set of objects, jquery only use the first object of this set.
You have to use "this" to work on the context :
$(".submit").click(function(e) {
e.preventDefault();
// $(this) : your input with class .submit (the one you click)
// parent() : the parent of $(this) (the form)
// and then find the child with the unique class you want
var dataString = {
memid: $(this).parent().find(".memid").val(),
validity: $(this).parent().find(".validity").val()
};
// EDIT: Get the loading image (you should use a class instead of this selector)
var loader = $(this).parent().find("> div");
// After you can use loader in this function and all sub functions
loader.hide();
// And then the rest of your code with the same logic...
});
Pay attention each function has a different $(this) linked to its execution context.

Use preventDefault() to prevent the page from refreshing when you click the submit button. Use this to get the current form's values. Change your dataString to use this to get the values of the current form.
$(document).ready(function() {
$(".submit").click(function(e) {
e.preventDefault();
var dataString = {
memid: $(this).parent().find(".memid").val(),
validity: $(this).parent().find(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to <?php echo $mbs_name; ?>?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
return false;
});
});

Related

request ajax doesn't call the good function

I have a trouble with my request AJAX. When I click on it, in the process, it calls an other php function which I don't need for this request (function switch, change statut).
http://www.noelshack.com/2022-31-1-1659342824-undefined-index.png
This line with error corresponds to another function.
My HTML :
<table id="list_client_pris" border=1>
<tr>
<td>#</td>
<td>Nom</td>
</tr>
<?php
$clients = $db->query('SELECT * FROM client');
foreach ($clients as $client) :
?>
<tr id="tr1">
<td><?php echo $client["id_client"]; ?></td>
<td><?php echo $client["nom_client"]; ?></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="info">Info client</button></td>
<td><button type="button" class="hide_client" data-id="<?php echo $client["id_client"]; ?>">Masquer client</button></td>
<td><button data-id="<?php echo $client["id_client"]; ?>" type="button" class="switch">Change statut</button></td>
</tr>
<?php endforeach; ?>
</table>
3 buttons call each their ajax's request.
The conflict is between the first button (class info) and the last, (class switch)
Why ?
The buttton class' info call a function which correspond to the error showed, but which is not called with the last button.
My JS , request for the first button, info:
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "POST",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
});
PHP corresponding function :
function read()
{
global $db;
$id_client = $_POST['id_client']; **(error showed)**
$query = $db->prepare("SELECT *,FROM client WHERE id_client = :id_client");
$query->bindValue(':id_client', $id_client, PDO::PARAM_INT);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
return ($result);
}
My other ajax's request for button switch :
$(".switch").click(function () {
var datas = {
cmd :' id_client_statut',
id_client: $(this).attr('data-id_statut'),
};
console.log(id_client);
$.ajax({
url: 'function.php',
type: 'POST',
data: datas,
done: function (click_result) {
console.log(click_result);
if (click_result.statut=2){
//transfer to libre
$('#tr2').append($('#tr1').html());
$('#tr1').html('');
}
}
}
);
});
Corresponding php function :
function change_statut(){
global $db;
$id_client_statut = $_POST['id_client'];
$query=$db->prepare(" UPDATE alarme INNER JOIN client_alarme ON client_alarme.id_alarme = alarme.id_alarme
INNER JOIN client on client.id_client=client_alarme.id_client
SET id_statut = 2
WHERE client.id_client= :id_client");
$query->bindValue(':id_client', $id_client_statut, PDO::PARAM_INT);
$query->execute();
$click_result = $query->fetch(PDO::FETCH_ASSOC);
return ($click_result);
}
My php function to distinguish :
if (isset($_POST['cmd'])){
if ($_POST['cmd'] == 'id_client_statut') {
change_statut();
}
else if ($_POST['cmd'] == 'id_client') {
read();
}
}
I don't really see why the first button would call the wrong function, but there is a problem with the way you setup the button events: via the onclick you are just binding the event handlers.
In function d_info() you currently just tell what should happen when the button .info is clicked. Idem for function change_statut().
So currently you have to click the buttons twice. First to bind the event and again to trigger the event (the second time it will also rebind the event).
You should get rid of the onclick attributes and bind the button events via the document ready event.
$( document ).ready(function() {
$(".switch").click(function () {
//...
});
$(".info").click(function () {
//...
});
});
In your Request you write :
$(".info").click(function () {
var datas = {
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: {cmd :' id_client', datas},
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
But the line data: {cmd :' id_client', datas}, gives you a new object witch is :
data: {
cmd :' id_client',
datas: {
id_client: $(this).attr('data-id'),
}
},
Now you can easily understand why your php gives you an error while reading $id_client = $_GET['id_client']; **(error showed)** as the real path to your value is $id_client = $_GET['datas']['id_client'];
But why using this kind of syntax while you have create datas in order to prepare ajax data object ?
The simpliest way to correct the error is to replace all object argument in the datas :
$(".info").click(function () {
var datas = {
cmd :' id_client',
id_client: $(this).attr('data-id'),
};
$.ajax({
type: "GET",
url: "function.php",
data: datas,
cache: false,
}).done(function (result) {
$('#nom').html(result.nom_client),
$('#prenom').html(result.prenom_client),
$('#date').html(result.client_date_naissance),
$('#adresse').html(result.client_adresse),
$('#mail').html(result.client_mail),
$('#tph').html(result.client_tph),
$('#age').html(result.age)
$("#info_client").css("display", "block");
date_client = (result.client_date_naissance);
return date_client;
});
Hope it's helpfull ;)
Happy coding

onsubmit return false is not working

The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});

How can i use ajax data variable use under submit button

When I click submit button, I cannot receive the value yearend. Instead I got an undefined value. How can I get yearend value when I click submit button?
My code:
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
var yearend= null;
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend +"company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click',function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);
var yearend = null;
$("#company").change(function() {
$("#dFrom").val("");
$("#dTo").val("");
var pass_code = $("#company").val();
var callpage = "dentrycomp.php?pass_code=" + pass_code
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend = data,
$("#content").html("")
$("#content").html(data)
}
});
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert(yearend + "company");
this alert box getting the right value yearend.i want that value recieve in under submit button
return true;
});
$('#submit').live('click', function() {
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button" + yearend); });
You should declare yearend globally i.e. at the top of the code.
I think it's because of var scope. You must define variable before the request and then redefine it and get it after the AJAX request.
That's the expected behavior with ajax outside your ajax call yearned is undefined. Put your on click function in ajax call itself. So, once your ajax call is finished and successful you'll attach your event listener in the success function. Use this logic instead:
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
//var yearend = "<?php echo $_SESSION['yearend'] ; ?>"
alert("this is submit button"+yearend);
});
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: callpage,
async: false,
success: function(data) {
yearend= data,
$("#content").html("")
$("#content").html(data)
$('#submit').live('click',function(){
alert("this is submit button"+yearend);
});
}
});
});
</script>
</head>
<body>
</body>
</html>

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

How to bind jquery ajax returned html using on.() [duplicate]

This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 8 years ago.
I know this question has been asked but I can't wrap my head around how to implement it correctly in my use case.
End game is when an item is added to the cart by clicking the items add button, it triggers and ajax call passing the items id to a php function that adds it to the cart session (this works great).
On the ajax calls success it calls the function update_cart(), which builds new cart html and returns it. The div holding the cart html has its contents replaced by the new cart html contents (item qty price line items). This part works well also.
The new cart contents line items include name, the qty is displayed in an input, and the price.
The newly created line items qty input is not reacting the the onblur action (i think) due to the fact that it hasnt been bound to anything since it didnt exist on page load.
Can some amazing gentleman (or woman) and scholar help me understand how to bind the new inputs so I can call an ajax function to update the item qty when the field blurs?
My JS
$(document).ready(function () {
function update_cart() {
var dataString = "";
//alert (dataString);return false;
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/updatecart.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: function(data) {
$('#cart-items').hide().html(data).fadeIn( "slow");
},
error: function(data){
$('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Updating Cart</div>").slideDown( "fast");
}
});
};
$(function() {
$("button[id^=add]").on("click", function(){
var id = $( this ).data('id');
var dataString = 'id='+ id;
/* alert (dataString);return false; */
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/add.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: update_cart ,
error: function(data){
// $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Adding Item</div>").slideDown( "fast");
}
});
return false;
});
});
$(function() {
$("input[id^=lineitem]").on("blur", function(){
var id = $( this ).data('id');
var qty = $( this ).val();
var dataString = 'id='+ id + '&qty=' + qty;
alert (dataString);return false;
$.ajax({
type: "POST",
dataType: "html",
data: dataString,
url: "/actions/add.action.php",
beforeSend: function() {
$('#loader').show();
},
complete: function() {
$('#loader').hide();
},
success: update_cart ,
error: function(data){
// $('#msg').hide().html("<div class='col-md-8'><div class='alert alert-danger alert-dismissable'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>Error Updating Quanity</div>").slideDown( "fast");
}
});
return false;
});
});
});
My Returned html and php foreach that creates it
foreach($_SESSION['basket']['items'] as $item){ ?>
<div class="cart-item">
<div class="col-lg-8 col-md-8 np item"><?php echo $item['name']; ?></div>
<div class="col-lg-2 col-md-2 np"><div class="input-group"><input data-id="<?php echo $item['id']; ?>" id="lineitem-<?php echo $item['id']; ?>" value="<?php echo $item['count']; ?>" type="text" class="form-control"></div></div>
<div class="col-lg-2 col-md-2 np price"><?php echo $item['price']; ?></div>
</div>
<?php } ?>
Thanks to anyone who can help me get my mind around how to do this. Everything was so smooth up until now.
I think this is what you want:
...success: function(data) {
$('#cart-items').hide().html(data).fadeIn( "slow");
$(".cart-item .input-group input").bind("change",...function);
OR
$(".cart-item .input-group input").on("change",...function);
OR
$(".cart-item .input-group input").change(...function);
}...

Categories

Resources