ajax form submission with jquery multiple forms - php

Following the examples on this page: http://www.formget.com/submit-form-using-ajax-php-and-jquery/
I am converting the forms on one of my sites to use ajax for submission, that way uses can use the forward and back buttons, and their info isn't showing up in the address bar.
It's worked so far, on pages that have a single form. But one page has multiple forms on it.
Form from campers.php
<form id="retro1457806069">
<input type="hidden" id="class" name="classa" value="retro">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>
<form id="two1457806069">
<input type="hidden" id="class" name="classa" value="classtwo">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>
<form id="three1457806069">
<input type="hidden" id="class" name="classa" value="classthree">
<input type="hidden" id="type" name="type" value="1">
<input type="submit" id="submit" value="Rent This Camper"></form>
Those are the actual form codes generated by my script (with all the excess text and such removed around them.
script.js:
$(document).ready(function() {
$("#submit").click(function() {
var classa = $("#classa").val();
var type = $("#type").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'class=' + classa + '&type=' + type;
if (classa == '' || type == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "campersub.php",
data: dataString,
cache: false,
success: function(result) {
window.location.assign("gear.php")
}
});
}
return false;
});
});
campersub.php
<?php
session_start();
$_SESSION["class"]=$_POST["class"];
$_SESSION["type"]=$_POST["type"];
echo "Success.";
?>
The problem is, instead of adding the form information to the $_SESSION array and redirecting the browser to gear.php when I click on the first submit button, absolutely nothing happens. But when I click on the second or third submit buttons it redirects the page to campers.php?classa=classone&type=1 for example.

I have modified some things, having in mind mainly: 'Id attributes must be unique in the document'
(Even, If there are not other references in the code to the form elements by id then the id attribute can be removed)
So I have renamed ids as they have an unique value, then I fetch the click event for catch any input submit
NOTE: I have accessed to the other elements from the parent (its form) which contains the last clicked element because I'm not sure if it is the entire HTML you have.
campers.php
<form id="retro1457806069">
<input type="hidden" id="class1" name="classa" value="retro">
<input type="hidden" id="type1" name="type" value="1">
<input type="submit" id="submit1" value="Rent This Camper"></form>
<form id="two1457806069">
<input type="hidden" id="class2" name="classa" value="classtwo">
<input type="hidden" id="type2" name="type" value="1">
<input type="submit" id="submit2" value="Rent This Camper"></form>
<form id="three1457806069">
<input type="hidden" id="class3" name="classa" value="classthree">
<input type="hidden" id="type3" name="type" value="1">
<input type="submit" id="submit3" value="Rent This Camper"></form>
script.js
$(document).ready(function() {
$("input[type=submit]").click(function(e) {
// **Accesing by proximty of the last clicked element, and by its name.
e.preventDefault();
var classa = $(this).parent('form').find('input[name="classa"]').val();
var type = $(this).parent('form').find('input[name="type"]').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'class=' + classa + '&type=' + type;
if (classa == '' || type == '') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "campersub.php",
data: dataString,
cache: false,
success: function(result) {
window.location.assign("gear.php")
}
});
}
return false;
});
});
I think it must run with these changes...

Related

Submit multiple forms using only 1 ajax?

I'm getting my multiple forms using a while loop (fetch data in the database).
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test2">
<input type="text" class="form-control" name="car_type" value="test2">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Here's my ajax (It only works in the 1st form but the rest not working):
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo();
});
});
Function for ajax:
function sendInfo() {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(".form").serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}
How can I set or how ajax will recognize the button I click/submit to process the form?
You don't close your <form> tag.
You use the same id twice.
You select anything with class form, not ID form.
Actually, I am amazed it works even one time.
Try this (no need to touch the JavaScript), your form should submit, but the button changing might not work (you use identical IDs there too; tip: an id has to be unique within the entire HTML DOM).
<form class="form form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Using "this" keyword inside submit handler, you will receive a reference to the form to which the clicked button belongs.
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
var form_to_submit = this;
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo(form_to_submit);
});
});
function sendInfo(form_to_submit) {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(form_to_submit).serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}

Update sql query and table contents using radion button and php

