Posting search value via html button - php

I am searching for a possibility to replace the lowre input text field with a button like: <input type="button" class="button" name="search" value="Urban" onclick="">.
HTML CODE:
<form method="post" action="search.php" id="search_form">
<input type="text" name="search" value="<?php echo $_POST['search']; ?>" class="search_sounds"/>
<input type="submit" value="" class="submit" />
</form>
The whole script is supposed to search the sounds of a database:
PHP CODE:
<?php if(isset($_POST['search']) && !empty($_POST['search']))
{
include('searchfunction.php');
if(count($data) > 0)
{
?>
<script type="text/javascript">
$(document).ready(function(){
var description = '';
var myPlaylist = [
<?php
echo(implode(',', $data));
?>
];
$('#main').ttwMusicPlayer(myPlaylist, {
autoPlay:false,
description:description, }
);
});
</script>
<?php
}
else
{
echo ('No sounds found.');
}
}
?>

add an id element to your button, like this (I removed the onclick="" code)
<input type="button" class="button" name="search" value="Urban" id="search_button">
Then use some simple jQuery:
$('#search_button').click(function() {
$('#search_form').submit();
});

Related

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);
})
})

How to avoid the jquery "colorbox" closing when we are submitting the data

i'm calling the external php page by using the ajax method in Jquery colorbox in that while i'm submitting the data the colorbox is closed automatically n go to the normal page view without lightbox how to avoid that and reopen the colorbox after submitting....
Please tell some suggestions r solutions abt this problems friends...
//home page
//jquery of colorbox
<script src="jquery/jquery.colorbox-min.js"></script>
<script>
$(function(){
$(".ajax").colorbox({width:"63%", height:"80%"})
});
</script>
<a class="ajax" href="assign_ajax.php">New Task</a>
This is the the page called by ajax in colorbox while submitting it goes to the normal page out of colorbox im using
//////////////////////////////ajax page///////////////////////
if(isset($_POST['update'])){
$sql = UPDATE `notes` SET `note`=$_POST['update_text'] WHERE`id`={$_GET['note_id']};
mysql_query($sql) or die(mysql_error());
}
<form name="update_form" id="update_form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>?note_id=<?php echo $row['id']; ?>" method="post">
<textarea name="update_text" id="update_text" rows="5" cols='55'><?php echo $row['note']; ?></textarea>
<br>
<input type="submit" id="update" name="update" value="update">
<input type="button" value="cancel" class ="edit" id="edit-<?php echo $row['id']; ?>">
</form>
<script src="jquery/jquery.colorbox-min.js"></script>
<script>
function showColorBox(event)
{
event.preventDefault();
$.colorbox({href:"assign_ajax.php"});
}
</script>
<a class="ajax" onclick="showColorBox(event)">New Task</a>
//Or
<script src="jquery/jquery.colorbox-min.js"></script>
<script>
$(function(){
$(".ajax").on("click",function(event){
event.preventDefault();
$.colorbox({href:$(this).attr("href")});
});
});
</script>
<a class="ajax" href="assign_ajax.php">New Task</a>
EDIT
<?php
if(isset($_POST['update'])){
$sql = "UPDATE `notes` SET `note`=$_POST['update_text'] WHERE`id`={$_GET['note_id']}";
mysql_query($sql) or die(mysql_error());
}
?>
<form name="update_form" id="update_form" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);>?" note_id="<?php echo $row['id']; ?>" method="post" onsubmit="return FALSE;">
<textarea name="update_text" id="update_text" rows="5" cols='55'><?php echo $row['note']; ?></textarea>
<br>
<input type="button" id="update" name="update" value="update">
<input type="button" value="cancel" class ="edit" id="edit-<?php echo $row['id']; ?>">
</form>
<script>
$(function(){
$("#update").on("click",function(){
$.ajax({url: $("#update_form").attr("action"), data:{note_id: $("#update_form").attr("note_id"),update_text:$("#update_text").val()}, type:"POST", dataType:"json"}).done(function(data){});
});
});
</script>

How to get the values from a submitted do...while form

