PHP submitting a form with multiple submit buttons using jQuery .post() - php

I have the following HTML code:
<form method="post" action="the_file.php" id="the-form">
<input type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input]; ?>">
<button type="submit" name="eat_something" value="TRUE">Eating</button>
<button type="submit" name="eat_something" value="FALSE">Don't Eat</button>
</form>
<textarea id="result"></textarea>
Followed by this JS:
$('#the-form').bind('submit', submitForm);
function submitForm(evt) {
jQuery.post(
$(this).attr('action'),
$(this).serialize(),
function(data) {
$('#result').empty().append(data).slideDown();
});
evt.preventDefault();
}
I also have a PHP script that receives the $_POST value from the input on submit and runs a conditions to test which submit button was clicked.
Like this:
$input = $_POST['the_input'];
$eating = $_POST['eat_something'];
if ( $eating == 'TRUE' ) {
// Do some eating...
} else {
// Don't you dare...
}
If I don't use the jQuery.post() function the submit values from the button are posted. However, for some reason, I can't manage to pass the button value to PHP $_POST with the jQuery.post() function. If I don't use jQuery.post() the output doesn't get appended to the textarea but rather in a text format on a separate page, like a document. I've also tried calling the submit function on the button $('button[type=submit]').bind('submit', submitForm); but this doesn't solve my problem either.
Thanks in advance for you help.

You forget signle quote and ) in the_name input.
<input type="text" name="the_input" value="<?php if (isset($_POST['the_input'])) { echo $_POST['the_input'] ; } ?>">
and for getting form button pressed value you need to append it value manually to serialize.
$form.serialize() + "&submit="+ $('button').attr("value")
Example
<script type="text/javascript">
$(function()
{
$('button[type="submit"]').on('click',function(e)
{
e.preventDefault();
var submit_value = $(this).val();
jQuery.post
(
$(this).attr('action'),
$(this).serialize()+ "&submit="+ submit_value,
function(data)
{
$('#result').empty().append(data).slideDown();
}
);
});
});
</script>
Complete Tested Code
<?php
if(isset($_POST['the_input']))
{
$input = $_POST['the_input'];
$eating = $_POST['eat_something'];
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>StackOverFlow</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function()
{
$('button[type="submit"]').on('click',function(e)
{
e.preventDefault();
var submit_value = $(this).val();
jQuery.post
(
$('#the-form').attr('action'),
$('#the-form').serialize()+ "&eat_something="+ submit_value,
function(data)
{
$('#result').empty().append(data).slideDown();
}
);
});
});
</script>
</head>
<body>
<form method="post" action="random.php" id="the-form">
<input type="text" name="the_input" value="<?php if (isset($_POST['the_input'])) { echo $_POST['the_input'] ; } ?>">
<button type="submit" name="eat_something" value="TRUE">Eating</button>
<button type="submit" name="eat_something" value="FALSE">Don't Eat</button>
</form>
<textarea id="result"></textarea>
</body>
</html>

Simplest answer would be:
<form method="post" action="the_file.php" id="the-form">
<input type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input']; ?>">
<input type="submit" name="eat_something" value="Eating" />
<input type="submit" name="eat_something" value="Don't Eat" />
</form>
Of course, this won't give exactly what you're looking for.
You can also do something like this:
<form method="post" action="the_file.php" id="the-form">
<input id="theInput" type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input']; ?>">
<button type="button" name="eat_something" data-value="TRUE">Eating</button>
<button type="button" name="eat_something" data-value="FALSE">Don't Eat</button>
</form>
$('#the-form button').bind('click', function(){
jQuery.post($('#the-form').attr('action'),
{
the_input: $('#theInput').val(),
eat_something: $(this).attr('data-value')
},
function(data) { $('#result').empty().append(data).slideDown() },
'json'
});

Change the buttons to this (change w/your form names)..
<input type="hidden" name="eat_something" value="" />
<input type="button" onclick="$('input[name=eat_something]').val('TRUE')" />
<input type="button" onclick="$('input[name=eat_something]').val('FALSE')" />
The Javascript function and the PHP are fine.
Thanks!
#leo

Related

Submit child-form in Nested-forms via ajax submit, without page-refresh

I am trying to submit a child-form, inside parent-form via ajax-jquery, so that it does not refresh entire page. Code is:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$(document).on('submit', '#form-2', function() {
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'a2.php',
data : data,
success : function(data) {
$("#form-2").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result").html(data);
});
});
}
});
return false;
});
}) // document ready ends here;
</script>
</head>
<body>
<form action="a1.php" method="post" name="form-1" id="form-1">
<input type="text" name="f1" />
<input type="text" name="f2" />
<input type="text" name="f3" />
<input type="text" name="f4" />
<!-----form 2 ajax starts----->
<form method="post" name="form-2" id="form-2">
<input type="text" name="g1" />
<input type="submit" id="sf2">
</form><!-----form-2 ends----->
</form><!-----form-1 ends----->
</body>
</html>
But its not working, it does simply nothing. I too used - preventdefault()
Any help ? I am trying to simply submit form-2 value in database, from which some dropdown of form-1 is getting all option values.
You could use:
$(document).on('click', '#sf2', function(event) {
var g1 = $('#g1').val();
$.ajax({
type : 'POST',
url : 'a2.php',
data : {
g1: g1
},
success : function(data) {
$("#form-2").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result").html(data);
});
});
}
});
});
and use a normal button:
<input type="text" name="g1" id="g1" />
<button type="button" id="sf2">Submit</button>
This is not good style though as forms should not be nested.