I am newbie.
How can i change the contents of the table using radio buttons and php. WITHOUT REFRESHING THE PAGE.
HTML
<form name="myform" action="" method="post">
<input type="radio" onchange="this.form.submit()" name="page" value="all"> All<br>
<input type="radio" onchange="this.form.submit()" name="page" value="old"> Old<br>
<input type="radio" onchange="this.form.submit()" name="page" value="new"> New>
</form>
PHP
<?php
$page = null;
if(isset($_POST['page'])){
$page = $_POST['page'];
}
switch($page){
case 'all':
// SQL QUERY
break;
case 'new':
// SQL QUERY
break;
case 'old':
// SQL QUERY
break;
}
?>
The problem is the page will refresh, and the selected radio button will become unselected.
change your form to,
<form id="myform" name="myform" action="yourphppage.php" method="post">
<input type="radio" name="page" value="all"> All<br>
<input type="radio" name="page" value="old"> Old<br>
<input type="radio" name="page" value="new"> New>
</form>
load jquery script in the page. after loading use the following code,
<script>
$(document).ready(function(){
$('input[name="page"]').on('change',function(){
$.ajax({
url: $('#myform').attr('action');
type: "POST",
data: {page: $('input[name="page"]').val()},
success: function(result){
alert(result);
}
});
});
});
</script>
i didnt ran it, but i am pretty sure it will be the solution to your problem. let me know if u face any problem.
I had used given blow code for resolving this type of problem :-
<form id="myform" name="myform" action="" method="post">
<input type="radio" name="page" value="all"> All<br>
<input type="radio" name="page" value="old"> Old<br>
<input type="radio" name="page" value="new"> New
</form>
<div id="responsecontainer"></div>
<script>
$(function(){`$(function(){
$("input[name='page']").change(function() {
var form = this.form;
$.ajax({
type: "POST",
url: "action.php",
data: $(form).serialize(),
success: function(response){
$("#responsecontainer").html(response);
}
});
});
});
</script>

Submit checkbox ID and textfield value without refreshing browser using Ajax

i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/

get an id of a specific form within several form on the same page (jquery)

I have a problem, and i don't know how to get an id of a specific form when in the same page there is several form. Each form has a different id :
HTML :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="submit" id="addToCart" name="addToCart">Add</button>
</form>
And this is the ajax
Jquery :
$('[id^=acheter]').submit(function() {
var CurrenID = $(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: $('#'+CurrenID).serialize(),
success: function(data) {
Method();
}
});
return false;
});
$('[id^=acheter]').submit(function() {
var data = $(this).serialize()+"&form_id="+$(this).attr('id');
$.ajax({
type: "POST",
url: "page.php",
data: data,
success: function(data) {
Method();
}
});
return false;
});
That will add your ID to the form post data?
in this line:
$('[id^=acheter]').submit(function() {
change to
$('#acheter').submit(function() {
Note that the id must be unique if you want to get more than one value from diferent tags use name or class.
to check the forms using the id just make a input button instead input submit, each one with a diferent variable to the jquery and submit .
example :
<form method="post" action="page.php" id="acheter1">
<input type="hidden" class="idProd8" name="idProd8" value="1">
<input type="hidden" name="price" value="10">
<button type="button" id="addToCart1" name="addToCart" onclick="submitF('1')">Add</button>
</form>
<form method="post" action="page.php" id="acheter2">
<input type="hidden" class="idProd8" name="idProd8" value="2">
<input type="hidden" name="price" value="20">
<button type="button" id="addToCart2" name="addToCart" onclick="submitF('2')">Add</button>
</form>
Then use jquery/javascript to check what button was clicked
function submitF(var)
{
if (var == 1)
{
...
/*do what you want knowing that the first form was clicked,
submit form with jquery if you want*/
...
}
if (var == 2)
{
...
/*do what you want knowing that the second form was clicked,
submit form with jquery if you want*/
...
}
}

Submiting form with jquery

I have a form and I need to add some data from database before submiting it.
My html code is:
<form action="https://91.199.226.106/services/authorize.php" id="arca" method="POST">
<input type="hidden" name="hostID" id="hostID"/>
<input type="hidden" name="mid" id="mid" />
<input type="hidden" name="tid" id="tid" />
<input type="hidden" name="additionalURL" id="additionalURL" />
<input type="hidden" name="orderID" id="orderID" />
<input type="hidden" name="currency" id="currency" />
<input type="hidden" name="opaque" />
amount<input type="text" name="amount" id="amount" value="" /><br>
<input type="submit" value="submit" />
</form>
<div id="script_area"></div>
<div id="error_area"></div>
And I have an event handler for form submit. Here is the code:
$("#arca").submit(function(e){
e.preventDefault();
var data="amount="+$("#amount").val()+"&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited=html.split("|",2);
if(splited[0]=="0")
{
$("#error_area").html(splited[1]);
}
else
{
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});
The PHP returns
"0|error message" or "1|script that sets fields values" that I place
in the div with id="script_area"
. The problem is that $("#arca").submit(); line ceeps on submiting the form on and on. How can I solve this problem? Thanks for help.
Replace $("#arca").submit(); with $("#arca")[0].submit();. This way you are calling the submit event on the underlying DOM element which won't trigger your callback and avoid the infinite loop.
You could change to bind a click event to submit button instead.
$("#arca").find('input[type="submit"]').click(function (e) {
e.preventDefault();
var data = "amount=" + $("#amount").val() + "&&lang=eng";
$.ajax({
url: "ajax/get_arca_submit_params.php",
type: "POST",
data: data,
cache: false,
success: function (html) {
var splited = html.split("|", 2);
if (splited[0] == "0") {
$("#error_area").html(splited[1]);
} else {
$("#script_area").html(splited[1]);
$("#arca").submit();
//alert("aaaaa");
}
}
});
});

Categories