I have the following code with a form inside a list that should submit the element through Ajax. The values in the form is repeated through a do ... while loop, so that the list become a dynamically list, like in this picture:
But when I click a button, the only element that is sent through the Ajax code is the value of the last button, even though I click on Oranges for example.
The code is as follow:
<script>
function submitForm() {
$.ajax({type:'POST', url: 'jQuery-ajax-demo.php', data:$('#MyJobsForm').serialize(), success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}});
return false;
}
</script>
</head>
<body>
<ul id="btn_MyJobs" data-role="listview" data-inset="true">
<li id="MyJobs_List" class="push">
<form id="MyJobsForm" onsubmit="return submitForm();">
<?php do { ?>
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</form>
</li>
</ul>
<div id="myJobs_Right">
<div class="form_result"> </div>
</div>
</body>
The jQuery-ajax-demo.php page looks like this:
<?php
if(isset($_POST['name'])) {
$name = $_POST['name'];
?>
Your Name Is: <?php echo $name; ?><br />
<?php
die();
}
?>
If you have to do it this way, then you might try creating a new form for each button:
<?php do { ?>
<form onsubmit="return submitForm(this);"> <!--Note I added "this" -->
<input type="hidden" name="name" value="<?php echo $row_Recordset1['cargo']; ?>">
<input type="submit" name="submit" value="<?php echo $row_Recordset1['cargo']; ?>">
<br/>
<br/>
</form>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
Then the only value that will get posted will be the hidden value that is in the form whose button you clicked. I updated the onsubmit call above to include this in the call. So you can do the below in your function:
function submitForm(form) {
var $form = $(form);
$.ajax({
type:'POST',
url: 'jQuery-ajax-demo.php',
data:$form.serialize(),
success: function(response) {
$('#myJobs_Right').find('.form_result').html(response);
}
});
return false;
}

Form Hidden by jQuery Code [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I'm not very good at jQuery. I have to show a form in the code below, but it seems jquery (or Javascript) keeps the code hidden.
The sample output is inhttp://210.48.94.218/~printabl/products/business-cards/. If you click the "CONTINUE" button in the page.
<?php
/**
* Template Name: Contact Page
*
* Description: Twenty Twelve loves the no-sidebar look as much as
* you do. Use this page template to remove the sidebar from any page.
*
* Tip: to remove the sidebar from all posts and pages simply remove
* any active widgets from the Main Sidebar area, and the sidebar will
* disappear everywhere.
*
* #package WordPress
* #subpackage Twenty_Twelve
* #since Twenty Twelve 1.0
*/
get_header(); ?>
<div id="primary" class="site-content">
<div id="content" role="main">
<script type="text/javascript">
var x1 = 5;
var x2 = 10;
var value = x1 * x2;
var list_value = 1;
var size, fold, back, front, qlnt, qlt, tprice;
</script>
<div id="jdModal">
<div id="jdModalContent" style="padding:10px;background:#fff;">
<form id="product_form" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data">
<input type="hidden" name="size" value="0" />
<input type="hidden" name="fold" value="0" />
<input type="hidden" name="back" value="0" />
<input type="hidden" name="front" value="0" />
<input type="hidden" name="qlnt" value="0" />
<input type="hidden" name="qlt" value="0" />
<input type="hidden" name="tprice" value="0" />
<input type="hidden" name="productName" value="Business Card" />
<h2>CONTACT US</h2>
<div><label>Business Name*</label><input type="text" name="businessName" value="" /></div>
<div><label>Your Name*</label><input type="text" name="yourName" value="" /></div>
<div><label>Email*</label><input type="text" name="yourEmail" value="" /></div>
<div><label>Phone*</label><input type="text" name="yourPhone" value="" /></div>
<div><label>Delivery Region*</label><input type="text" name="deliveryRegion" value="Christchurch" /></div>
<div><label>Employees</label><input type="text" name="employees" value="1-5 staff members in my business" /></div>
<div><label> </label><p class="note">If required please upload your files here (2 MB max).</p></div>
<div style="position:relative"><label>Upload file</label><input type="hidden" value="" id="jd_upload_uri_1" name="jd_upload_uri_1" /><input type="text" class="jd_upload_filename" name="jd_upload_file_1" readonly="readonly" /><input type="button" class="jd_upload" id="jd_upfile_1"value="Browse ..." />
</div>
<div style="position:relative"><label>Upload file</label><input type="hidden" value="" id="jd_upload_uri_2" name="jd_upload_uri_2" /><input type="text" class="jd_upload_filename" name="jd_upload_file_2" readonly="readonly" /><input type="button" class="jd_upload" id="jd_upfile_2" value="Browse ..." />
</div>
<div style="position:relative"><label>Upload file</label><input type="hidden" value="" id="jd_upload_uri_3" name="jd_upload_uri_3" /><input type="text" class="jd_upload_filename" name="jd_upload_file_3" readonly="readonly" /><input type="button" class="jd_upload" id="jd_upfile_3" value="Browse ..." />
</div>
<div><label>Message</label><textarea name="msg"></textarea></div>
<div><label>I'm also interested in</label><p><input type="checkbox" name="interests[]" value="Business Cards" /><span>Business Cards</span><input type="checkbox" name="interests[]" value="Flyer" /><span>Flyer</span></p></div>
<div style="margin-bottom:15px"><label> </label><p><input type="checkbox" name="interests[]" value="Booklets" /><span>Booklets</span><input type="checkbox" name="interests[]" value="Postcards" /><span>Postcards</span></p></div>
<div><label> </label><p class="note">To help us fight spam, please type the characters you see below.</p></div>
<div class="captcha_fix"><label> </label><p style="text-align:right"><input type="submit" value=" " name="productOrderForm" class="submit-product" /><input type="text" name="jd_captcha" class="jd_captcha" value="" maxlength="6" /><img src="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php?captcha" class="jd_captcha_img" /></p></div><div id="jd_msg_box"><p class="text"></p></div>
<div style="clear:both"></div>
</form>
</div>
</div>
<iframe name="formFrame" id="formFrame" src="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php?load"></iframe>
<div id="file-upload-elem">
<form id="upload_form_1" class="uploader-box uploader-box-1" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_1" class="inp-file" id="upload_file_1" /></form>
<form id="upload_form_2" class="uploader-box uploader-box-2" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_2" class="inp-file" id="upload_file_2" /></form>
<form id="upload_form_3" class="uploader-box uploader-box-3" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_3" class="inp-file" id="upload_file_3" /></form>
</div>
<script type="text/javascript">
var fileUploadElem = jQuery("#file-upload-elem").html();
jQuery("#file-upload-elem").remove();
var insertUpload, jd_error, jd_success, upload_error, jd_show_msg, invalid_captcha;
var isCustomQuote = false;
jQuery(function() {
console.log("Test");
if(jQuery("#customs").length > 0 || jQuery("#frprice").length > 0) {
jQuery("body").append(fileUploadElem);
var calculate = function() {
if(jQuery("#frprice").length > 0) {
size = (jQuery("#foldet").val()).split(":");
fold = (jQuery("#fold").val()).split(":");
back = (jQuery("#black").val()).split(":");
front = (jQuery("#front").val()).split(":");
qlnt = jQuery("#qlnt").val();
qlt = jQuery("#qlt").val();
var str = parseInt(size[0])+parseInt(fold[0])+parseInt(back[0])+parseInt(front[0])+parseInt(qlnt)+parseInt(qlt);
tprice = parseInt(str);
jQuery("h3#price span").text(tprice);
}
};
var jd_timer;
var upload_on_progress = 0;
jd_error = function(errCode) {
clearTimeout(jd_timer);
if(errCode == 0) {
jd_show_msg("Please fill all required fields (*)");
}
if(errCode == 1) {
jd_show_msg("Invalid Email Address.");
}
if(errCode == 2) {
//jd_show_msg("Invalid Email Address.");
alert("Form sending failed. Please try again later");
}
if(errCode == 3) {
alert("Invalid Action. Please Contact Administrator.");
}
};
invalid_captcha = function(x) {
if(x == 0) {
alert("Please Enter Verification Code.");
} else {
alert("Invalid Verification Code. Try Again.");
jQuery(".jd_captcha_img").each(function() {
jQuery(this).attr('src', jQuery(this).attr('src')+'&x='+Math.random());
});
}
jQuery(".jd_captcha").val("");
};
jd_success = function() {
setTimeout(function() { window.location = document.URL+"?thank-you"; },2000);
};
upload_error = function(err,uid) {
upload_on_progress--;
jQuery("input[name=jd_upload_file_"+uid+"]").val("");
alert(err);
};
insertUpload = function(data,file) {
upload_on_progress--;
var tmpData = data.split(':');
if(tmpData.length == 3) {
var tmpCounter = 0;
jQuery("input[name=jd_upload_file_"+tmpData[2]+"]").val(file);
var updateInput = jQuery("#jd_upload_uri_"+tmpData[2]);
var updateData = tmpData[0] + ":" + tmpData[1];
updateInput.val(updateData);
} else {
alert("Uploading File Error. Please Try Again Later");
}
};
jd_show_msg = function(err) {
var myBox = jQuery("#jd_msg_box");
myBox.children(".text").text(err);
timer = setTimeout(function() { myBox.hide(); },3000);
myBox.show();
};
jQuery("select").change(calculate);
jQuery("#price").click(function(){
jQuery(this).hide();
});
jQuery(".jd_upload:eq(0), .jd_upload_filename:eq(0)").css("opacity",1);
jQuery(".file_input_hidden:eq(0)").show();
var jdModal = jQuery('#jdModal').html();
jQuery('#jdModal').remove();
var uploaderBox = jQuery(".uploader-box");
jQuery(".inp-file").click(function(e) {
if(upload_on_progress > 0) {
e.preventDefault();
alert("Prevented");
}
});
var cboxTopCache = 0;
var cboxLeftCache = 0;
var fixFileWin = function() {
var fixLeft = 585;
var cboxOffset = jQuery("#colorbox").offset();
cboxLeftCache = cboxOffset.left;
cboxTopCache = jQuery("#jd_upfile_1").offset().top;
jQuery(".uploader-box-1").css("top", (jQuery("#jd_upfile_1").offset().top) + "px");
jQuery(".uploader-box-2").css("top",(jQuery("#jd_upfile_2").offset().top) + "px");
jQuery(".uploader-box-3").css("top",(jQuery("#jd_upfile_3").offset().top) + "px");
uploaderBox.css("left",(cboxLeftCache+fixLeft) + "px");
};
jQuery(window).resize(function() {
var cboxOffset = jQuery("#colorbox").offset().left;
var cboxOffset2 = jQuery("#jd_upfile_1").offset().top;
if(cboxOffset != cboxLeftCache || cboxOffset2 != cboxTopCache) {
fixFileWin();
}
});
var formOnClick = function(e) {
e.preventDefault();
isCustomQuote = (jQuery(this).attr('id') == 'frprice')?false:true;
jQuery.colorbox({html:jdModal,opacity:0.8,overlayClose:false,transition:'none', onComplete: function() {
fixFileWin();
uploaderBox.show();
jQuery(".inp-file").change(function() {
var _this = jQuery(this);
if(_this.val() != "") {
if(upload_on_progress > 0) {
alert("Upload is still in progress. Please wait.");
} else {
jQuery("input[name=jd_"+_this.attr("id")+"]").val("Uploading File.. Please Wait..");
_this.parent().submit();
upload_on_progress++;
}
}
});
if(!isCustomQuote) {
jQuery("#product_form input[name=size]").val(size[1]);
jQuery("#product_form input[name=fold]").val(fold[1]);
jQuery("#product_form input[name=back]").val(back[1]);
jQuery("#product_form input[name=front]").val(front[1]);
jQuery("#product_form input[name=qlnt]").val(qlnt);
jQuery("#product_form input[name=qlt]").val(qlt);
jQuery("#product_form input[name=tprice]").val(tprice);
}
jQuery("#colorbox #product_form").submit(function(e) {
var tmp_progress = upload_on_progress;
if(tmp_progress > 0) {
e.preventDefault();
alert("Upload in progress. Please wait.");
}
});
}, onClosed: function() {
uploaderBox.hide();
}});
};
jQuery("#frprice").submit(formOnClick);
jQuery("#customs").click(formOnClick);
if(!isCustomQuote) {
calculate();
}
}
});
</script>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar('right'); ?>
<?php get_footer(); ?>
replace
jQuery("#file-upload-elem").remove();
With
jQuery("#file-upload-elem").hide();
jQuery.remove(), completely removes the selected element from the DOM
EDIT:
To show the element when you need it use
jQuery.show()
i.e jQuery("#file-upload-elem").show();
http://jsfiddle.net/MJwFj/2/
although it looks very rough when .remove() has been commented out the form loads
uploaderBox.hide();
The code above will hide the following, the above code is safe to remove if you don't want this to happen:
<form id="upload_form_1" class="uploader-box uploader-box-1" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_1" class="inp-file" id="upload_file_1" /></form>
<form id="upload_form_2" class="uploader-box uploader-box-2" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_2" class="inp-file" id="upload_file_2" /></form>
<form id="upload_form_3" class="uploader-box uploader-box-3" action="<?php echo site_url(); ?>/wp-content/themes/ecs/formHandler.php" target="formFrame" method="post" enctype="multipart/form-data"><input type="file" name="upload_file_3" class="inp-file" id="upload_file_3" /></form>
It's not clear exactly which element is being hidden but there is also a timer that triggers after 3 seconds to hide another element. Try removing the following also:
timer = setTimeout(function() { myBox.hide(); },3000);
The first, you may set the css role display to the element you wanted to as none
.form{
display:none;
}
then you just need to show the form with jQuery .show() function on event you wanted to, such button clicked or something else. For example :
$(document).ready(function(){
$('.classOfButton').on('click',function(){
$('.form').show();
);
})
Update
if you wanted to show the form within the page are loaded, you need to put the javascript in the end of page, or if you use jQuery you just need to use .ready() function and inside of it you show up the form with some delay if necessary.
$(document).ready(function(){
$('.form').show();
})

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

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

Categories