Automatically increment input type="hidden" value

I have this line of code
<html>
<head></head>
<body>
<script>
$(document).ready(function(){
$("#update").click(function(){
$("#id2").css("display","hidden");
var r = $("#id2").val()+1;
$("#id2").val(r);
});
});
</script>
<title>CV Education Form</title>
.
.
.
.
</fieldset>
<input type="text" name="id" id="id2" value="<?php echo ($id == 0 ? 1 : $id );?>"/>
<input type="submit" value="Update" name="submit"/>
</form>
</body>
</html>
and I want to change it to hidden so it is invisble but also when i click on a button update (which I have it) then it increments the value ($id) ... More simple i want something like that id+1.
Do you know how can I do that?
When I click on update button i want the 1 which is the $id to become $id+1 but I dont want to add myself I want to do it automatically when i click the update button and also hide the textfield
Just specify the update button id and id of the inputs. Use the code below
<html>
<head><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$("#update").click(function(){
$("#id2").css("display","none");
var r = parseInt($("#id2").val(),10)+1;
$("#id2").val(r);
});
});
</script>
<title>CV Education Form</title>
.
.
.
.
</fieldset>
<input type="text" name="id" id="id2" value="<?php echo ($id == 0 ? 1 : $id );?>"/>
<input type="submit" value="Update" id="update" name="submit"/>
</form>
</body>
</html>
Check it here
http://jsfiddle.net/53cov3uq/3/
Hope this helps you
you can do it very simply using either Jquery or JavaScript .find the code below
function update()
{
var count=parseInt($('#counter').val());
$('#counter').val(count+1);
alert($('#counter').val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="hidden" id="counter" name="id" value="0"/>
<button onclick="update()">update</button>
i just kept alert at the end that will popup the current value of the id.
try this,
<script type="text/javascript">
function increment_val(){
var id_val = parseInt(document.getElementById('id').value);
id_val++;
document.getElementById('id').value=id_val;
}
</script>
and in button html call js function,
<input type="button" value="update" id="btn_id" onclick="increment_val();"/>
For that use javascript. Php is server-side script.
<script type="text/javascript">
function increment()
{
var elem = document.getElementById("hiddenElement");
elem.value = 1 + parseInt(elem.value);
}
</script>
<input type="hidden" id="hiddenElement" name="id" value="0" />
<button onclick="increment()">Click me</button>
You can use below code which increments the value on click of a button.
<button onclick="document.getElementById('id').value = document.getElementById('id').value + 1;">Update</button>
HTML
<input type="text" name="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
To change input type you can use the syntax like:
$("#id").attr('type','hidden');
To increment the value use
document.getElementById('id').value=parseInt(document.getElementById('id').value)+1;
or using jquery
$("#id").val($("#id").val()+1);
Hope it helps.
try this if you want to change text to hidden element and increment value
HTML Code:
<input type="text" name="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
<button onclick="increment_value()">Update</button>
JS:
function increment_value()
{
var txt_field = document.getElementsByName("id")[0];
txt_field.value = parseInt(txt_field.value) + 1;
txt_field.setAttribute("type", "hidden");
}
OR
If you want to simply hide the text field just use this version of the above function
function increment_value()
{
var txt_field = document.getElementsByName("id")[0];
txt_field.value = parseInt(txt_field.value) + 1;
txt_field.style.display = "none";
}
<input type="hidden" name="id" id="id" value="<?php echo ($id == 0 ? 1 : $id );?>" />
Jquery
$(function(){
$("button").click(function(){
$("#id").val($("#id").val()+1);
})
})

ajax post javascript variable to php in same page

i write sample code to ajax post javaxcript varible to php in 2 page, test.php and validate.php.
test.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.min.js" ></script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit" onclick="post();">
</form>
<div id="result" ></div>
<script type="text/javascript">
function post()
{
var name=$('#name').val();
var age=$('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data)
{
if (data=="1")
{
$('#result').html('you are over 18 !');
}
if (data=="0")
{
$('#result').html('you are under 18 !');
}
});
}
</script>
</body>
</html>
validate.php
<?php
$name=$_POST['postname'];
$age=$_POST['postage'];
if ($age>=18)
{
echo "1";
}
else
{
echo "0";
}
?>
how can i write/change above code in same page ?? and validate.php insert in test.php ??
added after first answer :
"but i dont have/use any button or in my page.
and where can i insert validate.php code in test.php. please help by insert complete correct code."
Try adding a submit() method to your <form> rather than attaching the event to the submit button.
$(document).on('submit', 'form', function(){
post();
return false;
});
At the moment I think your form is submitted no matter what, you have to either return false on submit or preventDefaults()
A good idea is also to add an ID to your form in case you have more than one on your page and use the relevant selector in the .on event handler such as
$(document).on('submit', $('#form-id'), function(){ ... });
ajax is use for exchanging data with a server. If you want write code in same page so reload page and write validate.php code above of test.php like this
<?php
//validate.php code
?>
<form action=test.php type=POST>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit">
</form>

Can I submit form values using <input type="button" />?

I'm working on a search engine and I have a really serious problem with GET and POST methods.
Im using an <input type="button" /> to avoid page from refreshing every time im pressing the button.
After button is pressed I'm showing a result (google_map, monumet picture, specs).
The problem now is that I want to submit and show form values + result (google_map, monumet picture, specs) by pressing this button.
This is a problem because <input type="button" /> does not submit form values and I'm really stuck.
Sure, here is a working example for you:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Working Example</title>
</head>
<body>
<form id="search-form">
<input type="text" name="text1" id="text1" value=""><br>
<input type="text" name="text2" id="text2" value=""><br>
<input type="text" name="text3" id="text3" value=""><br>
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: "GET",
url: 'response.php',
data: $('#search-form').serialize(),
success: function(response) {
$('#response').html(response);
}
} );
});
});
</script>
</body>
</html>
response.php
<?php
echo "text1: " . $_GET['text1'] . "<br>";
echo "text2: " . $_GET['text2'] . "<br>";
echo "text3: " . $_GET['text3'] . "<br>";
echo "your response ...";
In the response you return whatever your response is, plus the form fields.
onClick="document.getElementById('FormName').submit();"

