alert message won't display - php

I got a html page with 2 forms which are using the same php script..
<?php
if ($conn) {
if (isset($_POST['form_student'])) {
if ($_POST['form_student'] == 'Send') {
if (!empty($_POST["Ime"]) && !empty($_POST["Prezime"]) && !empty($_POST["BrojIndeksa"]) && !empty($_POST["TipNastave"])) {
header('Location: forme.html');
echo "<script>alert('Processing data to sql.');</script>";
} else {
echo 'You didnt fill all fields!';
echo "<script>alert('You didn't fill all fields!');</script>";
}
}
}
if (isset($_POST['form_subject'])) {
if ($_POST['form_subject'] == 'Send') {
// same checks just like above with redirecting
// and displaying alert box
}
}
}
?>
First problem is when I don't fill all fields in, it does work and echo 'You didn't fill al fields!' but doesn't display alert box message, and it only doesn't work when I don't fill all fields. And I'm wonder how can I actually by processing php script, without redirecting to that php script page, show msg box on html page, is it possible with out ajax or jquery, or I should instead using html extension change into php, and do all checks there and avoid processing script into action=""?

That's because of the row ..
echo "alert('You didn't fill all fields!');";
Try this one instead ..
echo "alert(\"You didn't fill all fields!\");";
What you did wrong was that you had an apostrophe in the string and around the string. I don't know how to explain this but I simply made the two quotation marks to not conflict with the php echo.
Update:
Regarding the second question about the redirect and such. Could you explain it further because I don't understand a word?

Related

How to go to new page on form submit only if form passes error checks?

I have an HTML form with PHP error checks. The form has several different types of fields (one for name, email, phone number, a checkbox, a drop down, etc.) and I have a PHP function written for each that runs when you hit the submit button, and checks that the form is filled in correctly and fully. If a field is left empty, or is filled in incorrectly, an error message appears. However, after I got that running, I tried to add a redirect, so that after the form is completed and submit is pressed, it brings the user to a confirmation page, if the errorchecks are passed. I wrote it like this:
if(isset($_POST['submit']) ){
header("Location:confirmed.php");}
It does what it's supposed to--bring the user to a new page--but it doesn't take into consideration any errorchecks. So, when submit is pressed, rather than run through the error checks, it immediately goes to the new page. I tried adding a variable named "errorcount" so each function so that the number of errors that occur when the form is submit will be either counted, or removed from the count, and then considered when changing the page...
if(isset($_POST['submit']) ){
if ($errorcount == 0){
header("Location:confirmed.php");}}
This didn't work either. I realized that $errorcount wasn't actually being updated at all; for what reason, I'm not sure. I set it up so each function returns $errorcount, and then called each function in the snippet of code above before running the second if statement, but it still does nothing.
I feel like I'm approaching this the wrong way, but I'm not really sure how else to do this. Please tell me if there's an easier way to achieve this, or maybe you have an idea what I'm doing wrong in the first place.
EDIT:
I am passing the variable $errorcount as global in each function, like so:
function validateName ($name, $submit){
global $errorcount;
if( empty( $submit )) {
return '';}
if (empty ($name)){
return "You didn't enter your name!";
$errorcount = $errorcount+1;
}
if (!preg_match("/^[a-zA-Z \-]*$/",$name, $matches)){
return "Please enter a valid name";
$errorcount = $errorcount+1;
}
else{
$errorcount = $errorcount-1;
}
return $errorcount;
}
However, $errorcount still does not actually change with the if loop I posted above. If I take that out (the section of code that causes the page to change) then the functions work as intended; once you click submit, the page refreshes, and error messages appear where the user did not fill out the form properly. But once all the form areas are filled out properly, clicking submit does... nothing.
EDIT 2:
I got it working. It's honestly not very efficient but it does what I need it to do. Thanks to all who helped!
You don't really need to count the errors, and you don't need to use global. Just write your validator functions so they return an error message if there is an error, or nothing if there is no error. Like this, for example:
function validateName($name) {
if (!$name) {
return 'name is required';
}
if (!preg_match("/^[a-zA-Z \-]*$/", $name)) {
return "Please enter a valid name";
}
}
Then when you run your validators, add any error messages you get to an array.
if ($error = validateName($_POST['name'] ?? '')) {
$errors['name'] = $error;
}
After you run all the validators, if the error array is empty, then there were no errors so you can redirect. And if it's not empty, then you have an array of errors keyed by field name, so you can display any errors next to the problematic fields, which your users will prefer rather than getting one error at a time in some generic location.
if (empty($errors)) {
// redirect
} else {
// stay here and show the errors
}
You're needlessly complicating things. Defining functions are only useful if you plan on re-using that code elsewhere. Try this instead:
if ( isset($_POST['submit']) )
{
if ( empty($name) )
{
echo "You didn't enter a name!";
sleep 3;
// redirect or re-load the form
}
elseif ( !preg_match("/^[a-zA-Z \-]*$/", $name, $matches) )
{
echo "Enter a valid name!";
sleep 3;
// redirect or re-load the form
}
header("Location:confirmed.php");
}

