Handling multiple buttons with same ajax call - javascript

I want to populate multiple forms with multiple buttons on PHP loop from mysql. For each entry, I have 3 buttons to be handled with the same ajax calls. The issue I'm facing is to recognize which button is clicked and added it to the form data to be sent for a PHP file
function() {
var form = $('#PayBillFormForm0'); // will be different for each PHP loop
var formMessages = $('#PayBillResults0'); // will be different for each PHP loop
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: "php/pay.php", // When pay0 button is clicked
url: "php/decline.php", // When decline0 button is clicked
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
(formMessages).html(alertBox);
$('#Bill0').delay(3000).fadeOut(2000); //Bill0 is different for each PHP loop
})
});
}
<div class="card" id="Bill0">
<div id="PayBillResults0"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form id="Form0" method="post" action="">
<input name="user" id="user" value="user" type="hidden">
<input name="id" id="id" value="9" type="hidden">
<input name="reciver" id="reciver" value="ppp" type="hidden">
<input name="amount" id="amount" value="333.0" type="hidden">
<input name="tax" id="tax" value="5.0" type="hidden">
<input name="comment" id="comment" value="XXX" type="hidden">
</form>
<div id="Buttons">
<div id="Pay">
<button form="" class="btn btn-success" id="pay0" value="pay0">Pay</button>
</div>
<div id="decline">
<button form="" class="btn btn-danger" id="decline0" value="decline0">Decline</button>
</div>
<div id="Hide">
<button form="" id="hide0" class="btn btn-warning" value="hide0">Hide</button>
</div>
</div>
</div>
</div>
I was able to perform this by labeling each form and labeling each button plus having multiple onclick functions as well as multiple jQuery codes. Any idea how to send clicked button value along with form data to PHP to handle differently.

