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;
}
I'm developing a WordPress theme and I have a PHP function that is supposed to handle and asynchronous request that gives the server both JSON and an image. My form (for readability, stripped of a bunch of inner HTML) looks like
<form method="POST" action="member-update" enctype="multipart/form-data" id="member-form">
9">
<input type="text" name="fullname" value="">
<input type="text" name="title" value="">
<textarea rows="4" name="bio" form="member-form"></textarea>
<input type="text" name="sord" value="">
<input type="file" name="pic">
<input type="hidden" name="memberAction" value="" />
</form>
and my JavaScript for making the AJAX request is
jQuery('.member-update-button').click( function() {
var parentForm = jQuery(this).closest('form');
var postData = parentForm.serializeArray();
jQuery.post( ajaxurl,
{'action': 'member_update', 'formStuff' : postData},
function(response) { alert('Got this from the server: ' + response); }
);
});
and my PHP function that, through a WordPress hook, handles the request starts out like
function member_update ( )
{
// there must be a more elegant way of getting those values out ....
$name = $_POST['formStuff'][0]['value'];
$title = $_POST['formStuff'][1]['value'];
$bio = $_POST['formStuff'][2]['value'];
$sord = $_POST['formStuff'][3]['value'];
$targetFileName = basename($_FILES['pic']['name']);
$targetFileNameAndPath = 'assets/' . $targetFileName;
I'm getting values out of the $_POST['formStuff'] array, but I am getting nothing for the $_FILES['pic']['name']. Any idea what I'm doing wrong?
You need to use an instance of FormData.
Make following changes in your code.
Add id attribute in your html
<input type="file" name="pic" id="pic">
Changes in js code
jQuery('.member-update-button').click( function() {
formdata = new FormData();
formdata.append( 'action', 'member_update' );
jQuery.each(jQuery('#pic')[0].files, function(i, file) {
formdata.append('file_to_upload', file);
});
jQuery.post( ajaxurl, formdata,function(response) {
alert('Got this from the server: ' + response);
});
});
Finally changes in php function
function member_update()
{
$file = $_FILES['file_to_upload']['tmp_name'];
}
I am using a form with the method of GET to add to the query string.
I am running into an issue. When the form is submitted every field is sent and added to the query including with no values.
Example:
http://web.com/?filter-types=news&filter-document-type=&filter-topics=we-have-a-topic&filter-featured=&filter-rating=
Can I not add these to the query string if they are not set? !isset() or is there another way to do this?
You could alternatively manipulate the form inputs thru javascript, just a Mike said in the comments, on submit check the fields, if empty, disable them so that they wont be included on submission.
This is just the basic idea (with jQuery):
<form method="GET" id="form_inputs">
<input type="text" name="field1" value="field_with_value" /><br/>
<input type="text" name="field2" value="" /><br/><!-- empty field -->
<input type="text" name="field3" value="field_with_value" /><br/>
<input type="submit" name="submit_form" id="submit_form" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[name="submit_form"]').on('click', function(e){
e.preventDefault();
$('form').children().each(function(i, e){
if($(e).is('input') && $(this).val() == '') {
$(this).prop('disabled', true);
// or $(this).attr('name', '');
}
});
$('form').submit();
});
</script>
Or if you do not want to use jquery at all:
document.getElementById('submit_form').addEventListener('click', function(e){
e.preventDefault();
var children = document.getElementById('form_inputs').childNodes;
for(i = 0; i < children.length; i++) {
if(children[i].type == 'text' && children[i].value == '') {
children[i].disabled = true;
}
}
document.getElementById('form_inputs').submit();
});
The reason all those keys show up in query string is because they exist as inputs in the form. If you don't want them sent, remove them from the form, or at least give them some meaningful defaults.
I guess you are looking a condition
if (!empty($_POST['var'])) {
}
OR
if (!isset($_POST['var']) && !empty($_POST['var'])) {
}
So I am creating a website that tracks a user's Shooting Score for Rifle Competitions. I have a Create Match tab, which brings them to a page containing a
Weapon Selection drop down, then a Date input, then a Location input, and then I have a Save Match button which will send these three inputs to a database along with a uniqueID (primary key, auto incremented) which will allow them to distinguish which match is which.
Now for each match you can create a String of Fire which the user can select. So on the same page, I have when the user presses Save Match, it sends the data, and then brings up another Dropdown box which houses the 4 String of Fire modes (200 yd slow, 200yd rapid, 300yd rapid, 600yd slow). And then a Create String button next to that which will bring down 10 target scores they can fill in after they push the button. the problem I am having is that when this button is pushed, it deletes the Create String dropdown box and button as well, and I'm not entirely sure what's wrong. I think it has something to do with how I'm using POST and that I am just creating a dropdown + button when they push Save Match....
Sorry for the long block of text, I'll try to break it down more if that was too confusing.
So basically I want to be able to push the first button (And retain w/e the user put in which I have working), and then it brings up a dropdown with 4 entries and a button, and then when that second button is created, a table of 10 entries is brought up, with a Save button, and when THAT button is pushed, it sends the 10 entries to the database. I can get the database transfer stuff working, I just need the creating more functional buttons/text inputs to work first.
Thank you for your time!
Code for HTML
<form name="table" action ='' method="post">
Rifle:
<select name="wpn" id="wpn">
<option>AR15</option>
<option>HK416</option>
<option>M1 Garand</option>
<option>M14</option>
<option>M4/M16</option>
<option>M24</option>
<option>SSG500</option>
<option>SSG556</option>
</select>
Date: <input type="date" name = "date" id="date" value = "<?php echo $_POST['date']; ? >">
Location:<input type="text" name="loc" id="loc" value = "<?php echo $_POST['loc']; ?>" />
<button type="submit" name = "save" value="Save Match">Save Match</button>
Code for PHP
<?php
//if ($_SERVER['REQUEST_METHOD'] == "POST"){
if($_POST['save'] == 'Save Match'){
if($_POST["date"]==NULL){
apologize("Please enter a valid date!");
}
else if($_POST["loc"]==NULL){
apologize("Please enter a location!");
}
$id = $_SESSION['id'];
$wpn = $_POST['wpn'];
$date = $_POST['date'];
$loc =$_POST['loc'];
//if(isset($_POST['button'])){
if(query("INSERT INTO matches (id, weapon, date, location)
VALUES (?, ?, ?, ?)",
$id, $wpn, $date, $loc) === false){
apologize("Sorry insertion of data failure!!!");
}else{
// redirect("../public/matches.php");
//header("Location: ../public/matches.php");
?>
<br /><br />
Strings of Fire:
<select name="mode" id="mode">
<option>200 Yard Slow</option>
<option>200 Yard Rapid</option>
<option>300 Yard Rapid</option>
<option>600 Yard Slow</option>
</select>
<button type="submit" name="save" value="Create String">Create String</button>
<?php
if(($_POST['save']) == 'Create String'){
echo test;
}
}
}
?>
</form>
Okay, this is a work-in-progress, but here goes.
I split what you've shown into two separate files; here's the UI page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Shooting Scores for Rifle Competitions</title>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<style>
body {
background: #e8e8e8;
}
.step {
width: 50%;
margin: 1em auto;
padding: 1em;
background: #fff;
}
#step1 select.weapon,
#step2 select.fire-string
{
width: 50%;
}
#step1 input.date
{
width: 10em;
}
#step3 ol.scores-list li
{
margin-bottom: 1em;
}
#step3 input.score
{
width: 8em;
}
</style>
</head>
<body>
<div class="container">
<?php
require('process.php');
?>
<div id="step1" class="step">
<form class="table" action="" method="post" id="step1-form" role="form">
<div class="form-group">
<label>Rifle:</label>
<select name="wpn" id="wpn" class="form-control weapon">
<option>AR15</option>
<option>HK416</option>
<option>M1 Garand</option>
<option>M14</option>
<option>M4/M16</option>
<option>M24</option>
<option>SSG500</option>
<option>SSG556</option>
</select>
</div>
<div class="form-group">
<label>Date:</label>
<input type="date" name="date" id="date" value="<?php echo $_POST['date']; ?>" class="form-control date" />
</div>
<div class="form-group">
<label>Location:</label>
<input type="text" name="loc" id="loc" value="<?php echo $_POST['loc']; ?>" class="form-control" />
</div>
<button type="submit" name="save-match" id="save-match" value="step1" class="btn btn-default">Save Match</button>
</form>
</div>
<div id="step2" class="step hide">
<form class="table" action="" method="post" id="step2-form" role="form">
<div class="form-group">
<label>Strings of Fire:</label>
<select name="mode" id="mode" class="form-control fire-string">
<option>200 Yard Slow</option>
<option>200 Yard Rapid</option>
<option>300 Yard Rapid</option>
<option>600 Yard Slow</option>
</select>
</div>
<button type="submit" name="save-string" id="save-string" value="step2" class="btn btn-default">Create String</button>
</form>
</div>
<div id="step3" class="step hide">
<form class="table" action="" method="post" id="step3-form" role="form">
<div class="form-group">
<label>Target Scores:</label>
<ol class="scores-list">
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
<li>
<input type="text" name="scores[]" class="form-control input-sm score" value="" />
</li>
</ol>
</div>
<button type="submit" name="save-scores" id="save-scores" value="step3" class="btn btn-primary">Save Scores and Finish!</button>
</form>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(function () {
// http://api.jquery.com/on/
$(document)
.on('click', '#save-match', function (e) {
e.preventDefault();
var button = $(this);
// http://api.jquery.com/serialize/
var form = $('#step1-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
// http://api.jquery.com/jquery.post/
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
// http://api.jquery.com/slidetoggle/
$('#step1').slideToggle('slow', function () {
// http://api.jquery.com/removeclass/
$('#step2').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-string', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step2-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
$('#step2').slideToggle('slow', function () {
$('#step3').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-scores', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step3-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
alert(result);
})
.fail(function () {
});
});
});
</script>
</body>
</html>
Here's the server script:
<?php
if(isset($_POST['save-match']))
{
$is_valid = true;
# step 1
if(empty($_POST["date"]))
{
$is_valid = false;
apologize("Please enter a valid date!");
}
if(empty($_POST["loc"]))
{
$is_valid = false;
apologize("Please enter a location!");
}
if($is_valid)
{
$id = $_SESSION['id'];
$wpn = $_POST['wpn'];
$date = $_POST['date'];
$loc =$_POST['loc'];
if(!query("INSERT INTO matches (id, weapon, date, location) VALUES (?, ?, ?, ?)", $id, $wpn, $date, $loc))
{
apologize("Sorry insertion of match data failure!!!");
}
else
{
# step 1 finished successfully.
}
}
}
else if(isset($_POST['save-string']))
{
# step 2
if(empty($_POST["mode"]))
{
apologize("Please enter a valid mode!");
}
else
{
$id = $_SESSION['id'];
$mode =$_POST['mode'];
if(!query("YOUR QUERY HERE TO INSERT / UPDATE MODE", $id, $mode))
{
apologize("Sorry insertion of mode data failure!!!");
}
else
{
# step 2 finished successfully.
}
}
}
else if(isset($_POST['save-scores']))
{
echo "Received " . count($_POST['scores']) . " scores!";
# step 3
if(empty($_POST["scores"]))
{
apologize("Please enter your scores!");
}
else
{
$id = $_SESSION['id'];
$scores = $_POST["scores"]; # this will be an array
if(!query("YOUR QUERY HERE TO INSERT / UPDATE SCORES", $id, $scores))
{
apologize("Sorry insertion of scores data failure!!!");
}
else
{
# step 3 finished successfully.
}
}
}
else
{
# assuming a GET request at this point
}
?>
I obviously have no idea what your apologize() or query() functions are. For sake of the example I'm choosing to assume apologize() simply echos a string, or perhaps throws an exception. The important bit is the script section at the end of the UI page:
$(function () {
// http://api.jquery.com/on/
$(document)
.on('click', '#save-match', function (e) {
e.preventDefault();
var button = $(this);
// http://api.jquery.com/serialize/
var form = $('#step1-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
// http://api.jquery.com/jquery.post/
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
// http://api.jquery.com/slideToggle/
$('#step1').slideToggle('slow', function () {
// http://api.jquery.com/removeclass/
$('#step2').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-string', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step2-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
$('#step2').slideToggle('slow', function () {
$('#step3').removeClass('hide');
});
})
.fail(function () {
});
})
.on('click', '#save-scores', function (e) {
e.preventDefault();
var button = $(this);
var form = $('#step3-form').serialize()
+ '&'
+ encodeURI(button.attr('name'))
+ '='
+ encodeURI(button.attr('value'));
$.post('/process.php', form)
.done(function (result, status, jqxhr) {
alert(result);
})
.fail(function () {
});
});
});
I've included links to each jQuery function where it's first used, so I'd recommend reading the manual for each one at some point. Here's what happens:
To begin, we bind "event listeners" for each of the submit buttons, using .on(). By hanging the listeners off of document, we can make sure the listeners still work even if the forms or buttons get replaced at some point. When using .on(), the first argument is the specific event we want to handle (in this case, the click event). The second argument defines a filter; basically, only handle a click event if an element matching that selector was the trigger. The last argument is a function to call when event needs to be handled.
Next, we get a reference to the button that triggered the event (which we'll use in a second). We then call jQuery's .serialize() on the relevant form for this button, which generates a form-encoded string we can use to post the form asynchronously (more on that in a minute). Unfortunately for our PHP script, the serialize function does not include the button in the string (for reasons beyond the scope of this question), so we have to manually append the relevant values to the string.
Continuing on, we use jQuery's $.post() function to send our serialized data to the server, where it will be processed as if it were a normal POST. $.post() has a few functions that we can use to handle the result of the POST; the two I mostly use are .done() and .fail(). .done() will be called if the request was successful (meaning it returned a 3xx HTTP code) and .fail() is called for 4xx or 5xx HTTP codes.
Finally, when receiving a successful response, we hide the current step and show the next, until we get to the last step. From there I would assume you either return to the initial view, or show some sort of success message...
I basically repeat the same logic for the three "steps" you've outlined. What this particular script does is hide and show each step as your user walks through it. It's obviously incomplete, so let me know where to elaborate.
NOTE: I've included links to CDN versions of both jQuery and Bootstrap (just to make the UI look a little less plain and take advantage of some helper classes).
I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>