Five unique pages lead to one page. Can I change the <h1> according to the page they came from?

I have five unique forms each on a page of HTML. They then go to a PHP file to send the e-mail of data. Next they go to the HTML thank you page. I am hoping to change the heading according to which form they just submitted.
For example, if they submit a review, the should read "Thank you for your review" etc.
Technically all of these are saved as php files but only the e-mail page has php items.
Like <?php echo("<p>". $mail->getMessage()."</p>"); ?>
You should redirect to another php file and pass a parameter on url. Example:
sendemail.php
<?php
/** After send the email, check what kind form is (I don't know how do you check this).
This example is just to show you: */
if ($formType == 'review') {
$type = 'review';
} else if ($formType == 'anothertype') {
$type = 'anothertype';
}
header('Location: /thankspage.php?type=' . $type);
?>
thankspage.php
<?php
$type = $_GET['type'];
if ($type == 'review') {
echo '<h1>Thanks for your review</h1>';
} else if($type == 'anothertype') {
echo '<h1>Thanks for your anothertype</h1>';
}
?>
One way put a hidden field in your forms that'll get passed with the other form data. Then put an if statement on the thank you page and echo the appropriate message.
However, that'll only work either if you change the thank you page to php or change the page that receives and processes the form data to echo the thank you message as well

How to display empty field error message

I have a page which allows the user to "create a topic", open submitting this the form goes to another through a verification process which inserts the topic into the database and re-directs to back to the main page. However I want my verification page "add topic" to display an error message if all fields are not filled in. here is a my code, please can you tell me where I would need to add this validation code to notify the user to fill all fields:
// get data that sent from form
$topic=$_POST['topic'];
$detail=$_POST['detail'];
$name=$_POST['name'];
$email=$_POST['email'];
$datetime=date("d/m/y h:i:s"); //create date time
$sql="INSERT INTO $tbl_name(topic, detail, name, email, datetime)VALUES('$topic', '$detail', '$name', '$email', '$datetime')";
$result=mysql_query($sql);
if($result){
echo "Successful<BR>";
echo "<a href=main_forum.php>View your topic</a>";
}
else {
echo "ERROR";
}
mysql_close();
My suggestion would be create a separate php file called validation and inside the validation file add a function. Of course you can create this function inside the same php file. If you made the separate use an include statement to place it on your page. Also a quick post-back to itself would be good since you could easily be able to get access to the posted variables and already be on the page to show errors. Otherwise you would have to return the Errors in a get, post or session. If everything was successful you could post or redirect right after the postback (maybe to a success page) and the user would only see the postback if errors present.
include_once("Validation.php");
as shown above.
validateNewTopic($topic, $detail, $name, $email, $datetime)
{
}
Then inside you could use if statements to check conditions. If you want a quick solution you can create a variable to hold all the errors.
$Error = "<p class='errors'">;
if ($topic == "")
{
$Error+="topic is required";
}
if ($Error != "<p class='errors'">)
{
return $Error +"</p>";
}
else
{
return "";
}
Since you are posting the values you can catch them in a variable on postback to validate.
$topic = $POST['topic'];
$Error=validateNewTopic($topic);
if ($Error != "")
{
?>
echo $Error
<?php
}
else {
//run sql code and show success
}
By putting the paragraph tags inside the $Error messages we can just echo and it will already be in the paragraph tag with the class errors. You can make it prettier by using an un-ordered list and when adding an error using list items. I'm not sure how familiar you are with php but at anytime you can stop writing php code by closing the tags. (< php ?> and reopen < ? php) as shown above in the if statement. I know this was not 100% clear but this is something you should try/research and practice since it is used so often. Good luck!
You can send the error to the main page by using php GET request, and then display it.

