Alert boxes when validating form in PHP - javascript

I am writing PHP to validate form data. I am trouble shooting my alert boxes.
This is the bones of my code:
function emailcheck ($email1)
{
$regexp="/^[a-zA-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
if (preg_match($regexp,$email1))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['submit'])) {
if ($emailcheck == TRUE){
//send email
//various fields etc
echo '<script type="text/javascript"> alert("Your form has been submitted.") </script>';
}
else
{
echo '<script type="text/javascript"> alert("Enter a valid email address.") </script>';
return FALSE;
}
}
When I test the form for the emailcheck function to be FALSE I get this;
followed by this:
How can I fix this? Thanks
edit
I am not concerned with the entire php/javascript validation; I am looking at a specific detail- what am I doing wrong with my functions here? Why is it printing off the alert.. there must be something basic I've overlooked.
There is, obviously, a problem with how I am using the isset function, and the way I am calling in the emailcheck function.
I have client side validation, but am focused on the php validation in this question - so please, no need to discuss javascript validation.

You've got some kind of syntax/ quoting error. Backup your file, then binary search A/B by removing or drastically simplifying sections of code, until the symptom is fixed.
You have then found your problem, & can fix it in the restored file.
Postscript: error may be in the PHP quoting or <? syntax -- we're seeing Javascript either being emitted, or parsed by the browser, as HTML.
Try viewing the source & checking what the browser sees?
PS2: We're also seeing PHP code (the } else {) being shown in the browser. Your code sample doesn't show the <? PHP start -- you've got some kind of error in the <? ?> PHP syntax.
By the way, I'm the only person who is actually picking up these obvious symptoms & helping you.

$emailcheck is a variable and not a function. it should be
$emailcheck = emailcheck($email);
if($emailcheck === TRUE): /* more code */ endif;
IMO I would use the function that goes with the PHP installation.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<script>alert('GOOD email');</script>";
} else {
echo "<script>alert('BAD email');</script>";
}
link to php fiddle

I think you need to change your test in your if statement.
function emailcheck ($email1) {
$regexp="/^[a-zA-A-Z0-9_\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$/";
if (preg_match($regexp,$email1)) {
return TRUE;
} else {
return FALSE;
}
}
if (isset($_POST['submit'])) {
$emailAddy = "someone#somewhere.com"; //get email address from form here
if (emailCheck($emailAddy)){
//send email
//various fields etc
echo '<script type="text/javascript"> alert("Your form has been submitted.");</script>';
} else {
echo '<script type="text/javascript"> alert("Enter a valid email address."); </script>';
}
}
Your current statement isn't checking the return value of your function, it is testing the value of the variable $emailCheck, which isn't actually set to anything.
Edit
I also just noticed in your regexp string you have a capital 'S' instead of a $, assuming that you wanted to signify the end of the string. Also, both of your alert() calls were missing the semicolon at the end. I've tried out this code on my end and it seems to work. I've modified my answer to reflect the changes. Hope that helps!

Related

How do I insert # character in echo statement for JavaScript?

When I include the # glyph in my statement, to return to an anchor on the page, the PHP code fails.
I've tried everything I can think of to resolve this issue, escaping PHP characters, writing JavaScript functions and the list goes on.
if (isset($_POST['name'])) {
$_POST = array();
echo "<script>window.location.href='Contact_Us.php#myForm'</script>";
} else {
unset($_POST);
}
There are no error messages.
The page appears to refresh and the code to unset the POST variables fails.
If you really want to do things that way simply drop out of PHP instead of trying to echo things.
if (isset($_POST['name'])) {
$_POST = array();
?>
<script>window.location.href='Contact_Us.php#myForm'</script>
<?php
} else {
unset($_POST);
}

Page redirection using if statement with javascript and php

I want to redirect a php page using php if statement. I did the redirect code with javascript but its not working.
Can someone please help me modify my code if i missed something out or help me out with a better solution.
Below is the code;
$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){'<script>window.location.href = "http://www.url.com/login.php";
</script>
';}
else {echo "NOT WORKING";}
I tried this too
$vbi = $row_rsRek['duck'];
if ($vbi == "blocked"){header("Location: www.url.com/login.php");}
else {echo "NOT WORKING";}
PHP has a build in feature for your needs
header("Location: path/to/file");
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
http://php.net/manual/en/function.header.php
You can use header function :
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
<?php
$vbi = 'blocked';
if ($vbi == "blocked")
{
header("Location: http://www.yourwebsite.com/user.php");
}
else
{
echo "NOT WORKING";
}
?>
see this link for more information and discuss :
How to make a redirect in PHP?

JS and PHP variable don't show good

If this was in asks, sorry for that, but I want to speed help, thanks!
Do you have suggestions for result this ? Because when I do this it show last $name, it doesn't work.
JavaScript:
var name = 'Test';
if(name === 'Test'){
<?php $name = "Test"; ?>
} else {
<?php $name = "Error"; ?>
}
I have click function and when I click I check ID of object, but after this I want check this id is good e.g. (if(id === 'content')) and show good alert, when i checked it.
This is your server-side code, which will execute exactly once when the page is requested:
$name = "Test";
$name = "Error";
After this code executes, $name will be "Error". Every time.
This is your client-side code, which will execute exactly once when the page renders in the browser:
var name = 'Test';
if(name === 'Test'){
} else {
}
After this code executes, name will be 'Test'. Every time.
You're trying to mix server-side code and client-side code. They don't mix like that. They execute on two completely different platforms at two completely different times in two completely different contexts. Whatever you're trying to do (which we don't know), this isn't how you do it.
The way you wrote it isn't going to work. First of all PHP is executed before the JavaScript is parsed. In your code you set a variable inside PHP, so nothing actually happens. If you want something written on the page use echo or print.
What I think you want is to send a variable to PHP. For this you need a form or an Ajax-call.
If you want it the other way around, set a JavaScript variable based upon a PHP value you need to use JSON notification.
The only way I could even think of doing this would be:
<script>
var name = 'Test';
if(name === 'Test'){
</script>
<?php $name = "Test"; ?>
<script>
} else {
</script>
<?php $name = "Error"; ?>
<script>
}
</script>

