If I submit blank fields it still adds it into database. I made a loop to check if everything is on place but it keeps redirecting it to error page. I've been struggling with this almost 2 hours but cant find a solution.
Links are here since i can post more than 2 :
Try to set
Don't allow nulls
in the column property of table. It can be done during the table design or Edit table Design in the database.
Hope this helps.
You using empty(). http://us3.php.net/empty
This only returns false if NULL, FALSE, or not exists, NOT if empty string.
You should be doing this:
foreach($required as $post){
if ($_POST[$post] == "") {
die(header("refresh:0.5;url=error.php"));
}
}
However, I don't know why you don't just put this over the entire code block so it only gets executed on submit of the form. Then you don't have to keep rechecking it.
if (isset($_POST)) { //or a specific $_POST variable if multiple submit paths
//code here
}
Additionally, you should edit your question to include the relevant code in the question or in the future, searchers may discover that your pastebin link no longer works.
I think in any way you should make some client-side validation on empty field like jQuery functions :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("form").submit(function(){
if($("#first_name").val() == ''){
alert("First name cann't be empty");
return false;
}else if($("#last_name").val() == ''){
alert("Last name cann't be empty");
return false;
}else if($("#email").val() == ''){
alert("Email cann't be empty");
return false;
}else if($("#password").val() == ''){
alert("Password name cann't be empty");
return false;
}
});
});
</script>
You're trying to get indexes on $_POST array that doesn't exist, so correct your $required array and put fields names not the variables names, just like this in process.php:
$required = array('first_name','last_name','password','email');
foreach($required as $post){
if($post = empty($_POST[$post]) || $_POST[$post] == ""){
die(header("refresh:0.5;url=error.php"));
} elseif($required != empty($_POST)) {
echo "";
}
}
I think yor a looking for something like,
if(isset($_POST['field1']) && !$_POST['field1'] =="")
{
//your codes goes here
}
Maybe You have done something like
<input type=text name=name1 value ="" />
If so, Please do it like,
<input type=text name=name1 />
This will not send name1 to your page;
Related
<?php
if(isset($_POST["username"]) && $_POST["username"] != "")
{
$username= $_POST['username'];
if (strlen($username) < 4) {
echo '4 - 15 characters please';
}
if (is_numeric($username[0])) {
echo 'First character must be a letter';
}
}
?>
php code not working: please help me validation using java script or ajax
e<script type="text/javascript" language="javascript">
function callme()
{
var showme = document.getElementById("show");
var user = document.getElementById("uname").value;
//for check new browser show ajax from
if(user!=="")
{
showme.innerHTML=' loading.....';
var hr = new XMLHttpRequest()
{
hr.open("post","index.php",true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.readystatechange=function()
{
if(hr.readystate== 4 && hr.status==200) {
showme.innerHTML= hr.responseText;
}
}
var v="username="+ user;
hr.send(v);
}
}
}
</script>
<body>
<span>username:</span>
<input type="text" name="uname" id="uname" onBlur="callme();"/>
<div id="show"></div>
</body>
all code working fine only php code not working please help me
when we enter some text in textbox only loading.....
any type of validation are not showing ...
I think your problem is here hr.readystatechange. What you need is hr.onreadystatechange
Maybe this is not the solution but you can echo or print_r or in a file what you receive from the browser in php and see if $_POST['username'] is coming with this name and no with uname.
print_r($_POST);
Your code is very old, now you can use jquery to make things easy with javascript and for php there are lots of frameworks out there that can do your php easy. Tags like onclick into html are deprecated or very near to be.
Is better if you expect an string
$_POST["username"] !== ""
Try to store the message in one variable and at the end of the php function, return it, is better to have only one exit than multiple along the function.
Next time try to put the question and the code in order, for readability and understanding.
Thanks, and sorry for my english... XD
I a have page in which users will be adding folders to their account. When they create a name for the album, it checks to see if an album of that name already exists; if it does already exists, it tells them it is taken, but if it doesn't, it creates the album which appears on the page.
What I need is for the textbox to reset ONLY if the album is created successfully. At the moment I have something similar to:
if(isset($_POST['create_album']))
{
if(isset($_POST['new_album']) && $_POST['new_album'] != "")
{
$new_album_name = $_POST['new_album'];
if(/** Here I check if the $new_album_name exists **/) {
$new_album_name_error = "album exists numbnuts";
}
else
{
/** LOTS OF CODE **/
/** Here I create a new album with the input **/
/** END OF LOTS OF CODE **/
echo "<script>
document.getElementById('new_album').value='';
</script>";
}
}
}
The id of the submit button being 'create_album' and the id of the textbox being 'new_album'.
However I cannot seem to get anything to work, where it will get the ID of the textbox and clear it. Everything else works perfectly.
Note: In the code, I have taken out the filepaths and code for checking if the album exists and for creating one, for simplicity and because it's not needed.
Another option is doing it without AJAX.
NOTE: I'm supposing you are making the request to the same PHP file.
<?php
$new_album_name_error = "";
$albumName = "";
if(isset($_POST['create_album'])) {
if(isset($_POST['new_album']) && $_POST['new_album'] != "") {
$new_album_name = $_POST['new_album'];
if(/** Here I check if the $new_album_name exists **/) {
$new_album_name_error = "album exists numbnuts";
$albumName = $new_album_name;
}
else {
/** LOTS OF CODE **/
/** Here I create a new album with the input **/
/** END OF LOTS OF CODE **/
}
}
}
?>
<span class="error_code"><?php echo $new_album_name_error; ?></span>
<input type="text" id="new_album"><?php echo $albumName; ?></input>
Whenever you load the page, the input will be empty.
If some error appears, it will show the error in the span and it will display the album name.
If everything is OK, it will display the album name as empty.
PHP is a 1 time shot. It queries server and spits out a response. anything interactive needs some help. Id recommend jquery/javascript with ajax. Have the submit button call an ajax page that does your query, it will return a result. from that result you can determine the value of the textbox.
<script>
($'#subAlbum').click (function ()
{
var newAlbum = $('#newAlbum');
var data = "newAlbum="+newAlbum;
$.ajax(
{
type: "POST",
url: "checkAlbum.php",
data: data,
success: function(result)
{
if (result == "true") //error condition
{
$('#newAlbum').val('');
}
else
{
$('#newAlbum').val(newAlbum);
}
}
})
});
</script>
<form id='albumForm' method='POST' action='#'>
<input type='text' name='newAlbum' id='newAlbum' value='<?php echo $albumName;?>'>
<input type='button' id='subAlbum' value='submit'>
on checkAlbum.php run your query and echo either "true" or "false" as a response.
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.
I have tried the following code to display some divs.
<?
$uri=$_SERVER['REQUEST_URI'];
$uri=explode('/',$uri);
$uri=$uri[4];
echo $uri;
?>
<script type="text/javascript">
$(document).ready(function() {
var ty=<?=json_encode($uri);?>;
if(ty="gen")
{
alert("gen");
}
else if(ty="cc")
{
alert("cc");
}
else
{
alert("not gen");
}
});
</script>
$uri value will be something like /site/view-wall/type/gen/id/6. The type variable can be changed to vo,cc,fr etc. If I changed the web address to www.example.com/site/view-wall/type/cc/id/6 I am getting alert "gen", not "cc". Always I am getting alert "gen". The if conditions are not working. I couldn't figure out the simple if condition :(
Any help should be appreciated!
You are setting the variable value, you have to use double equal == to compare
In JavaScript, == or === are used to compare; you're using =, which sets the value of a variable. When you do this:
if(ty="gen")
{
alert("gen");
}
That's equivalent to doing this:
ty = "gen";
if(ty) {
alert("gen");
}
All non-empty strings are truthy, so your condition always succeeds.
To fix it, change the = in all of your conditions to == or ===.
I’m not sure whether the problem I’m having is with JavaScript or with PHP.
My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.
My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.
What am I doing wrong?
Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.
Also I have a question about choosing answers. May I choose more than one reply as an answer?
<?php
// Set variables
$selected_radio = 'test';
session_start(); // start up your PHP session!
// The below code ensures that $dest should always have a value.
if(isset($_SESSION['dest'])){
$dest = $_SESSION['dest'];
}
// Get the user's ultimate destination
if(isset($_GET['dest'])){
$_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest'];
$dest = $_SESSION['dest']; // new code
}
else {
echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value)
}
// Show the terms and conditions page
//check for cookie
if(isset($_COOKIE['lastVisit'])){
/*
Add redirect >>>> header("Location: http://www.mywebsite.com/".$dest); <<This comment code will redirect page
*/
echo "aloha amigo the cookie is seto!";
}
else {
echo "No cookies for you";
}
//Checks to see if the form was sent
if (isset($_POST['submitit'])) {
//Checks that a radio button has been selected
if (isset($_POST['myradiobutton'])) {
$selected_radio = $_POST['myradiobutton'];
//If No has been selected the user is redirected to the front page. Add code later
if ($selected_radio == 'NO') {
echo "NO status checked";
}
//If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later
else if ($selected_radio == 'YES') {
echo "YES status checked";
// header("Location: http://www.mywebsite.com/".$dest);
}
}
}
?>
<HTML>
<HEAD>
<TITLE>User Agreement</TITLE>
<script language="javascript">
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
thisform.submit(); // this line submits the form after validation
}
</script>
</HEAD>
<BODY>
<H1> User Agreement </H1>
<P>Before downloading you must agree to be bound by the following terms and conditions;</P>
<form name="myform" METHOD ="POST" ACTION ="user_agreement4.php">
<input type="radio" value="NO" name="myradiobutton" />NO<br />
<input type="radio" value="YES" name="myradiobutton" />YES<br />
<input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" />
</form>
</BODY>
</HTML>
See this line:
if (isset($_POST['submitit'])) {
If the user presses the submitit button, and javascript is disabled, everything works as expected - the button inserts its name/value pair into the posted data right before the form gets posted, so $_POST['submitit'] is set.
If, however, javascript is enabled, the button doesn't trigger a postback itself, instead it calls a javascript function which posts the form. Unfortunately though, when you call form.submit(), it won't go looking for buttons and add their name/value pairs to the posted data (for various reasons). So you need to find a different way of telling whether you are processing a post-back; the easiest way is to just put a hidden field into your form and check for that, e.g.:
(in the HTML part, somewhere inside the <form></form>):
<input type="hidden" name="is_postback" value="1" />
...and then change your PHP check to:
if ($_POST['is_postback'] == '1')
Change your javascript to:
function valbutton(thisform) {
// validate myradiobuttons
myOption = -1;
for (i=thisform.myradiobutton.length-1; i > -1; i--) {
if (thisform.myradiobutton[i].checked) {
myOption = i;
}
}
if (myOption == -1) {
alert("You must choose either YES or NO");
return false;
}
if (myOption == 0) {
alert("You must agree to the agreement to download");
return false;
}
return true; // this line enables the form to submit as normal and is not actually required
}
And remove the "return false;" from the on click event of the button. Having the validation function return false on validation fail is sufficient to stop the from from validating.
This should enable your php to work as is.