Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
First question here, so please be patient with me.
I am developing a website for my company. I have an HTML form that uses a php file to email me the data entered by the user. But the user is routed to an ugly .php page with a simple "Thank you" message.
My question has several parts.
Is it standard to have a "Successful Submission" page which looks nice and fancy, or is it fine to just stay on the page the form is on?
If it's fine to stay, how do I execute the php code to send the data without leaving the page?
Further, if I stay on the page, how do I display a message over it saying something like "Thanks, your form was submitted"?
Considering question 1
Is it standard to have a "Successful Submission" page which looks nice and fancy, or is it fine to just stay on the page the form is on?
It is not mandatory to have a separate page to display response to the end user. Actually it depends on the scenario for which you are developing the page. The main intention is to provide the best UI experience for the end users / visitors of your site. If there is some crucial information with large content, then it is better to show it in another page after form submission. If it is just a success message then it is fine to stay on the same page after form submit and show the response message there.
Now coming to question 2 and 3
If it's fine to stay, how do I execute the php code to send the data without leaving the page?
Further, if I stay on the page, how do I display a message over it saying something like "Thanks, your form was submitted"?
You can accomplish it using ajax. With the help of jquery you can make it much simpler using
$.ajax function
Ex :
$("#formbutton").click(function(){
$.ajax({
type: "POST", // method
url: "savecontact.php", // call to external php file
data: {name:n,contact:c}, // passing variables to php file
success: function(result) {
// get the response after ajax call is successful
},
complete: function(result){
}
});
});
Now in savecontact.php you write the necessary code (usual php code to insert into table) to save the data and return response.
Ex:
result = mysqli_query("INSERT INTO table (NAME ) VALUES ('val')"));
if($result)
{
echo "Success";
exit;
}
else
{
echo "Error";
exit;
}
After ajax call gets executed, inside success function of ajax call you will get the response either Success or Error and based on that you can display the message into an empty div which normally placed above the form.
success: function (response) {
if(response == "Success"){
$("#div").html("Thanks, your form was submitted");
}
else{
$("#div").html("Issue with form submission.Please try again");
}
}
The appropriate message will gets display after form submit as ajax response.
Is it standard to have a "Successful Submission" page which looks nice and fancy, or is it fine to just stay on the page the form is on?
Answer: It will be good if you show Thank you!!! message on same page if the page is having other content also.
If it's fine to stay, how do I execute the php code to send the data without leaving the page?
Answer: You can use AJAX to send async request to server with data filled in form.
3.Further, if I stay on the page, how do I display a message over it saying something like "Thanks, your form was submitted"?
Answer: Once you get success response from AJAX you can change the HTML code with Thank you message, and if you get some error while submitting form, you can show that error on same page without refreshing page.
It usually is based on your preferences.
For me, I usually include my validation script on the action page (Redirects to a blank page temporarily). I save my post variables into my session so I can reload the form later. If there is an error, I save the error message in a session variable then redirect to my form page. In my form, I include in each input element this fragment
value=<?php if isset($_SESSION['var_name']){echo $_SESSION['var_name'];}?>
If the data is valid however, I will execute certain stuff (database inserts, mailing, etc...) before redirecting to my landing page (usually the homepage).
As to properly answer your 3 questions:
Like I said, it is preferential. It can range from a simple pop-up to redirect,to a full fledged page. However, it IS standard to inform your user about the submission's status. He won't be doing guess work on your page.
If you want to stay on your form page, try to send your form through AJAX to your validation script. Nice and simple
Refer to #2. You execute your code in the AJAX snippet
Yes you can use same page which your going to submit form.
You can set action to another .php page as example sendEmail.php
action="sendEmail.php" method="post"
and you can get form submitting value in there. when the email sent you can put condition like this
if(emailSent == true){
header('Location: http://www.example.com/index.php?success=true');
}
when the sendEmail.php redirect to the index page you can get url value using php. And display the success message
$paraVal = $_GET["success"];
if($paraVal == true){
// display message
}
Related
I am trying to show a paper-toast when the user forgets to fill in some data in a form or when he submits a wrong e-mailadres.
I have this PHP-code that will print out an error message on the screen when the user submits the form and forgets to fill in the input or when he submits a wrong e-mailadres. This works fine. Here's a small part of the code:
<?PHP
if(isset($errorMsg) && $errorMsg) {
echo "<p>*",htmlspecialchars($errorMsg),"</p>\n\n";
}
?>
I want to make it so, that the error message appears in a paper-toast. Further, i want to display a paper-toast when the form is successfully submitted.
My question is: is it possible to call a paper-toast with the error message and appears when the form is submitted?
Thank you in advance,
The only way PHP can "trigger client side events" is by outputting HTML that will behave as you want. In your case, you basically need to output the HTML for a toast and make sure it opens as soon as the page is loaded. To do that, just set the opened attribute:
printf('<paper-toast text="%s" opened></paper-toast>', htmlspecialchars($errorMsg));
My goal is to set a Google Conversion value from a custom field defined in WordPress. The conversion script is located on the landing page, so I need to get my custom field data from my form to the landing page. I can't use GET or POST as the form submission is handled by a third party and no data is returned to the actual landing page.
So I've tried using a PHP session, but this third party is getting in the way of just being able to use PHP, because it's keeping all the data for itself.
This is the approach I'm hoping I can get working:
The validation for the form is done using jQuery Tools.
I then need to submit the variable after validation has been successful via jQuery/AJAX to a separate php file.
Then as the landing page starts to load, I must grab that variable from mentioned PHP file and echo it in the relevant place.
I figured I don't actually need to start a session on the page with the form, as jquery is grabbing the data straight out the input, not any session data. So here's my input with conversion value:
<input type="hidden" id="conv" name="conv" value="90">
Then my form validation:
$("#course-form-modal").validator().submit(function(e) {
// when data is valid
if (!e.isDefaultPrevented()) {
// this grabs the value from my form
var con_val = $("#conv").val();
// and this sends it...
$.post(
"../../usersession.php",
{ data: con_val }
);
}
});
Then I've got the code in usersession.php... where I sent the data:
// As I'm just trying to echo what was sent to this page, via ajax, I shouldn't need to worry about starting/retrieving a SESSION yet... right?
<?php $var_value = $_POST['data']; ?>
<div id="results">
<?php echo $var_value ?>
</div>
// I CAN WORRY ABOUT THIS HALF LATER. RIGHT NOW I JUST WANT TO ECHO MY RESULTS ON USERSESSION.PHP //
Finally, I've got the code on my landing page to retrieve the data from usersession.php:
session_start();
$var_value = $_SESSION['conv'];
echo $var_value;
I'm not entirely sure all this code is right for starters, I'm more of a front end guy...
-EDIT-
Right, I'm pretty sure the code is correct at least now. For some reason it's still not working though. At the moment I'm wondering if WordPress would prevent me writing to usersessions.php from my javascript file (for reference, that file path is set absolutely in my working (not working) example)? I know WordPress will sometimes throw a 404 when you try to access a file directly.
The other potential issue could be with the third party software, vanillasoft. I've a link to their script in the action tag of my form, could that somehow bypass/kill the sending/receiving of data between the form > usersession.php > and then the landing page?
On a side note, if anyone has a great idea on how I can test if usersession.php is receiving the data then please let me know? I did have this code originally, but it returns nothing and if I link straight to the file after a send something (as in just paste the file url in to my browser) it returns a '0'...
if(isset($_POST['conv'])) {
session_start();
$_SESSION['conv'] = $_POST[''conv''];
echo "1";
} else {
echo "0";
}
Set your ID on the input. jQuery is looking for the ID, but you have only set the name.
<input type="hidden" name="conv" value="90">
Should be:
<input type="hidden" name="conv" id="conv" value="90">
EDIT:
Can't believe I didn't catch this earlier. Your problem is in the usersession.php at the following line.
$_SESSION['conv'] = $_POST[''conv''];
You have the POST quoted wrong.
It should be:
$_SESSION['conv'] = $_POST['conv'];
EDIT (re: New js edits)
In you java script your post vars should be formatted thusly:
{ name: "John", time: "2pm" }
So your line should be something like this:
$.post(
'../../usersession.php',
{
conv: $("#conv").val()
},
function(data)
{
alert("Data Loaded: " + $("#conv").val());
}
);
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.
I have a form that is shown inside a Colorbox. When users click submit there is some validation done (checking if an entered field already exists in my database) if it does a message is shown and user is prompted to enter a new value. However when this happens the form is not shown the second time inside the Colorbox window, instead it appears on a blank page.
the form is posted to PHP_SELF, how can i change this to show in PHP_SELF (in the current Colorbox)?
cheers
I know this is aside from what you are asking, but
What if you used jquery's submit() and post() instead of PHP_SELF to pass form data to an external php class and handle displaying the return data? If the data is acceptable, you can call $.colorbox.close() manually. If data is unacceptable you can display a message to the user describing the problem.
$('myform').submit(function(){
//validate the data with javascript
//send the data to your function with post
$.post('http://url/to/your/function',{a:first_input,b:second_input},
function(return_data){
if(return_data == 'success'){
$.colorbox.close();
}else{
//display your error message here
}
,html
);
});
I know how to get an AJAX response:
$.post( '/action',
{ actiontodo: 'insert' }
function (data) { alert(data); } );
Int the action.php (server side):
<?php
if ($_POST['actiontodo'] == 'insert')
{
doInsertAction();
echo "inserted";
}
?>
Finally the output of this code is an alert BOX with the word: inserted.
BUT, without ajax, I have two ways to solve this (in the server side):
ONE:
<?php
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
header( "Location: " . $_SERVER['HTTP_REFERER'] . " &response=inserted" );
} ?>
TWO:
<?php
session_start();
if ($_POST['actiontodo'] == 'insert') {
doInsertAction();
$_SESSION['response'] = 'inserted';
}
header( "Location: " . $_SERVER['HTTP_REFERER'] );
?>
Returning to the page I get the answer from the SESSION or from GET and shows the alert.
I like more the ONE solution, but each solution has a problem:
ONE problem:
The returning URL is : http://www.foo.com/myrefererurl&response=inserted
If you types this URL without using the form, you will see the alert BOX each time you will refresh the page. The question is: How to show the message only ONE time? (ONLY AFTER THE FORM ACTION)
TWO problem:
The SESSION now has the value inserted ($_SESSION['response']), when the page returns from the action obviously the solution maybe delete this value of the session like: unset( $_SESSION['response'], but SUPPOSE the UNSET do not reached for any reason (connection failure or navigation stopped by the user, etc), when you go to another form in other page the alert will showed because the $_SESSION['response'] still exists (in another form without submit it and has nothing to do with that response). Inclusively WITH GET &response=inserted in another URL the problem will exists too.
I hope you understand this questions and bring a BEST WAY solution. Basically the question is how to control that responses......
Unobtrusive JS, or "progressive enhancement" is the way to go.
Step 1:
Build your page first to work without JavaScript. Let's say you have a simple application where a user selects something and hits submit. Depending on the selection, you will either display a helpful error message above the form or you'll update the page with the correct output and hide (or get rid of) the form. Build this page like you would for AJAX, but do not script anything yet.
Here's your page:
<html>
<head>
<style type="text/css">
p#feedback { display:none;}
</style>
</head>
<body>
<div id="feedback"></div>
<div id="form">
<form action="getaction.php" method="post" id="actionform">
<select name="requestedAction">
<option value="foo">Do Foo</option>
<option value="bar">Do Bar</option>
</select>
<input type="submit">
</form>
</div>
</body>
</html>
On a successful submission. the server will get a request with one $_POST value: requestedAction=foo (or bar). Based on this, your server script will construct a new page with everything from <html> to </html>.
At this point, you have a page that works in any non-JS-enabled browser. Old fashioned. Very reliable.
Step 2
Add the scripting to override the default submit behavior. Grab the data you need from the page and construct an AJAX submission. The only difference between this and the submission above is that you will add a flag telling the server that the request is coming via AJAX and to send back only the needed message (you could also send it to a different script). The server script will basically go through the same logic as above, but rather than building the entire page, it only sends back the message string and leaves it to AJAX to put that data in the right place. Your response could be just a text fragment, a block of HTML or an XML data structure. It depends on your needs.
<script type="text/javascript">
$(enhance); // at onDOMReady, run the enhance function
function enhance() {
// Override the default form submission behavior:
$('form#actionform').bind('submit',doSubmit);
};
function doSubmit(event) {
$.ajax(
{
type:'POST',
url:'/path/to/getaction.php',
data:'request=' + $('form#actionform select[name=requestedAction]').val() + '&type=ajax',
success:fnCallback
}
);
// Kill the submit action so the user doesn't leave the page
event.preventDefault();
};
function fnCallback(xhr) {
var strResponse = xhr.responseText;
if (strResponse === "error") {
$('div#feedback').text("There was an error. Please try again.");
}
else {
$('div#feedback').text(strResponse);
$('div#form').hide();
}
};
</script>
In this case, the AJAX submission will be identifiable to the server because there is a second POST parameter of type=ajax.
A site that does this really unbelievably well on a very big scale is ESPN. Turn off JS and check out their main story headlines under the big picture. The behavior is identical to their AJAX-enabled page and aside from the video not working, you really would never know if your JS was on or off. There's basically no way to build a site like this without starting from dumb HTML and building up.