When looping with PHP, you should NEVER use any id on elements. Use classes instead... Or some data attributes.
You were using unique ids by adding a number to them... Fine. But a class is more useful since you can add one event handler to a class... Instead of n event handlers for element created by the PHP iterations. So it avoid useless code duplication and just make sens.
That is what I suggest you now. Modify your PHP loop so it will create that HTML:
(I removed all that seemed useless)
<div class="card" data-id="0">
<div class="PayBillResults"></div> <!-- To show Ajax Response Message -->
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="user" type="hidden">
<input name="id" value="9" type="hidden">
<input name="reciver" value="ppp" type="hidden">
<input name="amount" value="333.0" type="hidden">
<input name="tax" value="5.0" type="hidden">
<input name="comment" value="XXX" type="hidden">
</form>
<div>
<div>
<button class="btn btn-success pay" value="pay">Pay</button>
</div>
<div>
<button class="btn btn-danger decline" value="decline">Decline</button>
</div>
<div>
<button class="btn btn-warning hide" value="hide">Hide</button>
</div>
</div>
</div>
</div>
See the data-id="0"? That is where you will have your form number using the PHP iteration counter.
Now here is the client-side script to use once (do not loop that):
$(document.ready(function(){
// Change the URL to use with Ajax on button click
var AjaxUrl = "";
$(".pay").on("click",function(){
AjaxUrl = "php/pay.php";
$(this).closest(".card").find("form").submit();
});
$(".decline").on("click",function(){
AjaxUrl = "php/decline.php";
$(this).closest(".card").find("form").submit();
});
// Form submit handler
$("form").submit(function(e) {
e.preventDefault();
var card = $(this).closest(".card");
var formData = $(this).serialize();
formData.append("formNumber",card.data("id"));
$.ajax({
type: 'POST',
url: AjaxUrl,
data: formData
})
.done(function(response) {
var messageAlert = response.type;
var messageText = response.message;
var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><d style="font-size:12px; ">' + messageText + '</d></div>';
card.find(".PayBillResult").html(alertBox);
card.delay(3000).fadeOut(2000);
})
});
}); // End ready
So on .pay or .decline button click, the URL to use with the Ajax request is changed accordingly.
(I don't know the use of the third button)
Then the .closest() form submits. And from $(this), which is the <form>, you can find all the related elements you need.
Notice that the form number that is submitting is added to the formData.
You'll retreive it with $_POST['formNumber'].

Related

How can I clone a form and add autocomplete automatically? (with Jquery)

Let me describe what does the codes are doing. It is a simple form of html. Here is two box. When user type a name (the name must exist in the list that I clawed from other website) in the second box. The firstbox would show the id of the name. When someone click the "clone" button the programe would clone the form and change its id.
Here is my question:
How can set autocomplete automatically when I clone the form.
How can I autocomplete the first box (id of the name,id="Rent_form_g_ID") while user type the name in the second box (id="Rent_form_g_name").
The following code only run when I didn't clone anything.
This is my code:
<body>
<form>
<div class="row" id="general_form">
<div class="col-2">
<label for="Rent_form_g_ID" class="form-label">id of name</label>
<input type="text" class="form-control"id="Rent_form_g_ID" value="" disabled readonly>
</div>
<div class="col-2">
<label for="Rent_form_g_name" class="form-label">name</label>
<input type="text" class="form-control" placeholder="enter the name" id="Rent_form_g_name">
</div>
<div class="col-2">
<button type="button" class="btn btn-primary btn-block" onclick="delete_data(this.id)">delete</button>
</div>
<br>
</div>
</form>
<div class="row">
<hr>
<button type="button" class="btn btn-primary btn-block" onclick="append_a_data()">新增一筆資料</button>
</div>
<body>
<script>
var general_data={};
var general_name=[];
var general_key=[];
//get general data via api
//analyze the data which i get
var url='https://ap3.ragic.com/haisann/forms2/1?api=true';
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, false ); // false for synchronous request
xmlHttp.send( null );
general_data=JSON.parse(xmlHttp.responseText);
console.log(general_data);
for(var i in general_data){
general_key.push(general_data[i]["財產編號"]);
general_name.push(general_data[i]["財產名稱"]);
};
console.log("get general data ssucess fully");
function link_autocomplete_data($id){
//連結財產資料
$('#'+$id).autocomplete({
source: general_name
});
}
var cloneCount = 1;//clone
//clone sub form and change id
function append_a_data(){
var $html=$('#general_form').clone().attr('id', 'general_form'+ cloneCount).insertAfter($('[id^=general_form]:last'));
$('#general_form'+ cloneCount).find('#Rent_form_g_ID').attr('id','Rent_form_g_ID'+cloneCount);
$('#general_form'+ cloneCount).find('#Rent_form_g_name').attr('id','#Rent_form_g_name'+cloneCount);
link_autocomplete_data('Rent_form_g_name'+cloneCount);
cloneCount++;
};
function delete_data($id){
$('#'+$id).parent().parent().remove();
};
$(document).ready(function(){
link_autocomplete_data("Rent_form_g_name");
// also I don't know how to write this programe better
$('#Rent_form_g_name').click(function() {
$(this).change(function(){
var g_name=$('#Rent_form_g_name').val();
for(i in general_data){
if(general_data[i]["財產名稱"]==g_name){
$('#Rent_form_g_ID').val(general_data[i]["財產編號"])
$('#Rent_form_g_stock').val(general_data[i]["財產數量"])
};
};
});
});
})
</script>

cant get serialize to work with javascript generated input fileds

I am using jQuery's serialize(). But in this case, it is not picking up my input fields that are created via some JavaScript code in a called PHP page in $(document).ready(function (). I did an alert but the input fields were not in the JSON string.
The serialize() call is actioned by a submit action.
I tried both these but neither worked.
var dataString = $( "input" ).serialize();
var dataString = $(this).serialize().replace(/\'/g,'\\\'');
I am guessing it is becuase they are generated at runtime.
Any help is much appreciated.
var url = "../js/contactmail.php";
var dataString = $(this).serialize().replace(/\'/g,'\\\'');
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function (data) {
var arraydata = $.parseJSON(data);
}
});
Code auto generated by JavaScript at runtime:
<div class="col-md-12">
<input data-prefix="thé" data-suffix="tea" id="tea" type="number" value="0"
min="0" max="10" step="1" style="display: none;">
<div class="input-group ">
<div class="input-group-prepend">
<button style="min-width: 2.5rem" class="btn btn-decrement btn-outline-secondary" type="button">
<strong>-</strong>
</button>
<span class="input-group-text">thé</span>
</div>
<input type="text" inputmode="decimal" style="text-align: center" class="form-control " placeholder="" />
<div class="input-group-append">
<span class="input-group-text">tea</span>
<button style="min-width: 2.5rem" class="btn btn-increment btn-outline-secondary" type="button">
<strong>+</strong>
</button>
</div>
</div>
</div>
Okay.. after some trial and error I have realised that serialize() uses HTML name Attribute and not the ID Attribute. So the answer is to include name = 'tea'

How to submit forms input values using post to server side script

I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});

Why this submit function in Meteorjs doesn't work?

