how do i change the content of a div using php - php

It doesn't exactly have to be a div, it can be anything, a article section a ...
I'm making a website for a university project, the website is similar to DropBox (file hosting website). NON COMMERCIAL!
I'm on the registration page at the moment and what I want to do is after the user presses the submit button I want to change the content of a div tag which is next to the field which is wrongly entered.
For example, if the user types in a password that is less than 3 characters long an "X" will appear in the div tag next to the password field and under the submit button a message will appear saying "Password must be more than 3 characters."
This is part of the code, not posting all of it because it's too long.
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="text" name="password" id="password" required="required"/>
<div id="right_or_wrong"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" />
<div id="error_msg"></div>
</form>
I have tried to search on how to do this but I can't find anything and I just can't figure it out.
I know I can put the PHP code in the div tag and assess it from there but I want to put the code at the bottom of the form to make it neater.

So in register.php when you validated the form and see that the password was too short, you can set a variable like $password_error = "Password must be more than 3 characters.".
Then you can just re-render the form and
<div id="right_or_wrong"><?php echo $password_error; ?></div>

You can validate before sending the form to the server, with simple onsubmit function:
<script>
function validate(){
// here, check the password and other answers
if( /* check password here */ ){
document.getElementById("right_or_wrong_password").innerHTML="X";
document.getElementById("error_msg").innerHTML="Password must be more than 3 characters.";
return false; // prevent from submitting form
}else if( /* check field1 here */ ){
document.getElementById("right_or_wrong_field1").innerHTML="X";
document.getElementById("error_msg").innerHTML="Error in the field......";
return false; // prevent from submitting form
}else{
return true; // the form can be submitted
}
}
</script>
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="password" name="password" id="password" required="required"/>
<div id="right_or_wrong_password"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" onsubmit="validate()" />
<div id="error_msg"></div>
</form>
In this way, you can verify each field of the form (answers structure only). Then a server validation is always necessary.

PHP can't do that alone. PHP is server-scripting - it can't run on user's machine and handle live events.
Instead, use Javascript's AJAX and call a php file which would return the text. And, then use Javascript to append that text to div or whatever you want.

Related

Simple submit form to go to a page

I have some numbered pages:
1.php
2.php
3.php
etc.
I want to create a textbox that the user enter any number: 2 for example, and hit enter or Go button, and they will go to the page 2.php depending on the number entered.
I know how to link to a specific page as in form action="....", but I am not sure how to echo the user input and translate it as link (whether using html or php).
Ex:
<form method="POST">
<input type="number" value="" />
<input type="submit" value="Go" />
</form>
You need to add an action attribute to your form and a name attribute to your number input. The file from your action attribute will "catch" the POST variables and do the logic needed to redirect your user. Change your form tag to:
<form method="POST" action="redirect.php">
<input type="number" value="" name="redirect" />
<input type="submit" value="Go" />
</form>
Then create the redirect.php file that gets the POST variables and does the redirection:
<?php
$redirectPage = (int) $_POST['redirect'];
$redirectUrl = "http://www.example.com/{$redirectPage}.php";
header("Location: $redirectUrl");
printf('moved.', $redirectUrl);
Beware that there's no input validation nor error handling included.
I think, the best available option in your case would be the one using client-side javascript to dynamically change the form's action attribute base on the number entered in the input box.
A quick and dirty solution to fulfil such a task might look like this
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function submitAction(formElement) {
var // get the input box element
el = document.getElementById('form-action-number'),
// get a number specified by user in the input box
num = parseInt(el.value),
// validate that it's really a number and is greater than zero
// (you don't want someone to request -666.php right? :)
// build a page url using the correct number
page = !isNaN(num) && num > 0 ? num.toFixed(0).toString() + '.php' : undefined;
if (page) { // the page url is valid
// set form's action attribute to an url specified by page variable
formElement.setAttribute('action', page);
// returning true will allow the form to be submitted
return true;
}
// you might think of a better way to notify user that the input number is invalid :)
console.error('INVALID NUMBER SPECIFIED!');
// returning false will prevent form submission
return false;
}
</script>
</head>
<body>
<!-- When user clicks Go, the return value of submitAction function will be used to decide if the form should be submitted or not -->
<form method="POST" onsubmit="return submitAction(this)">
<input id="form-action-number" type="number" value="" />
<input type="submit" value="Go" />
</form>
</body>
</html>
With PHP you can do something like this:
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
header('Location: ' . $_POST['my_number'] . '.php');
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>
This is like DaMeGeX's answer but uses javascript to go to the new page.
<?php
// Check if the POST value has been set
if(isset($_POST['my_number'])) {
// Redirect to the corresponding page
echo "<script> window.location.href = '".$_POST['number'].".php' </script>";
}
?>
<form method="POST">
<input name="my_number" type="number" value="" />
<input type="submit" value="Go" />
</form>