submit normally newly created ajax form

I want to submit my form. In my form using first button I create a textbox through ajax and after that I use second button to submit the form normally. When I want to get the value of newly created textbox using $_POST it gives error. How can i get value of ajax created button on submission. my php code is :
<?php`enter code here`
session_start();
ob_start();
require_once "config.php";
if ($_SERVER['REQUEST_METHOD']=="POST")
{
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js"> </script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subtest").click( function() {
alert(jQuery("#tt").val());
});
});
</script>
</head>
<body id="#bdy">
<form id="FrmMain" method="post" action="">
<div id="Shd" style="font: 10%; margin: 50px; background-repeat:repeat-y; padding- left:120px;" >
<input type="text" id="txtFrom" name="txtFrom" />
<input type="text" id="txtUpto" name="txtUpto" />
<input type="text" id="txtOpt" name="txtOpt" />
<input type="submit" id="subt" name="subt" />
<input type="submit" id="subtest" name="subtest" />
<div id="RuBox" style="font-weight:bold;"><input type="checkbox" id="chkaccept" name="chkaccept" /> I accept terms and conditions.</div>
</div>
</form>
<div style="color:#F00; font-size:18px; display:none;" id="divload">Please wait loaidng... </div>
<div id="disp"></div>
</body>
</html>
Code of my adp.php file :
<?php
sleep(5);
?>
<div style="color:#30F; font-size:36px;">
Application testing............
<input type="text" id="tt" name="tt" />
</div>
I am not getting value of textbox named "tt" in temp form
Thanks
You're pretty much not posting anything from here:
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
So I would assume that you only want to generate a text field dynamically. And you can do it without the use of ajax:
var form = $('#FrmMain');
$('<input>').attr({'type' : 'text', 'id' : 'tt', 'name' : 'tt'}).appendTo(form);
Plus you're also trying to print out $_GET['tt'] while the form method is POST
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
This should also be:
echo $_POST['tt'];

Categories