I have a form which consists of 7 questions. I ask them individually using display:none. But the problem is that submit function doesn't work. When I click it, it just redirects back to the first question and url turns to - http://localhost:3000/?problem=&why1=&why2=&why3=&why4=&why5=&solution=&submit-all=Answer . I really need help with this please. Below is code for HTML template and JavaScript submit function to submit in Problems collection.
<template name="submitProblem">
<div class="container">
<div class="main-page">
<form class="text-center">
<div id="submit-problem">
<input autofocus="autofocus" type="text" name="problem" id="problem" placeholder="What's the problem ?"/>
<input type="button" id="route" value="Find Its Route" class="route btn btn-sample">
</div>
...
submit-why1 - submit-why4
...
<div id="submit-why5" class="hidden">
<input autofocus="autofocus" type="text" id="why5" class="" name="why5" placeholder="This problem exists, because..."/>
<input type="button" value="Answer" class="btn-success btn answer5">
<button class="btn back5 back-btn"><i class="fa fa-arrow-left fa-3x"></i></button>
</div>
<div id="submit-solution" class="hidden">
<input autofocus="autofocus" type="text" name="solution" id="solution" placeholder="What could be the best solution ?"/>
<input type="submit" id="submit-all" name="submit-all" value="Answer" class="btn btn-primary submit-all">
<button class="btn back6 back-btn"><i class="fa fa-arrow-left fa-3x"></i></button>
</div>
</form>
</div>
</div>
</template>
Template.submitProblem.events({
'submit .submit-all':function() {
event.preventDefault();
var problem = $(event.target).find('[name=problem]').val();
var why1 = $(event.target).find('[name=why1]').val();
var why2 = $(event.target).find('[name=why2]').val();
var why3 = $(event.target).find('[name=why3]').val();
var why4 = $(event.target).find('[name=why4]').val();
var why5 = $(event.target).find('[name=why5]').val();
var solution = $(event.target).find('[name=solution]').val();
Problems.insert({
problem: problem,
why1: why1,
why2: why2,
why3: why3,
why4: why4,
why5: why5,
solution: solution,
submitdate: new Date()
});
console.log(problem + why1 + why2 + why3 + why4 + why5 + solution);
Router.go('submitted');
}
});
You need to pass the event as the first parameter to your handler:
submit: function(event) {
event.preventDefault();
...
Otherwise it won't be defined, the default action (a POST) won't be prevented, and your page will reload.

Input field with two buttons

I have a form with one input field, but two buttons. The idea is to check in or out with a code. The process comes to the php file, where it ends with just a blank page. What´s wrong?
EDIT
I changed "btn_in" to "inputAnst_nr" And now it works to reg in. BUT, how to i fetch wich button is pressed?
HTML
<form class="form-inline well" id="usr_stamp" name="usr_stamp" method="post" action="php/usr_time_reg.php">
<div class="control-group">
<input id="inputAnst_nr" name="inputAnst_nr" class="form-control input-lg" placeholder="Ange Anst. nr" type="tel">
<button id="btn_in" name="btn_in" class="btn btn-lg btn-info primary col-sm-offset-1" type="submit">In</button>
<button id="btn_out" name="btn_out" class="btn btn-lg btn-danger primary col-sm-offset-1" type="submit">Ut</button>
</div>
</form>
JS
$(document).ready( function () {
$("#btn_in").on('click', function() {
$("#usr_stamp").attr("action", "php/usr_time_reg.php");
});
$("#btn_out").on('click', function() {
$("#usr_stamp").attr("action", "php/usr_time_reg.php");
});
});
PHP
//Check if POST is empty
if(!empty($_POST)){
//Check if POST is "inputAnst_nr"
if(!empty($_POST['inputAnst_nr'])){
//Put POST_btn_in in variable
$posted_anst_nr = $_POST['inputAnst_nr'];
You could just use the same name attribute value for both buttons, just make sure you designate the appropriate value. Example:
<?php
if(isset($_POST['btn_in_out'])) {
$status = $_POST['btn_in_out']; // In or Out depending on which one you clicked
echo $status;
}
?>
<form class="form-inline well" id="usr_stamp" name="usr_stamp" method="post">
<div class="control-group">
<input id="inputAnst_nr" name="inputAnst_nr" class="form-control input-lg" placeholder="Ange Anst. nr" type="tel">
<button id="btn_in" name="btn_in_out" type="submit" value="In">In</button>
<button id="btn_out" name="btn_in_out" type="submit" value="Out">Ut</button>
</div>
</form>
Sample Output

Categories

Resources