PHP: Not changing the value of a variable

I have a problem in confirmation message when the USER click CANCEL the value of $IsCanceled = "yes"
then when I click OK the value of `$IsCanceled = "no"..
The problem is, when I click the OK the value of $IsCanceled is still yes...
<?php
else { ?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
<?php $IsCanceled = "no";?>
} else {
<?php
$IsCanceled = "yes";
?>
}
</script>
<?php
}
//and so on...
I already traced everthing but its still "yes" the value..
Thanks
PHP and Javascript.
Two completely different languages used in various different tasks.
What you have written above tries to mix two languages, which if you were writing in any other environment you wouldn't even consider doing. The above script you have written, will run its PHP when on the server, and produce an output that is sent to the browser.
In your case, that will look something like:
<script>
var myVar = "i station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
} else {
}
</script>
That is the exact output of your code at the moment. If you want to navigate the user to "save to other networks", you would have to create a hidden HTML form, with an <input type="hidden" .. that can hold the answer you need. Then, with Javascript, you can show your confirmation dialog and populate the HTML form, submit it, and handle it again with PHP.
Think of it like Tennis. You cannot change the way you hit the ball, after already sending it to the opponent. In this case, you can program both sides and make them handle the tennis ball accordingly.
php is server side scripting it can not assigned without page refresh.
Use javascript(client side scripting) variable to assign yes or no
else
{
?>
<script>
var myVar = "<?php echo $bldg[$i]; ?> station is already full. Do you want to save the other networks?";
if (confirm(myVar)) {
IsCanceled = "no";
} else {
IsCanceled = "yes";
}
alert(IsCanceled);
</script>
<?php
}
If you want to do some logic at client side you need to use JS without PHP in it.
And if you need to do logic server side so you need to POST or GET to the server.
Just open your page as source right after it loaded and you will see, that in place where you put PHP condition will be nothing.
It's because PHP already done all it's work. Check $IsCanceled and show page to you.
ALSO note, that if you need to check instead of assign you need to use double equals sign instead one e.g. if($IsCanceled == 'no') will check if variable IsCanceled equals string 'no'. BUT if($IsCanceled = 'no') tells php to assign string 'no' to variable IsCanceled it will be TRUE always because it's assignment and result of assignment is TRUE

How do I put a session value into a javascript?

I have a session['password']. I would like to get the session value and use it to validate against user's input.
if(opw != $_session['password']){
errors[errors.length] = "Sorry, password does not match.";
}
This is what I have been trying, however if I input this they do not read the session. And ignore this conditions. How do I actually insert session value into Javascript?
As the other answers have suggested, you have to embed your PHP session value into the javascript when the page is generator. But the others have forgotten one important thing - you have to generate VALID javascript or your entire script will get killed with a syntax error.
if (opw != <?php echo json_encode($_SESSION['password']) ?>) {
Note the call to json_encode - it's not just enough to output the password string. You have to make sure that the password becomes a VALID javascript string, which json_encode ensures.
Your inline JavaScript code:
var session = <?php print $_SESSION['password']; ?>;
Is that what you're looking for?
You need to surround the $_SESSION in <?php echo ?>. This causes the PHP variable to be printed into the Javascript on the page.
if(opw != <?php echo $_SESSION['password']; ?> ){
However, this is a deeply insecure method of checking a password and I advise against using it. If not transferred over SSL, the password will be sent in plain text on every page view. Furthermore, it is likely to be cached by the web browser where anyone with access to the computer may read it.
You'll have to actually echo out the errors manually:
// do all of your validation and add all of the errors to an array.
if($opw != $_session['password']){
$errors[] = "Sorry, password does not match.";
}
echo "<script type=\"text/javascript\">var errors = ".
json_encode( $errors ).";</script>";
Then, later:
<script type="text/javascript">alert(errors)</script>
Please note that PHP is totally different from JS. PHP is a server side coding-language, meaning it get's executed when your server is rendering the requested page. In that page (which contains some HTML) there can also be JS. However, JS cannot connect to PHP in the way you think it does. For this you could use Ajax or something (but that's way too complicated for the goal you're trying to achieve).
You probably want something like this
// eg. index.php or something
...
<?php
session_start();
if ($_POST['password'] == 'somePassYouDefined') {
echo 'Authenticated';
}else if (isset($_POST['password'])) {
echo 'Couldn\'t authenticate ...';
}else {
?>
<form method='post'>
<input type='password' name='password' placeholder='Password' />
<input type='submit' />
</form>
<?php
}
?>
ASP version:
if(opw != '<%=Session("password")%>' ){
I added quotes because a password is usually a string.
When the user runs this script, the html page that is downloaded to their computer will display the password IN PLAIN TEXT, ie:
if(opw != 'BOBSPASSWORD' ){
So, if they don't know or have a password, they can view/source and find it.

Categories