I have a basic form that asks for certain information and then validates the form using javascript before actually submitting it to a seperate php file to email the form submission to me however, after successfully submitting the form, it goes to blank page and then a Thank you popup shows up. How do I set it so hitting the submit button doesn't go to a new page but just displays the popup on the current page?
My code for filling out the form is:
<form action="send_group.php" method="post" onsubmit='return formValidator()'>
//Asks to input information
<input type="submit" value="Submit" />
</form>
My PHP code is:
<?php
$webmaster_email = "email#email.com"; //E-mail the message will be sent to
$info = $_REQUEST['info'] ;
$info1= $_REQUEST['info1'] ;
$info2= $_REQUEST['info2'] ;
$info3= $_REQUEST['info4'] ;
mail( "$webmaster_email", "Information Form Submission",
"Info: $info
Info1: $info1
Info2: $info2
Info3: $info3" );
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for your booking request. We will get back to you as soon as possible.');\n";
echo "</script>";
?>
You have to use an AJAX request.
So you bind an onclick event on your submit button, then you send an AJAX request, and when the AJAX request suceeded you display your response (Bad or not).
JQuery is really powerful and easy for AJAX request, look here : http://api.jquery.com/jQuery.ajax/
You can either use AJAX to submit the data in the background, or, the easier option put the from and php into the same php file.
Well, the browser shows exactly what it receives from your php-script.
One way to solve your problem without Ajax could be the following approach: To display your original page after the request has been processed add e.g.
header("location: your_form_page.php?req=1");
in case of success, and e.g.
header("location: your_form_page.php?req=-1");
in case an error occurred to send_group.php. The GET parameter req can be used to display either the thank-you-box or an error message. The switching logic must of course be implemented already in your_form_page.php, e.g.
if ($_GET['req'] == '1') {
echo "<script type='text/javascript'>\n";
echo "alert('Thank you for ...');\n";
echo "</script>";
} else if ($_GET['req'] == '-1') {
echo "<script type='text/javascript'>\n";
echo "alert('Error ...');\n";
echo "</script>";
}
You have to redirect the user after the script successfully finishes, using the location header
header("location: formPage.php?success=1");
Then on your original form page you can run the javascript.
Use xhrRequest (ajax) for retrieve information from validation page and then show result to your user.
Related
Alert box is not working at the time of submitting the form. Nevertheless, I get 'Customer Added Successfully' message in php. But I don't get an alert box. My code is given below:
if($_POST['submit'])
{
$name=$_POST['name'];
$phone_number=$_POST['phone_number'];
$email=$_POST['email'];
$sql="insert into
customer set name='$name',phone_number='$phone_number',email='$email'";
$in executeUpdate($sql);
if($in)
{
echo "<script type=\"text/javascript\">".
"alert('success');".
"</script>";
$sess_msg="Customer Added Successfully.";
$_SESSION['sess_msg']=$sess_msg;
}
header("Location: addCustomer.php");
}
You're sending a Location: header which results in a redirect, so the browser ignores any code in the page (including the javascript containing the alert).
You either need to remove the redirect (display the alert and a link to the next page), or display the alert on the target of the redirect. I'd go for the second option to avoid issues with reloads on a POST.
Apologies if this has been asked before, but I am working on my first site and still learning. I am trying to add a captcha to the contact form taken from here http://www.captcha.net/ and using PHP.
At the moment it is working, but the code supplied on the site for it to work is as follows:
<html>
<body> <!-- the body tag is required or the CAPTCHA may not show on some browsers -->
<!-- your HTML content -->
<form method="post" action="verify.php">
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<input type="submit" />
</form>
<!-- more of your HTML content -->
</body>
</html>
and the verify code for it on a different file (server side) is:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
What I am wondering is if there is a way to have the if statement (if the captcha is wrong) open the contact page but show a hidden div displaying that the captcha code is wrong and try again.
In your case, You can try this way:
verify.php
if (!$resp->is_valid) {
header("Location: contact.php?show-error"); // replace by your file name
exit;
}
else {
// Your code here to handle a successful verification
}
contact.php
if(isset($_GET['show-error'])){
echo "<div>
The reCAPTCHA wasn't entered correctly.
Go back and try it again.
</div>";
}
Or:
<div style="display:<?php echo isset($_GET['show-error']) ? "block" : "none"; ?>">
The reCAPTCHA wasn't entered correctly.
Go back and try it again.
</div>
But in your case, I think it's better to move verify code to contact page. So you can easy decide to show a message depend on if condition.
I'm not sure what the purpose of your "hidden div" idea is. Aren't you just providing users with a form to enter details and a captcha, and then when they submit you verify ALL their inputted data? If all ok submit, else show errors and make them amend.
If so, could you not put the captcha code on your contact page?
If in the same file as your form, when user submits (PHP_SELF) you can run through the entire form data they sent checking what they inputted (is_numeric(), strlen(), etc) and then also check the captcha.
After all checks, if any errors at all, tell them where/what and they can try again. Otherwise action the form (email you, store in DB, whatever).
You can then check the captcha on the same page:
if (!$resp->is_valid)
{
$CaptchaError = "error";
// echo is invalid, reset form and make them try again
}
else
{
$CaptchaError = "ok";
}
If for whatever reason you need to captcha code in a separate file to your form, then just POST or set url vars GET or SESSION so when you send them back to wherever the captcha form is with header redirect, you have the data to serve them with the error notice.
Though processing this all on one page with POST data is usually the easiest and most manageable method.
Rather than doing a die, take the message in a variable called $error. Based on isset($error) being true or false, you can make the div visible/hidden on the page load
Inside the if statement (if the captcha is wrong), you could replace the error message with something like this:
if (!$resp->is_valid) {
header("Location: http://yoursite.com/contactformpage.php?error=captchaerror");
exit;
} else {
// Your code here to handle a successful verification
}
Just be sure to replace http://yoursite.com/contactformpage.php to whatever the actual URL to your contact form page is, but keep everything else (?error=captchaerror) as is.
Then on the contact form page you can have another if statement like this (put it wherever you want the error message to appear):
if(isset($_GET['error']) && $_GET['error'] == 'captchaerror') {
echo "The reCAPTCHA wasn't entered correctly. Please try again.";
}
If you have other possible 'error' scenarios you can change the "captchaerror" part of the url and repeat the steps above.
If you're not familiar with PHP $_GET variables, take a look at this page: http://php.net/manual/en/reserved.variables.get.php
I have a questionnaire in a form. In the end of it the submit button is pressed that is supposed to call a .php file that inserts data into a database through its action information and afterwards show the last page that contains something like "thank you for participating etc." via the onsubmit info.
problem is that the last page is shown before the .php file is shown which means it is visible only for like half a second and then the php script is carried out which ends up showing a blank page.
The php script works it inserts data into the questionnaire correctly so there should be no mistakes syntax-wise.
any ideas if I have to exit the cript or something and return to the .html file or what could be wrong?
on your opening form tag add action="submit.php"
then once it goes to that page when the submit button is hit add this to the bottom of that php page:
header("Location: successfull.html");
IT sounds like what youre doing is showing the message with Javascript via the onsubmit event - this happens before the request is even set to the server and the php script. Youd either need to do an ajax form submission and then display the message when the request completes or make the php script redirect to the success message page when it is done.
But this is all just speculation without seeing any code... you should post some :-)
Why not submit the form to process.php then process it:
if(isset($_POST)){
$name = $_POST['name'];
// etc etc
// if all error checks pass, then echo out - thanks for taking part in our survey!
}
What you're doing is submitting it, and it seems you're getting javascript to say 'thank you' but it is being submitted before this thank you message can be displayed - no harm in echoing this out on your .php page!!
Update
You mention about redirecting to a page afterwards, but this can be done by:
header("Location: where/to/go.php");
exit;
But you can't do this with the above (echoing out a success) since it will redirect straight away.
The way I deal with this is putting the html contents into the php file.
<?php
if (!isset($_POST["submit"])) { // if page is not submitted to itself echo the form
?>
<html>
<head>
<title>survey</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
...... (your form) ......
<input type="submit" value="submit" name="submit"><br />
</form><br />
</body>
</html>
<?
}
else {
$db = new PDO('...');
$db->exec(...);
echo "Thank you!";
}
?>
A few ways you could accomplish that.
You could make the php file it submits send out the data for the "thank you for participating" page (if you're fine with simply going to another page).
Alternatively, if you want to stay on the same page but just show the "thank you" notification, I would use JavaScript to disable the default action (e.preventDefault(); in the event handler) for the "submit" button on the forum, then also use JavaScript to use AJAX to submit the data.
An example (using JQuery), which won't change your page and perform the submit in the background, and display the "thank you" when done, on the current page.
$("a#confirmSubmit").click(function(e) {
e.preventDefault(); // Prevents the submit button from changing pages
data = {
Name: $("input#Name").attr("value")
// Add other data here also
};
$.post("/page/to/submit/to.php", data, function(d) {
//Write the code here to show the "thank you" notification.
//It will show upon completion here.
});
});
If you want to check for errors with inserting into the DB, you could check the value of the data of the AJAX call, to conditionally show the error. You can then return the user to the exact same form they were already on, with all the data still there, and show them an error message.
echo '<td><input type="text" name="input"></td>';
echo '<td><input type="button" onclick="function(input.value);"/></td>`;
written in php. it's all in a table which is in a form. The function is executed properly, sends the data into a new php file and is running some data validation tests displaying some (error) messages according to these test results.
if the input is correct, i want the code to insert the value into a database and refresh the whole page. The data is being inserted, but the page is not refreshed.
I use this at the end in order to refresh but it doesn't seem to work:
echo '<script type=text/javascript language="javascript">document.location.href="page.php"</script>';
So you send some data back to an php file and in the event that some conditions are not met you send back some error messages, in the case they are met, cant you just simply use:
header( "Location: page.php");
exit;
i use of php and jquery in my application
i want when users submit success a form in page1 , forward form page1 to page2 and show a pop-up message(like this site) "success" and when they do not submit success , dont forward and just show pop-up message "error"
how i can implement this process?
thanks?
In your form, you can add some javascript into your form tag like so...
<form action="page2.php" onsubmit="if (CONDITION) {alert('Success'); return true;} else { alert('Error'); return false;}">
<input type="submit" value="Submit">
</form>
You can just a call a function ("return checkCondition();") in the onsubmit part and write the function in a separate Javascript file.
If the Javascript in the onsubmit part returns true, then it will go to the page specified in the action. If it returns false, then the form validation fails and it will stay where it is.
You would use something like this:
<?
if($form_success) { //
header("location: formpage2.php?success=1");
}
else {
header("location: formpage1.php?error=1");
}
?>
If you wanted to pass form data from page1 to page2 on success, use either or URL query string or store whatever's in $_POST in $_SESSION.
For the popup message, I would check for a success value in the query string of formpage2 and from there use javascripts alert to alert the user of their success.
I would not rely on Javascript itself in the first "return CheckCondition() in onsubmit" (by Muddybruin), but I would use it! I would not rely on it because the visitor CAN turn of Javascript and easily bypass the functionality.
I would also use the "header-redirection-answer" (by Levi Hackwith), but I would modify it to:
<?php
//checkform.php
if($form_success) {
//Include template or code here when form is successful
}
else {
//Include template or code here when form is unsuccessful
}
?>
If you absoutely must go to a specific file when form is successful, then I would include it instead of redirecting it. This is because redirections can cause unnessary issues regarding to links indexing in searchengines and it would be a lot slower than to just include directly into the checkform.php. Also keep in mind that header redirects must be sent BEFORE any other output is sent from the script.