Confused about creating a "login" form

So what I want to do it kind of like a login form, but rather than it being individual users, it's more of a password locked page.
Here's sort of what I have for php
<?php
$user = $_POST['user'];
if($user == "placeholder")
{
include("randomfile.html");
}
else
{
if(isset($_POST))
{?>
<form id="login" method="POST">
User <input type="text" name="user" id="userID"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?}
}
?>
and it's basically doing what I want it to do, but if you were to go back (like use the go back button in the browser) it doesn't get rid of that submitted text (in this case, it would be "placeholder").
Any suggestions of any other way to do this, maybe easier or more basic because I just started with php, and is it possible so that if you enter "placeholder" and submit it, then go back, it doesn't have the User field already filled out with what you previously submitted?
<form id="login" method="POST" autocomplete="off">
That work for all the form, I think is the easiest. Ref: form:autocomplete

Copy / Paste Data in Ajax Live Search

I'm working with Ehsan Abbasi's Ajax Live Search (ALS)
https://github.com/iranianpep/ajax-live-search
http://ajaxlivesearch.com/
which invokes MySQL, PHP & jQuery to search and display search suggestion results as you type (similarly to popular search engines).
I'm struggling with the following:
When the user copies data and pastes it into the form, thereby rendering the live search pointless, what is the syntax to pass that data into the submitted form?
What does "onResultEnter" refer to? The user hits the enter button?
What does "onAjaxComplete" refer to? The user clicks a submit button?
Here's my relevant work to put these issues into context.
First, we initialize some variables and connect to our database via PHP:
# Live search initialization.
# --
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php' : die('Handler.php not found');
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php' : die('Config.php not found');
use AjaxLiveSearch\core\Config;
use AjaxLiveSearch\core\Handler;
if (session_id() == '') {
session_start();
}
$handler = new Handler();
$handler->getJavascriptAntiBot();
# Connect to database.
# --
require_once($_SERVER["DOCUMENT_ROOT"]."/connect.php");
global $dbc;
# Initialize required CSS and JavaScript files to be included.
# --
$additional_css = "<link href=\"/als/css/ajaxlivesearch.css\" rel=\"stylesheet\" type=\"text/css\" />";
$additional_js = "<script type=\"text/javascript\" src=\"/als/js/ajaxlivesearch.js\"></script>";
We next include two distinct forms to execute unrelated searches:
<!-- Model number search form -->
<form role="form" id="productsSearch" action="search-models.php" method="get" class="search-form">
<div class="input-group">
<input type="text" name="model_number" id="models" class="form-control modelSearch" placeholder="Enter your model number">
<input type="hidden" name="model_number" id="model_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" onclick="return model_validator();">Go</button>
</span>
</div>
</form>
<!-- Part number search form -->
<form onsubmit="return part_validator();" action="search-parts.php" role="form" method="get">
<div class="input-group">
<input type="text" name="part_number" id="parts" class="form-control partSearch" placeholder="Enter your part number">
<input type="hidden" name="part_number" id="part_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">Go</button>
</span>
</div>
</form>
Note here that the model search form involves an onclick event to validate model numbers. Similarly, the part number search form invokes an onsubmit event to validate part numbers. Both of these events were in our custom code before ALS entered the picture.
In addition, we have included a hidden field in each form to contain the value selected by the user in the ALS to be passed into the form when submitted to the action scripts.
These hidden field values are set in ALS functions associated with each of these input forms:
<!-- Model search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".modelSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#models').val(selectedOne);
// Hide the result.
jQuery("#models").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=model_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
<!-- Part search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".partSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#parts').val(selectedOne);
// Hide the result.
jQuery("#parts").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=part_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
I'd very much appreciate any help troubleshooting the syntax to get data that's copied by users from unknown sources & pasted into either of these forms and passed into the form action search scripts. Any light that could be shed on the onResultEnter and onAjaxComplete functions would likewise be welcomed.
If there's any additional information I can pass along to assist troubleshooting, do please let me know!
Best,
Allison

form submits before validation in php

