How can I create a custom form in WordPress? - php

I have a WordPress site and would like to create a form (input → database).
I've seen two tutorials:
How you can easily create customized form in WordPress
How to create custom forms in WordPress without using plugins?
They're both very similar. Creating the front end with HTML and JavaScript, and then processing the information to the database using PHP.
My problem is that whenever I submit the form, it shows a 404 page which says:
Oops! That page can’t be found.
Now my problem is (or I want to know):
Where do I need to put the process.php file? (I'm using FileZilla). I've tried several places in the public_html/wp-content folder.
Why aren't the name and email fields being validated? (no alert for empty name field, etc.)
Form structure:
Your Name: [TEXT], Your Email: [TEXT], Sex: [*male *female], Your Age:[TEXT], [Submit Button]
Form page:
<form name="myForm" method="POST" onsubmit="return form_validation()" action="../process.php">
Your Name: <input id="customer_name" name="customer_name" type="text" />
Your Email: <input id="customer_email" name="customer_email" type="text" />
Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female
Your Age: <input id="customer_age" name="customer_age" type="text" />
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function form_validation() {
/* Check the Customer Name for blank submission */
var customer_name = document.forms["myForm"]["customer_name"].value;
if (customer_name == "" || customer_name == null) {
alert("Name field must be filled.");
return false;
}
/* Check the Customer Email for invalid format */
var customer_email = document.forms["myForm"]["customer_email"].value;
var at_position = customer_email.indexOf("#");
var dot_position = customer_email.lastIndexOf(".");
if (at_position < 1 || dot_position < at_position + 2 || dot_position + 2 >= customer_email.length) {
alert("Given email address is not valid.");
return false;
}
}
</script>
File process.php (not edited):
<?php
$customer_name = $_POST["customer_name"];
$customer_email = $_POST["customer_email"];
$customer_sex = $_POST["customer_sex"];
$customer_age = $_POST["customer_age"];
$conn = mysqli_connect("Database Host", "Database Username", "Database Password", "Database Name");
if(!$conn) {
die(‘Problem in database connection: ‘ . mysql_error());
}
$query = "INSERT INTO ‘Database Name’.’Table Name’ ( ‘customer_name’, ‘customer_email’, ‘customer_sex’, ‘customer_age’ ) VALUES ( $customer_name, $customer_email, $customer_sex, $customer_age )";
mysqli_query($conn, $query);
header("Location: my-site.com/success"); // Redirects to success page
?>

To answer question one: WordPress provides action and filter hooks for developers to add their custom PHP code or functions. You should look into that, because using plugins that produce snippets will not help in your case, because it causes your PHP code to execute without even loading your form, so you will be seeing your success page instead.
To learn more about action and filter hooks visit here.
Alternatively to us action/filter hooks, you can upload your PHP file into the theme folder. However, there's a flaw to that. Your file may be lost when WordPress updates.
To answer question two: There is an easier way to validate your form if using JavaScript. All you need to do is add the word 'required' within the input tag. You can also use input type 'email' together with the required keyword to validate you email. See the example below.
<form name="myForm" method="POST" action="../process.php">
Your Name: <input id="customer_name" name="customer_name" type="text" required/>
Your Email: <input id="customer_email" name="customer_email" type="email" required/>
Sex: <input name="customer_sex" type="radio" value="male" />Male <input name="customer_sex" type="radio" value="female" />Female
Your Age: <input id="customer_age" name="customer_age" type="text" />
<input type="submit" value="Submit" />
</form>
If you still want to use your JavaScript function, try using document.getElementById('customer_name') and document.getElementById('customer_email') instead of document.forms. Also make sure you close your script tag at the end. See below for an example.
<script type="text/javascript">
function form_validation() {
/* Check the Customer Name for blank submission */
var customer_name = document.getElementById('customer_name').value;
if (customer_name == "" || customer_name == null) {
alert("Name field must be filled.");
return false;
}
/* Check the Customer Email for invalid format */
var customer_email = document.getElementById('customer_email').value;
var at_position = customer_email.indexOf("#");
var dot_position = customer_email.lastIndexOf(".");
if (at_position < 1 ||
dot_position < at_position + 2 ||
dot_position + 2 >= customer_email.length) {
alert("Given email address is not valid.");
return false;
}
}
</script>

Related

How to add input value to URL in php

I have a question from php and I'm not expert in php.
1.I have html page with one form include a text box and submit button .
2.I have a static target url like this : https://example.com/invoice/XXXXXXXXXXXXXX
XXXXXXXXXXXXXX is just numbers and has 14 characters.
*** What I need is that my customer enter its 14 characters number in input text form and when it submit , goes to target url.I want to check input form for entry numbers too.
I make a sample form like this but not work:
<form action="https://example.com/invoice" class="pey-form" method="get">
<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="submit" value="submit">
</form>
What can I do?
As hassan said , you can do this only with javascript.
This will redirect to the url what you desired.
document.querySelector("form").onsubmit = function(){
this.setAttribute("action",this.getAttribute("action")+"/"+document.querySelector("[name=peyid]").value);
}
For example
If document.querySelector("[name=peyid]").value = 12345678901234 The url will look like https://example.com/invoice/12345678901234?peyid=12345678901234
So if you just need to redirect to that url you don't even need form just
<input type="text" id="peyid" name="peyid" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" maxlength="14" ><br><br>
<input type="button" value="submit">
<script>
document.querySelector("[type=button]").onclick = function(){
location.href = `https://example.com/invoice/${document.querySelector("[name=peyid]").value}`;
}
</script>
Using PHP—to receive a form value, validate it, apply it to a URL, and redirect the client to that location, use $_POST, preg_match(), string interpolation, and header().
/invoice/index.php:
<?php
if ( isset($_POST['peyid']) && preg_match("/^\d{14}$/", $_POST['peyid']) ) {
header("Location: http://www.example.com/invoice/{$_POST['peyid']}");
exit;
}
?>
<html><head><title>oops</title></head><body>An error occurred.</body></html>

Multiple Forms, check input from all with one submit button

I've got multiple forms like this on one page:
<form method="post" action="#">
<input type="hidden" name="product_id" value="'.$item['articlenumber'].'" />
<input type="text" name="update_quantity" value="'.$pg->quantity.'" />
<input type="hidden" name="packing" value="'.$item['packing'].'" />
<input type="hidden" name="unit" value="'.$item['unit'].'" />
<input type="submit" name="addtocart" value="Update" />
</form>
And I've got one submit button at the bottom:
<input name='placeorder' type='submit' value='Place order' />
How can I check all forms when I press the submit button? I need to validate that the input that was given is the correct quantity.
UPDATE
I now got all the values from the forms in JavaScript and the validation is correct. Now I want to store the variables into PHP SESSIONS. I saw the answer from Ben and that would work if the values where in PHP, they are now in JavaScript. I need them on other pages so I thought Sessions would be the best thing here (if not, other suggestions are welcome).
I saw this answer and there they say it is not possible on one page. I understand that because PHP is server side and Javascript client side. Is this the only possible way to send Javascript variables to PHP?
Alright, first you should remove the type='submit' on the input. So change it to :
<input name='placeorder' value='Place order' />
Then you just need to add a javascript function to validate.
$(document).ready(function() {
$("input [name='placeorder']").click(function() {
var formOK = true;
$("form input").each(function(index, element) {
var value = $(element).val();
if (value != "OK") {
formOK = false;
}
});
if (formOK) {
submitForms();
} else {
alert("Form Input Inccorect");
}
});
});
function submitForms() {
$("#form1").add("#form2").submit();
}
With regards to your question about storing form data in a session variable Try something along these lines:
session_start();
if (isset($_POST['placeorder'])) {
$_session['ProductID'] = $_POST['product_id'];
$_session['UpdateQuantity'] = $_POST['update_quantity'];
$_session['Packing'] = $_POST['packing'];
$_session['Unit'] = $_POST['unit'];
}
Hope that helps
Both answers helped me a little bit but I needed to combine them so I ended up with a solution like the following. I got the values from the inputs by their unique name like this:
var sizeS25 = parseInt($("input[name='size-s25']").val(), 10) || 0;
var sizeM25 = parseInt($("input[name='size-m25']").val(), 10) || 0;
Then I send the variables to a PHP file:
window.location.href = "phpsessions.php?sizeS25=" + sizeS25 + "&sizeM25=" + sizeM25;
In the PHP file I set the variables as sessions:
$_SESSION['sizeS25'] = $_GET['sizeS25'];
$_SESSION['sizeM25'] = $_GET['sizeM25'];

when working with php sessions form input data not getting save

Hey i have having a problem i just found working with session i am using at the moment firefox 23 but i have check that on some other browsers as well.
I have created a simple code where i have created a form and just opened a session and i have noticed that once i have submit the form and then click on "Go Back" to return to the page the info i have inserted is not saved on the browser.
Normally when you submit a form once you go back the data you have entered is saved and you can just edit the inputs and resent it but when i have used session_start() on the page that function stopped working.
Well i am guessing maybe the browser save the form data in sessions as well and once i use it in php it's somehow effect the normally way the browser work.
I hope someone know how i can fix that i know you are able to save sessions with html5 and javascript now but i would rather do that with php.
Attached below is the code i have been using:
<?php
session_start();
// store session data
$_SESSION['name']= "name";
?>
<form method="post" action="index.php">
<input type="text" name="email" placeholder="Email" /><br />
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The browser refilling the form is simply that, the browser. This is not something you should rely upon for form re-population.
Your PHP code does not attempt to refill the form by printing anything within the input value="" attributes.
Generally when a form is submitted a programmer will validate the submitted values, store them in some fashion (the session is fine) and if they need them to reappear on the form they will print those values back out like I described.
I think you want to put the CORRECT fields back into the form values and blank out the incorrect ones. You don't have to use sessions:
<?php // formx.php
// accept POST variables
$fld1 = isset($_POST['fld1']) ? $_POST['fld1'] : "";
$fld2 = isset($_POST['fld2']) ? $_POST['fld2'] : "";
// edit variables
$errmsg = "";
if (!$fld1 == "") { if($fld1 <> "1") { $errmsg .= "fld1 is not 1<br />\n"; $fld1 = ""; } }
if (!$fld2 == "") { if($fld2 <> "2") { $errmsg .= "fld2 is not 2<br />\n"; $fld2 = ""; } }
if ($errmsg == "") { $errmsg = "Values accepted"; }
// output form
$body = <<<EOD
<html>
<body>
<div>%s</div><!-- errmsg -->
<form name="formnm" action="formx.php" method="post">
Enter "1" <input type="text" name="fld1" value="%s" /><br />
Enter "2" <input type="text" name="fld2" value="%s" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
EOD;
printf($body, $errmsg, $fld1, $fld2);
?>

Jquery returning ObjectObject, first two fields return as expected

I was wondering if someone could help me out as I have googled for quite a while today, and haven't found anything to solve my problem.
The websites I've looked at mentioned it's because it's returning JSON, but they are getting it on all the fields, not just the one.
But what I can't understand, is why isn't the first two fields as well? Hence my confusion
I am submitting a login form, using Jquery and AJAX (I'm knew to this).
The first two fields (email and pass) submit, and return as expected.
For testing purposes I simply return their values in <span id="loginresponse"></span>.
I have a third field, to prevent CSRF, called 't' (named it random names, to see if this was the problem - I still get [object Object] returned). <input type="hidden" name="t" value="RandomToken"/>
When submitting the form, I expect it to return what I entered into the fields - "Email,Pass and RandomToken".
Instead, I get Email,Pass,[Object Object].
Here is my DoLogin function, which is called when the form is submitted.
function DoLogin()
{
var Email = $("#email").val();
var Pass = $("#pass").val();
var LoginResponse = $("#loginresponse");
var T = $("#t");
var EmailPlaceholder="Email address";var PassPlaceholder="Your password here";
$.get('path/to/login_ajax.php?email='+Email+'&pass='+Pass+'&t='+T, function(data)
{
$('#loginresponse').html(data);
});
/*if(Email != EmailPlaceholder && Pass != PassPlaceholder && Email != "" && Email != " " && Pass !="" && Pass != " ")
{
}*/
}
Here is my HTML form:
<form action="javascript:DoLogin();" method="post"><!--Also tried changing method to GET, still got the same problem -->
<input id="email" class="inputemail" type="text" name="email" size="40" value="Email address" onclick="$(this).val('');"/><span>Your email</span><br/>
<input id="pass" class="inputpassword" type="password" name="pass" size="40" value="Your password here" onclick="$(this).val('');"/><span>Your password</span><br/>
<input id="t" type="hidden" name="t" value="RandomToken"/>
<input class="indexsubmit" type="submit" value="Login"/>
</form>
<span id="loginresponse"></span>
And finally, login_ajax.php
<?php
echo $_GET['email'].$_GET['pass'].$_GET['t'];
?>
As mentioned above - I am only echoing the results, for know, as I'm knew to Jquery and AJAX, so I want to check if all fields are returning the values as expected, and one isn't...The token field.
You are chaining the object T of the input element and not the element's value to the query string of your GET request.
You should change this line
var T = $("#t"); // The object of the input element
to this
var T = $("#t").val(); // The value of the input element
Maybe what you want is:
var T = $("#t").val();

Form validated but still submitting without values?

im using javascript validation to check for values within each form field before the form sends to the database but when i click submit the form still sends even without any values.
To test it i clicked on each of the fields to clear them and then tried submittin the button
here is the form
<form method="post" action="send.php" id="theform" name="theform">
<input type="text" name="firstname" id="firstname" value="First Name" onFocus="this.value=''" class="yourinfo" ><br/>
<input type="text" name="lastname" id="lastname" value="Last Name" onFocus="this.value=''" class="yourinfo"><br/>
<input type="text" name="email" id="email" value="Email Address" onFocus="this.value=''" class="yourinfo"><br/>
<div id="datepicker"></div>
<input type="hidden" name="date" id="date">
<input type="image" src="images/sbmit-button.png" name="submit" height="49" width="190" id="submit" value="submit" style="margin-top:10px; margin-left:-2px;" >
</form>
heres the javascript
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstname", "lastname", "email"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
im also linking to a jquery file:
<script type="text/javascript" src="js/jquery-1.5.1.min.js"></script>
ive tested it on its own and it seems to work but something seems to be over riding it and skipping past the validation in this page
==================================================================================
i still not working... basicallly do u think it might have something to do with the jquery UI datepicker that im also using with the form?? ive not included that in the form validation as i only wanted to make sure the firstname, lastname and email was filled out
i have this included in my form page:
<script>
$(function() {
$("#datepicker").datepicker({
altField: '#date'
});
$('#submit').click(function() {
$('#output').html($('form').serialize());
});
});
</script>
would this be having an effect of it submitting even though there are no values in the fields?
something is definatley overriding the validation and submitting it
It's working for me! (but it's probably not working how you imagine it should)
Once you enter a valid email, the form is sent if you hit submit. Why? Because you have already filled in firstname and lastname for the user - with the strings First Name and Last Name!
So you shouldn't just check for empty or error string filled first and last names, but you should also trigger an error if the first name is First Name or the last name is Last Name.
// Check for empty value, the error string
// OR the default values of "First Name" and "Last Name"
if ((input.val() == "") ||
(input.val() == emptyerror) ||
(input.val() == "First Name") ||
(input.val() == "Last Name")) {
input.addClass("needsfilled");
Working example
(I assume you use server side validation as the final check, since people like me just love NoScript. )
(Also you declare 5 global variables at the top of your code and one more global in your for loop (i)... don't forget var.. just like you used for input)
What if I disabled JavaScript? You should (also) validate on the server side.
Also refactor your code! You can start with extracting methods.
You need to cancel the submit event. It looks like you're trying to do this with a return false or a return true. However, with jQuery you'll need to do it a slightly different way.
First, you'll need to have an argument name for the JavaScript event. I typically use e.
$("#theform").submit(function(e){
Then you'll need to update the following code as follows:
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
e.preventDefault();
} else {
errornotice.hide();
}
The e.preventDefault() stops the event from being processed. In this case, that means the form will not be submitted.

Categories