Changing action based on input value using PHP - php

I'm working on a form that I'd like to change the form action based off of the value of an input on form submit. This needs to be accomplished using PHP.
Here's what I've tried so far:
<?php
$action = "";
$input = (isset($_POST["hp"]));
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
<!-- form stuff here -->
<input id="hp" name="hp" type="text" class="hp"/>
<input type="submit" name="submit" id="submit" value="Submit Query" class="button" />
</form>
This doesn't work because the hp field for (isset($_POST["hp"])) doesn't have a value from the get-go, so it always goes to action1.
I've also tried:
<?php
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
$action = "";
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
<form name="contactForm" id="contactForm" method="post" action="<?php echo $action; ?>">
That didn't work because Perch (the CMS this is being built on) throws you an error that $action isn't defined yet.
And when I tried:
<?php
$action = "";
if(isset($_POST['submit'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>
It didn't do anything at all on submit because it set the action as "".
Any suggestions?

To write in short way
$action = isset($_POST['hp'])?'action2':'action1';
That's all.

Differents possibilities:
Same action and redirect
The most easy way probably is send form to the same PHP file, and in this file, get the content of this input via POST and redirect to the correct file.
Prevent default submit and add submit event via JavaScript
The second option, may be add an event to form on submit via JavaScript, prevent default action to prevent the submit, then check value of input, set action and submit form:
<form name="contactForm" id="contactForm" method="post" action="">
...
</form>
<script>
document.querySelector('#contactForm').addEventListener('submit', function(e) {
//Prevent default submit
e.preventDefault();
//Check input value
if (...) {
this.action = "page1.php";
} else if (...) {
this.action = "page1.php";
}
//perform submit form.
this.submit();
});
</script>
Use data binding library
This is probably the best form to do it, but the most complicated to understad, this form is based of use a data binding library like Vue.js, KnockoutJS or RactiveJS to set in model object the action string depending of input value.
Then, in HTML form tag, set in action the value of model data using the binding syntax of the chosen library:
//Vue.js syntax
<form name="contactForm" id="contactForm" method="post" :action="action">
//Ractive.js syntax
<form name="contactForm" id="contactForm" method="post" action="{{action}}">
What do I recommend?
If you're novel with PHP and don't know JavaScript, the first option is probably the best for you, if you If you know JavaScript and you know how to work with events, but never used a binding library, probably the second option is more recommended for you.
If you worked with some data binding library (or framework that implements data binding like Angular), the third options is probably the best for you.

If the 2nd and 3rd versions don't work, you must be missing an input like:
<input type="submit" name="submit">
You can either add that button to the form, or you can change your code to use if isset($_POST['hp'])
<?php
$action = "";
if(isset($_POST['hp'])){
$input = ($_POST['hp']);
if($input == "") {
$action = "action1";
} else {
$action = "action2";
}
}
?>

None of the answers above worked for me, so here is what I ended up going with.
Use Case:
I have a "Search" form with two fields. When a user clicks "Search",
these values should be added to the URL, so that previous searches
may be bookmarked. The search should then be performed.
When the page is first loaded or no search criteria are used, all
possible results should be shown.
Code description:
At the top of the file, check if the user submitted the form.
If so:
get the values from the fields you want and save them to local variables.
navigate to the same PHP file, this time passing the variables you are interested in
If the user did not submit the form:
check for URL parameters
If there are URL parameters present, save them to local variables,
and use these local variables to run the search
Code Snippet:
if(isset($_POST['submit'])){
if(!empty($_POST['projectNameSearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_POST['projectNameSearch']);
}
if(!empty($_POST['projectDescriptionSearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_POST['projectDescriptionSearch']);
}
if($projectNameSearch != '' || $projectDescriptionSearch != ''){
header("Location: projects.php?projectnamesearch=$projectNameSearch&projectdescriptionsearch=$projectDescriptionSearch");
}
} else {
if(isset($_GET['projectnamesearch'])){
$projectNameSearch = mysqli_real_escape_string($conn, $_GET['projectnamesearch']);
}
if(isset($_GET['projectdescriptionsearch'])){
$projectDescriptionSearch = mysqli_real_escape_string($conn, $_GET['projectdescriptionsearch']);
}
}

Related

Sending Form Data Using POST To The Current Page And Another PHP Page At The Same Time

I have seen another person ask this question in stack overflow but I did not get any clear answer/idea from 'his post'. I want to know whether there is a way of sending form data via POST to the current PHP page addstudio.php to verify the entered data & if the entered data is valid it gets redirected to the next PHP page getstudio.php.
To send the form data to the current page I used the following line:-
<form action = "<?php $_PHP_SELF ?>" method = "post">
This is just done to validate the form information and if the form is left blank then a message is displayed in the same PHP page, the code for this is shown below.
<?php
$valid = true;
$studioIdError = $studioNameError = $studioAddressError = $studioPCodeError = $studioTelNoError = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST["studioId"])){
$studioIdError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioName"])){
$studioNameError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioAddress"])){
$studioAddressError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioPCode"])){
$studioPCodeError = " *This Field Cannot Be Empty";
$valid = false;
}
if(empty($_POST["studioTelNo"])){
$studioTelNoError = " *This Field Cannot Be Empty";
$valid = false;
}
}
?>
To the above code I want to know if there is a way I can get the getstudio.php page to run when $valid = true.
I cannot use the code include 'getstudio.php'; because I want getstudio.php to run on a seperate page.
I cannot use the code header("Location:getstudio.php");exit(); to run either because the values in the global array $_POST[] is not sent to the PHP page like it is when the page is called directly from the form (Eg:- <form action = 'getstudio.php' method = 'post'>).
Is there a way of running the getstudio.php page while sending the values stored in the $_POST[] array to the getstudio.php page when $valid = true?
You have a few options.
Use AJAX to validate the form; then, if valid, do the submit.
Store the data somewhere client-side or server-side between pages (cookies or sessions).
Send a specially-crafted html that makes the browser to mimic a user sending a form. [ugly, the user sees a redraw]
Keep both validation and processing in the same page (why separate?).
In any case don't forget to re-validate before acting upon user data, unless absolutely sure the data can't be affected by a user (in the list above, only when storing data in a session, and still not recommended). Then, if validating again anyways, why bother with a separate page?
So as i understand you want to send Data first Addstudio.php than Getstudio.php but you want second one with redirection.
Make your HTML like this :
<form action="getstudio.php" method="POST">
<!-- etc -->
</form>
Make your Javascript like this (include jQuery):
$(".your-form-class").on('submit',function(evt){
evt.preventDefault();
var instance = $(this);
var formData = new FormData($(".your-form-class")[0]);
$.ajax({
type:"POST",
data:formData,
url:"addstudio.php",
success:function(response){
instance.submit();
}
});
});
Here is your current page
<?php
$_POST["studioName"] = 'testdata';
$valid = true;
if(empty($_POST["studioName"])){
$studioNameError = " *This Field Cannot Be Empty";
$valid = false;
}
// send data to getstudio.php if valid
if($valid){ ?>
<form method="post" action="getstudio.php" id="senddata">
<input type="hidden" name="postdata" value="<?php print_r($_POST); ?>">
</form>
<script>
document.getElementById("senddata").submit();
</script>
<?php } ?>
Here is your getstudio.php file to receive validated post data
<?php
echo '<pre>';
print_r($_POST['postdata']);
die;

javascript and php validation?

I have some javascript and php code written to validate a field. Both codes are to validate whether the field is not empty, is within a limit of 35 characters and contains only alphabetic characters and a hyphen(-). What i want to do is for both the javascript and php to validate simultaneously and show they're messages for entering incorrect data but it only seems that the javascript is validating properly due to the fact that an alert pops up but no message is shown from the php side. Here is my code :
<script type="text/javascript">
function validateFamily()
{
var family=document.getElementById('family');
var stringf = document.getElementById('family').value;
var ck_password = /^[A-Za-z-]/;
if (family.value=="")
{
alert("Family name must be filled out");
return false;
}
else if (document.getElementById('family').value.length > 35)
{
alert("Family name cannot be more than 35 characters");
return false;
}
else if(!ck_password.test(stringf))
{
alert("Family name can only contain alphabetic characters and hypehns(-)");
return false;
}
return true;
}
</script>
<?php
if (isset($_POST['submit'])) {
$flagf = false;
$badcharf = "";
$stringf = $_POST["family"];
$stringf = trim($stringf);
$lengthf = strlen($stringf);
$strmsgf = "";
if ($lengthf == 0) {
$strmsgf = '<span class="error"> Please enter family name</span>';
$flagf = true;}
else if ($lengthf > 35) {
$strmsgf = '<span class="error"> Can not enter more than 35 characters</span>';
$flagf = true;}
else {
for ($if=0; $if<$lengthf;$if++){
$cf = strtolower(substr($stringf, $if, 1));
if (strpos("abcdefghijklmnopqrstuvwxyz-", $cf) === false){
$badcharf .=$cf;
$flagf = true;
}
}
if ($flagf) {
$strmsgf = '<span class="error"> The field contained the following invalid characters: '.$badcharf.'</span>';}
}
if (!$flagf) {
$strmsgf = '<span class="error"> Correct!</span>';}
}
?>
<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateFamily() && validateGiven() && validateMaleFemale() && validDate() && validateAddress() && validatePost() && validateParent() && validateWork() && validateHome() && validateMob() && validateCheckBoxes() && validateTextBoxes();">
<b>Student's Family Name</b>
<br>
<input type="text" id="family" name="family" /><?php echo $strmsgf; ?>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
Could anyone help me with this?
Your JavaScript and PHP cannot execute simultaneously because the former happens in the user's browser before the form is POSTed and the latter happens after this once the form has reached the server.
You can verify this by inspecting the source code of your webpage in the browser: there's no PHP!
If your JavaScript makes the catch, nothing is sent to the server because you return false. In practice it makes sense to have the server-side checks in place in case:
Someone is tricky and modifies the form after it's validated but before it's sent.
JavaScript is disabled or breaks for some reason.
The way this form works is that you have a JS function in the form's onsubmit property which can prevent the form's submission if a value is wrong. If your JS function returns false because of an error, the form will never be submitted.
In order to get the functionality you want, you need to perform the checks on the server side only, but you'll need to submit the form each time for that to occur...
An alternative way would be to check the entered values when the user finishes adding a value to each of your text fields, i.e. attach a JS function to the fields' blur() property, and make an AJAX call to your server that will validate the field contents before the form is actually submitted.
You can use jQuery's validate plugin for more complex validations, if these can be done on the client side, as well:
http://jqueryvalidation.org/
As paislee stated there is no way you can simultaneously run php and javascript. There are however dynamic requests you can send to run some php code and it's called AJAX. This will also not ensure an absolutely accurate simultaneous execution but will be closer to what you aim for.

How can I validate inputs directly from the database without page reloading?

I'm just a PHP starter and now I want to learn JQUERY, on my learning process I practice on validating inputs usually I validate my inputs using a pure PHP code only and every time I validate the inputs the page reloads and now I want to improve in doing things I found some articles like http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (can't post other links) but I am more confused because they have different approach and I want to use the approach from the JQUERY tutorial but I haven't found any good tutorials and there is no tutorials on JQUERY's site that is using a database, usually I code like this:
<form method="post">
<label for="Username">Username:</label>
<input id="Username" type="text" name="username">
<?php
session_start();
if(isset($_SESSION['msg'])){
$msg=$_SESSION['msg'];
echo '<label for="Username">'.$msg.'</label>';
?>
<input type="submit" name="reg">
</form>
<?php
if(isset($_POST['reg'])){
$result=//check username from database here
if($result){
$_SESSION['msg']='username not available.';
}
else {
$_SESSION['msg']='username available.';
}
}
?>
Now I want to learn how can I validate inputs directly from the database without reloading the page? I don't know where should I start, what to add in my code. Any help, advice or suggestions will be really a big help for me :)
first, in your form add a onSubmit function
<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()">
you can do this in ajax like that
function check_form()
{
var user = $('#Username').val(); // Username is the id of your input
var password = $('#password').val(); // password is the id of your input
$.ajax(
{
type:"POST", // or get as you want
url:"myfile.php", // it is the php file which can do the job
data: "user="+user+"&password="+password, // the param to send to your file,
success:function(msg)
{
;// msg is the result of your 'myfile.php', everything you write is in the msg var
}
});
}
in your php file you can get your data like this :
$user = $_POST['user'];
$password = $_POST['password'];
// if your type is get then use $_GET instead of $_POST
tell me if you have any problem with my code.
Write your validation script as though you're expecting a page refresh. Instead of outputting error messages, put them in a JSON array and print the JSON data. Then call the script from the AJAX function. It's really that simple.
<?php
// validate.php
$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : "";
$errors = array();
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) {
$errors[] = "SampleInput_number must be a number!";
}
// sample input must also match a value from the database
if (!matchesDBValue($sampleInput_number)) {
$errors[] = "SampleInput_number must match a value from the database!";
}
function matchesDBValue($value) {
$retval = false;
// compare to db values here...
return $retval;
}
echo json_encode($errors);
Your form would look something like this:
<form action="" method="post" id="theForm">
<input type="text" name="sampleInput_number" id="sampleInput_number" />
<input type="button" id="formSubmit" value="Submit" />
</form>
And your javascript would look like this:
<script language="javascript" type="text/javascript">
$(#formSubmit).on("click", function() {
$.post("validate.php",
{
sampleInput_number: $("#sampleInput_number").val()
}, function(data) {
// check returned json data
// perform action based on results
if (no_errors) {
$("#theForm").submit();
}
}, "json"
);
});
</script>

Post form data to a new page and show that page with the posted data

I have:
form.php
preview.php
form.php has a form in it with many dynamically created form objects. I use jquery.validation plugin to validate the form before submitting.
submit handler:
submitHandler: function() {
var formData = $("#myForm").serialize();
$.post("preview.php", {data: formData },function() {
window.location.href = 'preview.php';
});
Question:
- How to change the current page to preview.php and show the data? my submitHandler doesnt work? Any tips?
preview.php:
$results = $_POST['data'];
$perfs = explode("&", $results);
foreach($perfs as $perf) {
$perf_key_values = explode("=", $perf);
$key = urldecode($perf_key_values[0]);
$values = urldecode($perf_key_values[1]);
}
echo $key, $values;
enter code here
You can simply add the onsubmit even of the form and use your validation check along a function. At the end if anything is going good, return it with a true state otherwise, false to stop it from getting submitted.
For example:
<form name="Iran" method="POST" action="preview.php" onsubmit="return alex90()">
</form>
And use this script:
<script language="javascript">
function alex90()
{
// use whatever validation you want
if(form == valid){
return true;
}else{
alert("Something's wrong folk!");
return false;
}
}
</script>
Just submit the form without ajax and make sure action of form is "preview.php"
EDIT: to do this in validation plugin simply remove the submitHandler option you show above. This is used if you want to over ride normal browser form submit, which you now don't want to do.
WIth your ajax submit, then trying to go to the page.... it is 2 page requests and without the form redirecting automatically there is no data available on page load using the javascript redirect
I managed to solve my problem. without sessions.
add to form:
<form action="preview.php" onsubmit="return submitForPreview()">
<input type="hidden" name="serial" id="serial" value="test">
js:
function submitForPreview()
{
if($("#form").valid()){
$('#serial').val($("#newAdForm").serialize());
return true;
}else{
return false;
}
}
preview.php
echo $_POST['serial'];
//Which shows the serialized string. YEEEEYYY :D
Thanks for help folk :D

How to prevent form from submitted based on PHP value?

I'm using Ajax to test if the Username on a Register form is too short.
Right now it just does this:
if (str.length<6)
{
document.getElementById("txtHint").innerHTML="Too short";
return;
}
How do I add an action above that doesn't let the user submit?
<form action="/insert/insert-user.php" method="post">
<input type="text" name="user" onkeyup="showHint(this.value)"/>
In the CheckUserName function, add your ajax code and return true or false. If It's false, it won't submit.
<form action="/insert/insert-user.php" onsubmit="CheckUserName()" method="post">
You may try adding a form name and onsubmit event to your form.
<form name="formName"action="/insert/insert-user.php" method="post" onsubmit="validate()">
function validate() {
if (document.formName.user.value.length < 7) {
// Display your message in your division
return false;
}
}
You must also repeat the check in php since the user may have Javascript disabled and for security measure:
if ($_POST['your_submit_button']) {
if (strlen($_POST['user']) < 7) {
$submit = false;
die ("<div style='color: red;'>Too short</div>");
}
}
Give your error div a class lets say 'error' and on submitting the form call another function in which you check the if error class have text by JQuery. If the class have the text just return false and your form will not be submitted

Categories