Reset the form data on unload

I'm using this code:
if(isset($_POST['btitle'])) {
if(count($errors) > 0) {
foreach($errors as $error)
$errContent .= "<li>".$error;
echo notification(
$errContent,
FALSE,
"The following errors were encountered:"
) . "<div style='margin-bottom: 10px;'></div>";
}
else {
echo notification(
"<li>New form added!",
TRUE,
"Success:"
) . "<div style='margin-bottom: 10px;'></div>";
}
}
When I type something in the input named 'btitle' and hit the submit button, everything is fine, until I refresh the page - it should loose the data and start again after refreshing, but it keep saying "Success:" even if the 'btitle' input is empty.
What am I doing wrong?
you need to redirect the user to the same page and loose the post data.
header("Location: file.php?success=true");//or ?errors[]=blabla
exit();
now, in the same page (file.php) you need to:
if(isset($_GET['success']) && $_GET['success'] == true){
//handle true
}else if(/* here you can ask about errors or what ever */){
}
BTW, if you don't do it, the entire submitting form will be act again like you resubmit it.
for instance, if you insert data to the database, it will be insert over and over again when you refresh the page, so if you redirect as suggested, you loose the posted data and now you can show the errors or success.
When you hit refresh, your browser resends POST data to the page. This question has been asked many times, for instance here and here. Take a look at the answers to some of those questions to get an idea of what you can do.

improve my PHP user interaction

I have a situation where a user fills out 1 of 2 forms on a registration page and is sent to a software download page. If they sign up as a new user, form is processed inserted into a MySQL database and they go to the page no problem.
Here is my issue. If they are a returning user and enter a license key, the processor script checks to see if its valid against the database and if it is it sends them to the software download page. If it is NOT a valid license key (heres what I dont like) the screen goes to the url of the script, page is white, an alert pops down telling them its not a valid license key and they are returned to the registration page to try again. I hate this. I need to figure out a way to either pop the alert on the registration page w/o leaving it or better yet display some kind of message on the page. One drawback is that the script is and always will be on a different server than my forms. Ive tried curl and had success with other situations but can't close the MySQL connection on this one. Is there another way to achieve some semblance of "cross domain AJAX" I would really like it to not go to the script url/white page/alert then return them. I would like it to happen all on one page. Here is that part of my script:
if ($_POST['license_code'] != "")
{
$result = mysql_query("(//mysql stuff here)");
if (($row = mysql_fetch_assoc($result)))
{
header("Location: http://" . $redirect);
}
//here is the part I dont like
else
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The license ID you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
}
mysql_close($link);
}
//I use jquery valiadate.js for CS validation, but realize this is necessary and would like it to behave like the desired result for the above
else
{
if (strpos($_POST['email1'], '#') === false)
{
echo "<html>\n";
echo "<body>\n";
echo "<script language=\"Javascript\">\n";
echo "alert (\"The email address you entered was not correct.\");\n";
echo "window.location=\"http://www.registrationpageURL.php\";\n";
echo "</script>\n";
echo "</html>\n";
echo "</body>\n";
return;
}
thx
Is it possible to remove the alert and when you redirect to registrationpage.php also send a parameter using the redirect url and popup an alert or error message after the redirect ?
Look into using AJAX. jQuery has a great API for this:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/load/
EDITIED - For cross-domain
You could do something like this:
<div id="results"></div>
<script type="text/javascript">
$("#the_form").submit(function() {
$.getJSON("http://remote.domain/script/to/validate.php?data=" + escape($(this).serialize()) + "&callback=?", function(data) {
$("#results").html(data);
});
return false;
});
</script>
This will (once the IDs are pointed at the correct elements) intercept the form submission, pull together the values from the form (through the serialize() function), and shoot it out to the validation script via AJAX. The output of the script is displayed in the #results div.
Hope this helps!

Categories