I have a form which I want to submit, so when I click on submit it goes to the selectorpage.php and finds the selected function type e.g. login in this, which further calls the controller to execute the function. Issue I have is that there is a function called validateForm() in js, as soon as I click the submit button, it goes to the selectorPage.php. I wanted to stop the form submission, perform validation through js and then submit the form from there, I used onsubmit = return false; in form tag but it just blocks the form of doing anything further. And I also don't know how to redirect the form to the selectorPage if it somehow works in js. So anybody would like to give me an idea how to submit form from js and then redirect that page to selectorPage.php. Thanks
<form method="post" action="selector.php?type=login" id="login" id="loginForm">
<div class="row">
<div class="offset1 span1">
<div class="lbel">
<label class="control-label" for "loginName">
Username/Email
</label>
</div>
<div class="lbl_inpuCnt">
<input type="text" class="input-xlarge" id="loginName"
name="loginName" maxlength="50"/>
</div>
<div id="usernameError"> </div>
<div class="lbel">
<label class="control-label" for="loginPassword">
Password
</label>
</div>
<div class="controls">
<input type="password" class="input-xlarge"
id="loginPassword" name="loginPassword"
maxlength="50"/>
</div>
<div id="passwordError"> </div><br/>
</div>
</div>
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset"
name="reset" value="Reset"/>
<input class="btn" style="width: 80px;" type="submit"
name="submit" value="Login" onclick="validateForm();"/>
</div>
</form>
this is the javascript according to the code above
function validateForm(){
form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
document.getElementById('usernameError').innerHTML = "&nbsp";
form.submit();
}
} //suppose it for the email validation only for the time being
you could try
<form ... onsubmit="return validateForm();"
in the validateForm() function use
return true / false
depending if errors are found.
Here is the canonical way using inline event handling - see further down how it could be made unobtrusive. Also only have ONE id on the form tag, also NEVER call anything submit in a form it is a reserved word and will block submitting by script (which is what you tried to do)
<form id="loginform" ... onsubmit="return validate(this)">
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" value="Login" />
</div>
</form>
this is the javascript
function validateForm(form){ // passing form object
document.getElementById('usernameError').innerHTML = ""; // reset
if (form.loginName.value == "") {
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
Alternative
<form id="loginform" ..... No event handler here ...>
Script:
window.onload=function() {
document.getElementById("loginform").onsubmit=function() {
document.getElementById('usernameError').innerHTML = ""; // reset
if (this.loginName.value == "") { // notice the "this"
document.getElementById('usernameError').innerHTML = "Invalid username";
return false;
}
return true;// allow submission
}
}
I've had similar issues to this in the past myself.
When you click the 'Login' button of your form, you are triggering two separate events - Calling of the 'validateForm();' javascript function, and submission of the form itself. The problem here, is that submitting the form involves the browser sending an outbound request back to the form target, and to my knowledge, there is no way, using javascript, to kill a request event once it has been triggered.
Using 'onsubmit=return false;', likely, is doing exactly what it is supposed to do - Exiting the current javascript scope (and therefore preventing further javascript associated to that particular event from executing). However, unfortunately, the submission of the form itself, while possible to trigger and control via javascript, is not actually handled by javascript and is not a javascript function itself.
What I've found, in my experiences, to be the best solution, is to use the 'button' type input instead of the 'submit' type input - Both 'submit' and 'button' appear as buttons, but 'button' doesn't actually have any default inherent associated event action (therefore, doesn't actually do anything when you click on it) - What this means, is that, via event handlers (such as 'onclick', as you've done), you are able to entirely control what happens when a user clicks on a 'button'.
You haven't included your 'validateForm();' javascript function here, so I don't know what it contains, but, if it doesn't already do so, I'd include code to submit the form via that javascript function, submitting the form once validation has been successful (or returning some sort of human readable error if validation fails) - That combined with using 'button' instead of 'submit' should solve your problem.
Hope this helps. :)
Edit: Thought of this shortly after making my initial reply. Some browsers will process events handlers such as 'onclick' prior to submitting forms via the submit input type; However, I've found that certain older browsers do not do this currently (thus context of my above post). For newer browsers that honour the results of event handlers processed prior to form submission, it should be possible to prevent the second event (form submission) from occurring at all if validation fails; However, not all browsers honour these results, and I've found that some will continue to submit the form regardless of those results.
well thanks u all, so finally I found the solution by your ideas here is what I have done
rather putting return formvalidate(); function I put it in submit onclick event and it run like charm... thanks
<div style="margin-left: 55px;">
<input class="btn" style="width: 80px;" type="reset" name="reset" value="Reset" onclick="clearFields()"/>
<input class="btn" style="width: 80px;" type="submit" name="submit" value="Login" onclick="return validateForm();"/>
</div>
this is the javascript
function validateForm(){
var form = document.forms['loginForm'];
if(document.getElementById('loginName').value == "")
document.getElementById('usernameError').innerHTML = 'Invalid username or email';
else{
form.submit();
}
return false;
}

how to submit a from with validation in PHP?

I want to submit this form through PHP. with validation for required field and validation for phone number and email field also
<form action="" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_LastName">
Last Name</label>
<input id="txt_LastName" type="text" title="First Name. This is a required field" />
</div>
<div class="row">
<label for="txt_Phone">
Phone</label>
<input id="txt_Phone" type="text" title="First Name. This is a required field" />
</div>
<div class="row requiredRow">
<label for="txt_Email">
Email</label>
<input id="txt_Email" type="text" class="required" title="Email. This is a required field" />
</div>
<div class="row">
<input type="submit" value="" class="button" />
</div>
</form>
In your method attribute inside your form, you need to declare either post or get.
Since your action attribute is "" it will submit to the page itself rather than redirecting to another page, so you can have your code that checks for validation in the same PHP file. First validation that is often checked is if the variable has a value by using isset:
if(isset($_POST['txt_Phone'])) { ... }
This just checks that the Phone number field does not contain empty data. I strongly suggest you perform other validation checks on the POST array so you do not have any users posting malicious code.
You can use functions like htmlspecialchars to prevent user-supplied text depending on what you plan to do with the values
Here are some references to help you along the way in the order they should be viewed.
Form Validation using PHP - PHP and MySQL Tutorial
PHP Advance Form Validation Tutorial
PHP Tutorial Part 2: Form Validation
Your form tag needs a target in the action field and a method in the method field (either GET or POST). So make the action your PHP script.
<form name="input" action="form_submit.php" method="get">
As for field validation, you will either have to parse that inside of the PHP and return a response or use Javascript in the browser to check on the fly.
Here is the shcema of such a script:
if ($_SERVER['REQUEST_METHOD']=='POST') {
//data validation:
$err="";
if (valid_phone($_POST['phone'])) $err="Wrong phone no";
if (!$err) {
//record data:
$sql="...";
query($sql);
Header("Location: ".$_SERVER['REQUEST_URI']); //redirect and exit
exit;
}
}
?>
<html>
<head></head>
<body>
<? if ($err) ?> <font color=red><b><?=$err?></b></font>
<form method="POST" id="get-protected">
here goes your form
Okay, firstly, I like to set the form action to <?=$_SERVER['REQUEST_URI']?> to submit it back to the current page, but leaving it as you have it will work fine too.
Secondly, you need to give all your <input>s a name attribute. This is the variable name that PHP will see.
When your users get an error (something doesn't validate correctly) you don't want all the data they entered to disappear. That means you have to set the value attributes of each input to what they had previously entered. Thus, your form starts to look like this:
<form action="<?=$_SERVER['REQUEST_URI']?>" method="" id="get-protected">
<div class="row requiredRow">
<label for="txt_FirstName">
First Name</label>
<input id="txt_FirstName" type="text" class="required" title="First Name. This is a required field" name="first_name" value="<?=htmlspecialchars($_POST['first_name'])?>" />
</div>
...
<div class="row">
<input type="submit" name="submit" value="" class="button" />
</div>
</form>
If you didn't know <?= is a basically a shortcut for <?php echo but it will only work if your server has short tags enabled. Some people prefer to type it out the long way (in case they want to switch servers later, or for future-compatibility, or because they're nutbars), but I say screw them, I'm lazy.
This page that has the form on it, has to saved with a .php extension (well, technically it doesn't have to, but that's another story). Then you need to handle you form validation. You have to code that up yourself. It might look something like this (put it above your form somewhere)
<?php
if($_POST['submit']) {
$errors = array()
if(empty($_POST['first_name'])) $errors[] = 'please enter your first name';
if(empty($errors)) {
// save the data to database or do whatever you want with it
header('redirect:succcess.php');
} else {
foreach($errors as $e) {
echo $e;
}
}
}
?>
It's been a while since I've coded in PHP so forgive me if there are syntax errors. That's the jist of it anyway, I'm sure you can find validation libraries out there if you Google. Might take some of the grunt work out of trying to validate email addresses and such.
Using Javascript you can do the validation for this form.For each condition you can use return true and return false,based on the condition.Then you can submit the value.
Using action attribute in form tag the values will be submitted to that file.

Categories