I have a form like this
<form action="index.php" method="get">
<input type="hidden" name="id" value="1">
<input type="hidden" name="order_by" value="">
<button type="submit">Submit</button>
</form>
It has some jQuery handlers to fill in "order_by" field.
If I submit this form with empty "order_by" filed, I get an address like this: index.php?id=1&order_by=
What is the best way I can do to get following address after form submission if the "order_by" is empty: index.php?id=1 ?
you can disable empty fields so they don't get added as data
$('form').submit(function(e){
var emptyinputs = $(this).find('input').filter(function(){
return !$.trim(this.value).length; // get all empty fields
}).prop('disabled',true);
});
in php you can do like this
if(!isset($_GET['order_by']) || !$_GET['order_by'])
return 'error msg';
or
if(empty($_GET['order_by']))
return 'error msg';
change html like this
<form action="index.php" method="get" onsubmit="return valid()">
<input type="hidden" name="id" value="1">
<input type="hidden" name="order_by" id="order_by" value="">
<button type="submit">Submit</button>
</form>
javascript:
function valid(){
if(!$('#order_by').val()){
alert("Order by not found");
return false;
}
return true;
}
$('form#formID').submit(function(e){
var emptyinputs = $(this).find('select').filter(function(){
return !$.trim(this.value).length;
}).prop('disabled',true);
var emptyinputs = $(this).find('input').filter(function(){
return !$.trim(this.value).length;
}).prop('disabled',true);
});
You can disable empty fields (both select and input) so they don't get added as data, and for a custom form id.
Related
In my WordPress v5.5.3, I have two forms with same input fields in a single page:
<form id="one" method="post">
<input name="name" type="text" value="My Name">
<input name="movie" type="hidden" value="1">
<button type="submit" name="submitone">Submit</button>
</form>
<form id="two" method="post">
<input name="name" type="text" value="My Name">
<input name="movie" type="hidden" value="2">
<button type="submit" name="submittwo">Submit</button>
</form>
With the below function, I am able to save the above form data:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
save_data();
}
However, data is saved twice with the above code.
I have tried identifying the form which is submitted and save the data with below:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submitone'])) {
save_data();
}
}
This is not working and not saving the form data.
How can I identify which form is submitted and save data?
Edit 1
Below the save_data(); method:
// input variables
$name = filter_input(INPUT_POST, 'name');
$movie = filter_input(INPUT_POST, 'movie');
// Table
global $wpdb;
$tablename = $wpdb->prefix . 'names';
// Name ID
$default_row = $wpdb->get_row("SELECT * FROM $tablename ORDER BY id DESC LIMIT 1");
if ($default_row != null) {
$id = $default_row->id + 1;
} else {
$id = 1;
}
// Names
$data = array(
'id' => $id,
'name' => $name,
'movie' => $movie,
);
// INSERT DATA INTO THE TABLE
$new_name = $wpdb->insert($tablename, $data);
The easiest way in my opinion - add hidden input field to forms with something that will help you identify it. Then, when one of this forms will be submitted, only it's hidden field will be given.
Example: <input type="hidden" name="formn" value="1"> and then in $_POST['formn'] you will have '1'.
Check out the following code.
The page template containing two form and the same page template is used to process Form Post method.
You might want to change the input field name 'name' and add a prefix to it to make it unique. ('my_name' in this code example) . Wordpress treats some field names in a form input as reserved keywords. WordPress behaves in strange way if you use any of the reserve names.
<?php
/**
* Template Name: Form Template
* Author: Meera Datey
* Template Post Type: post, page
*/
// Handle POST Submission here.
if(isset($_POST['submitone'])) {
print_r('First Form submitted');
$my_name = $_POST['my_name'];
// This should have input name from first form
print_r($my_name);
save_data();
}
if(isset($_POST['submittwo'])) {
print_r('Second Form submitted');
$my_name = $_POST['my_name'];
// This should have input name from second form
print_r($my_name);
//save_data();
}
?>
<!-- This is a GET Request -->
<form method="post" action="<?php the_permalink(); ?>">
<input name="my_name" type="text" value="My Name">
<button type="submit" name="submitone">Submit</button>
</form>
<form method="post" action="<?php the_permalink(); ?>">
<input name="my_name" type="text" value="My Name">
<but
ton type="submit" name="submittwo">Submit
You should use the wordpress core:
<form id="one" method="post">
<input name="name" type="text" value="My Name">
<input name="movie" type="hidden" value="1">
<input type="hidden" name="action" value="submitone">
<button type="submit" name="submitone">Submit</button>
</form>
<form id="one" method="post">
<input name="name" type="text" value="My Name">
<input name="movie" type="hidden" value="1">
<input type="hidden" name="action" value="submitone">
<button type="submit" name="submittwo">Submit</button>
</form>
function submitone_handle_form_submit() {
// here $_POST
}
// Use your hidden "action" field value when adding the actions
add_action( 'admin_post_nopriv_submitone', 'submitone_handle_form_submit' );
add_action( 'admin_post_submitone', 'submitone_handle_form_submit' );
function submittwo_handle_form_submit() {
// here $_POST
}
// Use your hidden "action" field value when adding the actions
add_action( 'admin_post_nopriv_submittwo', 'submittwo_handle_form_submit' );
add_action( 'admin_post_submittwo', 'submittwo_handle_form_submit' );
Say I have a HTML form that lets you input a name and age and returns with a list of people with that name and age.
<form method="post" action="/search_results">
<input type="text" name="personName">
<input type="text" name="personAge">
<input type="submit" value="Submit!">
</form>
And on the search results page I have a list of the results, but I only display 50 at a time and allow users to go forwards/backwards between the page with buttons. So the results page would also look for a POSTed 'pageNumber' value and default to 0 if there is none.
When they click a button, how would I resubmit the age and name and also submit the corresponding pageNumber from the button?
I'm using PHP
Add a hidden field to the form:
<form name=search"" method="post" action="/search_results">
<input type="hidden" name="pageNumber"
value="<?php echo isset($_POST['pageNumber']) ? (int) $_POST['pageNumber'] : 0; ?>">
<input type="text" name="personName">
<input type="text" name="personAge">
<input type="submit" value="Submit!">
</form>
Add a JavaScript function to modify the hidden field value:
<script>
function search(pageNumber) {
var form = document.forms.search;
if (!form) return;
form.elements.pageNumber.value = pageNumber;
form.submit();
}
</script>
Apply the JavaScript function for the page buttons:
<span onclick="search(1)">1</span>
<span onclick="search(2)">2</span>
Obviously, the buttons should be generated with PHP in the following manner:
<?php
for ($p = 0; $p < $pagesNum; ++$p) {
echo "<span onclick='search($p)'>$p</span>";
}
?>
<form method="post" action="/search_results">
<input type="text" name="personName" value="<?php echo (isset($formdata['personName'])?$formdata['psersonName']:"") ?>">
<input type="text" name="personAge" value="<?php echo (isset($formdata['personAge'])?$formdata['personAge']:"") ?>">
<input type="hidden" name="currentPage" value="<?php echo (isset($formdata['currentPage'])?$formdata['currentPage']:"0") ?>">
<input type="submit" value="Submit!">
</form>
formdata are the data which are the inputs of the previous submit. These data should be returned by the search_results page along with the view.
Below is the js
<script>
$(document).ready(function(){
$(".paginationBtns").click(function(){
var page = $(this).attr('pageValue');
$("input[name='current']").val(page);
$("form").submit();
});
});
</script>
Assumptions of the forward and backward button
<a href="#" pageValue=0>Back</a><a href="#" pageValue=50>Next</a>
You have to append the back and next pageValue while loading each page.
The best practice in pagination to use a simple link that contains the parameres (GET) and not (POST). That way, when you have the parameters in the url you can cache it, add to favorites, get indexed by google, share your page in email/facebook etc.
<a href='http://example.com/?personName=<?=$_POST['personName']?>&personAge=<?=$_POST['personAge']?>&page=<?=$next_page_number?>'>Next</a>
If for some reason you must or really want to use POST you can save the values in hidden inputs within a form in the page and then sumbit it when clicking on "next page" button.
Form example:
notice its just an example you should sanitize the variables and not put them directly from the $_POST
<form name="pagination" method="post" action="/search_results">
<input type="hidden" name="page" id="page" value="2">
<input type="hidden" name="personName" value='<?=$_POST['personName'];?>'>
<input type="hidden" name="personAge" value='<?=$_POST['personAge'];?>'>
</form>
notice that we set the next page numbers & do submit by using a command from the form of:
<button onclick='document.getElementById("page").value= "2";document.pagination.submit();'>Next page</button>
I have seen this done before but not sure how.
I am trying to have a search form go to pagename.php?q=[searchquery] so i can then get the searchquery from the address.
here is the form
<form class="sidebar-search">
<div class="input-box">
<input type="text" placeholder="Quick Product Search..." />
<input type="button" class="submit" value="" />
</div>
</form>
Here is the JS
// handle the search query submit on enter press
$('.sidebar-search input').keypress(function (e) {
if (e.which == 13) {
window.location.href = "search_results.php";
return false; //<---- Add this line
}
});
// handle the search submit
$('.sidebar-search .submit').click(function () {
if ($('.page-container').hasClass("sidebar-closed")) {
if ($('.sidebar-search').hasClass('open') == false) {
$('.sidebar-search').addClass("open");
} else {
window.location.href = "search_results.php";
}
} else {
window.location.href = "search_results.php";
}
});
Can anyone help with this?
You wouldn't actually need to do it using javascript
<form class="sidebar-search" method="get" action="search_results.php">
<div class="input-box">
<input type="text" placeholder="Quick Product Search..." />
<input type="submit" class="submit" value="" />
</div>
</form>
The action attibute defines the location (an URL) where the form's collected data should be sent.
The method attribute defines which HTTP method to send the data with (it can be "get" or "post").
This would probably help understand in detail.
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/My_first_HTML_form?redirectlocale=en-US&redirectslug=HTML%2FForms%2FMy_first_HTML_form
But if you still need to use javascript here the answer
define an id for the search field as below
<input type="text" id="txtSearch" placeholder="Quick Product Search..." />
and then
var searchString = $('#txtSearch').val();
window.location.href = "search_results.php?q=" + searchString;
Do this:
window.location.href = "search_results.php?q=" + $(".sidebar-search input[type=text]").val();
Or you can give an id to the search and get the value of the element with that ID.
if you hit enter/submit you go to search.php?query=value
<form method="get" action="search.php" >
<input name="query" type="text" />
<input type="submit" value="search" />
</form>
I have a form, that is this one
<form method="get" action="<?php bloginfo('url'); ?>">
<input name="date-beginning" type="text" class="datepicker" />
<input name="date-end" type="text" class="datepicker" />
<input name="s" type="text" />
<input type="submit" value="Ok" class="botao-pequeno botao-pequeno-input" />
</form>
Well, when the user sends all the fields, we get this response:
http://myblogurl.com/?s=example&date-beginning=05/05/05&date-end=07/07/07
If he doesn't fill, for example the date-beginning field we get http://myblogurl.com/?s=example&date-beginning=&date-end=07/07/07
What I want is that if he doesn't fill the field, for example date-beginning, the form still be sent, but variable don't to get sent, like this: http://myblogurl.com/?s=example&date-end=07/07/07
Is there a way to do it? How?
var form = document.forms[0];
form.addEventListener('submit', function(){
var a = document.getElementsByName('date-beginning')[0];
if(a.value === '')
a.disabled = true;
});
karaxuna's anwser works. I just adapted it to jQuery, if any one is interested, this is the code
$("#the-form").submit(function() {
if($('#the-field').val() === ''){
$('#the-field').attr('disabled',true);
}
if($('#the-other-field').val() === ''){
$('#the-other-field').attr('disabled',true);
}
});
I have a submit form for a URL and I want it to have specific behavior which I am not able to achieve so far. Initially I want the button to be enabled. After someone enters a URL and hits the "submit" button, I want to call my checkURL() function. If the function returns true, I want the button to become disabled and I want to then open remote_file.php. If it returns false, I want the button to be enabled and make them try another URL.
<form name=URLSubmitForm
action="remote_file.php"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000">
<input type="text" name="name" size="50">
<input type="submit"
onchange="this.disabled=false"
onclick="this.disabled=true; checkURL();"
value="submit">
</form>
Edit: It looks like I was just putting the onchange in the wrong place. I ended up doing this to fix reenabling the button
<input type="text" onchange="submit.disabled=false" name="name" size="50">
Thanks!
I would propose that you attach the event handling code to the form's onsubmit event, not the button event(s). What you're trying to control is whether or not the form is posted. The button being disabled while your validation logic runs is a secondary goal.
Try this instead:
<script type="text/javascript">
function checkURL(){
var submitButton = document.getElementById('submitButton');
submitButton.disabled=true;
/* implement your validation logic here
if( url is invalid ){
submitButton.disabled=false;
return false;
}
*/
// everything is valid, allow form to submit
return true;
}
</script>
<form name="URLSubmitForm" action="remote_file.php" onsubmit="return checkURL();" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000">
<input type="text" name="name" size="50">
<input type="submit" name="submitButton" id="submitButton" value="submit">
</form>
<input type="submit"
onclick="if (checkURL()) { this.disabled='disabled'; return true; } else { return false; }"
value="submit">
How about in the form's onsubmit event:
<form onsubmit="(function(){
if(checkURL()){
this.elements['submit'].disabled = 'disabled';
}
else{
return false;
}
})()">
Since you haven't given any ajax code, the form will still be submitted normally and when the page is reloaded the button will be enabled again.
onclick="checkURL(this);"
function checkURL(arg){
this.disabled=true;
if(<something>) this.disabled=false;
}