Alert box working at the time form submit using php - php

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.

Related

ERROR: localhost redirected you too many times USING PHP

Good morning, I'm a beginner in PHP. I'm developing an evaluation system for teacher and I have encountered this problem.
This page isn’t working localhost redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
MY CODE:
<?php
////DATABASE CONNECTION HERE!
session_start();
include("connection.php");
include("functions.php");
//CHECKING THE BUTTON IF IS IT CLICK!
if(isset($_POST['submit'])){
if(!empty(['submit'])){
if(!empty(['statement'])){
$statement1 = $_POST['statement1'];
$statement2 = $_POST['statement2'];
$statement3 = $_POST['statement3'];
$statement4 = $_POST['statement4'];
$statement5 = $_POST['statement5'];
$statement6 = $_POST['statement6'];
$result=mysqli_query($mysqli, "INSERT INTO results VALUES('','$statement1', '$statement2', '$statement3', '$statement4', '$statement5', '$statement6')");
if($result){
echo'<script type="text/javascript"> alert("YOUR RESPONSE HAS BEEN SUBMITTED. THANK YOU!") </script>';
}
}
else{
echo'<script type="text/javascript"> alert("SUBMIT YOUR RESPONSE") </script>';
}
}
else{
echo'<script type="text/javascript"> alert(" PLEASE CLICK ONE RADIO BUTTON PER QUESTIONS! </script>';
}
}
header("Location: evaluation.php");
die;
?>
Your problem is header("Location: evaluation.php");. You're inadvertently redirecting to yourself, infinitely.
Remove that statement.
TYPICAL ("CORRECT") BEHAVIOR:
User browses to your first page, e.g. "index.php".
You might do a database lookup to generate some HTML, or it might be static HTML.
In any case, the page contains an HTML form, and has a "Submit" button.
The user fills in the form, and clicks the button.
This calls your NEXT PHP page.
And so on...
It sounds like maybe you want your "first page" to query the database and present a list of teachers. Specifically, PHP will 1) query the database, 2) generate an HTML form, 3) which containins an HTML table, 4) one row per teacher.
The user selects a teacher (e.g. by clicking a radio button for the teacher on that row), and clicks "submit".
The "second page" might be an "evaluation form" for the chosen teacher. The user clicks "submit" on the second form when he's completed the evaluation.
The "third" (and final) PHP page might be an HTML message that says "Thank you for submitting this evaluation".
No "redirects". Just series of HTML forms, generated one at a time.
header() function returns error like ERR_TOO_MANY_REDIRECTS that change page name.php to some url like below.
header("Location: /index.php");
Or
header("Location: ./index.php");
Or
header("Location: ../application/index.php");

How do you show an alert box (in PHP) just before reloading a page or redirecting it to another page

I have this code right here which attempts to show an alert dialog box once a row is successfully inserted into the database. Also I want to reload the page after displaying the dialog box. It successfully pops up an alert box when commented out the header("location: link-1.php?e=Changes has been saved."), but when I uncomment it, the dialog doesn't show up anymore.
if(mysqli_affected_rows($connect) == 1){
echo "<script type='text/javascript'>alert('Updated successfully.');</script>";
header("location: link-1.php?e=Changes has been saved.");
}
else {
header("location: link-1.php?error=Something went wrong.");
}
Try this to show an alert and reload the page:
if(mysqli_affected_rows($connect) == 1)
{
?>
<script>
alert('Updated successfully');
location.reload(); // It will reload the page and reloading will get the latest inserted data from db
</script>
<?php
}
You can't call PHP Header to redirect since by sending out your html (javascript) your Header has already been sent. You need to redirect using javascript. window.location.href={your_url} will redirect.
But I don't think this is the right approach, you should probably do it backwards. Do the logic on redirect in PHP first, then on that script include your logic to whether show the alert box.

Update page after successful insertion into MySQL table

I am making a page that has a bunch of fields that allows the user to enter in information and submit it to a database. This page is called 'add.php' I created a 'form' tag and had the information posted to another page called 'process.php' where the information is collected, then inserted into the database. I want the user to know whether it was successful or not, so I was wondering how to tell the user something specific on the 'add.php' page. like "insertion successful!" at the top of the page.
I thought of including the 'process.php' code in 'add.php', then calling the 'add.php' in the action of the form, but the code gets called the first time the page is loaded, which inserts a completely blank entry into the database.
Should I implement some sort of flag that is only set to true after the 'submit' button is clicked? Or is there another way to update the page and tell the user the status of the insertion?
I can paste the relevant code as needed. :)
Thanks!
Assuming that you are using the post method in your form and php, you can simply check if a post was made:
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
// form was posted, process and display output
}
else
{
// nothing was posted, normal get request, show form
}
just check if query worked well. If no exception was thrown, it mostly has, and the add appropriate message with output.
First you need to check and handle errors
try
{
}
catch(Exception $e){
header('Location:oldlocation.php?succ=0')
exit();
}
header('Location:oldlocation.php?succ=0')
exit();
If all goes well, you can also redirect to a new location(as shown in code). This has to be done properly, you may redirect back to the old location, with additional data like
oldlocation.php?succ=1;
If anything goes wrong redirect to
oldlocation.php?succ=0
Then fetch the succ using $_GET["succ"] and print appropriate message.
If you din get, comment.
Here's what I would do...
Keep your processing data in one file, and include the form file at the end
//add.php
//if the form is submitted make the database entry
if(isset($_POST['foo']) AND $_POST['foo'] != '')
{
//code to process form submission
$success = 'success!';
}
//include the form
include addform.php
in addform.php put your form. Include an 'isset' that is watching for $success to alert that the entry was successful
//addform.php
<?php if(isset($success)){ echo "<h2> Data successfully entered! </h2>";} ?>
<form action='' method='POST'>
<input type='text' name='foo' />
//etc
</form>
So once you submit the form, the code starts at the top of add.php - the 'isset' sees the $_POST submission, runs the form submission code and sets the success variable. Then, it includes the form page. The form page has an 'isset' that is watching for the success variable. When you first navigate to the page, or if you refresh, the add.php code will skip the first code block (the form submission stuff) and won't make a database submission or set the success variable.

Form submit dialog

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.

returning from a form submit call to a .php file

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.

Categories