Confirm Form Submission - javascript

I'm new to web design, and I have a question about cache.
I have a page called buy-form.php that gets form data from form.php. I want it to have the cache error that makes Google Chrome read "Confirm Form Submission" when the is page accessed manually.
For example, I only want the page to be accessible when form data is submitted. If someone were to type in the page on the address bar, it should have an error.

A javascript alert("Confirm Form Submission"); can handle your request, and be effective across browsers. Call a function for the event <input [other attributes here] onclick=myFunction()> that has the alert you want. The alert will stop execution of the page until it is confirmed (selected). Attach a security code to your form submission and PHP can check for it and die; if it is not valid.

Add this statement to your buy-form.php:
if(empty($_POST))
{
echo "<script type='text/javascript'>alert('Error!');</script>";
}
You can replace 'Error!' to whatever you prefer

Related

Wordpress Login Form - How to show error message without reload page

I'm building my own custom login page for wordress. The login form seems to work, however I would like to be able to customize the error message more specifically.
When the login credentials are incorrect and you log in, the error message appears only after the page has reloaded. What I would like to do is show the error message without reloading the page.
I searched on stackoverflow and wordpress reference but couldn't find a solution for my case. Anyone have a suggestion on how I might achieve my goal?
Thanks for any replies, I appreciate any help.
Update 2
I thank the users who helped me with their answers, they were very helpful and I really appreciate it. I literally spent all day on this problem, I finally achieved my goal. The ajax request works and the message is displayed as I wanted. I had to go through a lot of things several times. However I leave the updated code for anyone who needs help.
My custom_login_page.php file
This contains the html structure, the form and the script that executes the ajax requests. Put the file in your active child theme. In my case I called the custom_login_page.php file. For this to be read by wordpress you need to create a new page and select it as a template.
<?php
// Template Name: Custom Login Page
?>
<?php get_header(); ?>
<div class="container_main">
<?php if (is_user_logged_in()) {
?><span>Sei gia loggato</span><?php // If the user is logged in, it shows the message below
} else { // otherwise, if the user is not logged in, it shows the login form
?>
<form id="login" action="login" method="post">
<!-- Message error -->
<p class="status"></p>
<!-- Username -->
<label for="username">Username</label>
<input id="username" type="text" name="username">
<!-- Password -->
<label for="password">Password</label>
<input id="password" type="password" name="password">
<!-- Link Recover -->
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<!-- Submit Button -->
<input class="submit_button" type="submit" value="Login" name="submit">
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
<?php
} ?>
</div>
<?php get_footer(); ?>
<script>
jQuery(document).ready(function($) {
// Perform AJAX login on form submit
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login #username').val(),
'password': $('form#login #password').val(),
'security': $('form#login #security').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
</script>
My functions.php file
In functions.php I put the functions linked to the form and some redirects useful when doing logine logout.
/* Redirect Custom Login Page */
function redirect_custom_login_page() {
wp_redirect(site_url() . "/login");
exit();
}
add_action("wp_logout", "redirect_custom_login_page");
/* Redirect wp-admin & wp-login php */
add_action("init","fn_redirect_wp_admin");
function fn_redirect_wp_admin(){
global $pagenow;
if($pagenow=="wp-login.php" && $_GET['action'] !="logout"){
wp_redirect(site_url()."/login");
exit();
}
}
/* Ajax Form Login */
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( is_wp_error($user_signon) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
Introduction
I will briefly describe how HTML forms work, why your page is reloading and how you can communicate with the server without reloading your page, finally, how you can update your page based on this communication.
How HTML forms work
When you create a form tag and a structure into it, with a button of submit type inside of it, specifying an action (or using the default), then, upon clicking on the button mentioned earlier, your form is submitted. On submitting your form, all elements inside the form, having a name attribute (i.e. name="somename") is picked up and a request will be sent to the specified action (defaulting to the same page), where the form data will be represented as key-value pairs, the keys being the names of your form elements and the values being the values of the elements.
Upon form submit, your browser will send a request to the target of the form. The action of the form (if valid) will pick up the request, handle it and respond to your browser.
When the browser receives this response, it will display it as the content of the page. The users experience this behavior as a page reload. You are bothered with this behavior, as you described in your question and you would prefer to have a less obtrusive, smoother behavior. This is possible with AJAX requests.
AJAX
AJAX requests are well-documented, so, if you are unfamiliar with them - which surely is the case -, then I advise to read the content of the link I have given you above and gain some experience with AJAX. If you get stuck with it, let me know your blocker, but, for now, I will assume that the tutorials clarify the matter for you and in a reasonable amount of time you will successfully learn how to tackle them.
You can also communicate with your server (without page reload) with push notifications or websockets, but since this is a request-response use-case, I strongly advise the use of AJAX. Since AJAX stands for Asynchronous Javascript and XML, the asynchronous part suggests that you are calling an asynchronous function that you do not wait for, that is, your request is being sent to the server and there is an event to handle the server response, upon which you can specify function(s) to be executed, known as the callback(s).
If you are going to have an AJAX request, then you do not necessarily need the form and the submit button is definitely not needed, instead, you could use an input type="button" with a click event handler that will pick up the data and send the request.
How to handle server responses
The simplest way to handle the requests is to just take the (HTML) response and refresh your page content for the regions you want to update (without page reload, of course). But this is not necessarily ideal.
If your structure does not change, but your content does, then it makes much more sense to change your server code to just send the content as JSON (Javascript Object Notation) and update only the content of your page. This approach ensures that your server does not have to send very large, superfluous responses to your browser if it's unnecessary. Instead, it just sends the data, reducing the load of your server's networking and, as a result, making your server more scalable. But this means that your browser will have to update the content itself, which is no longer automatic and you need to code the behavior in a client-side language, such as Javascript.
How you should proceed
Since all this is obviously new to you, I advise you to start with the simplest approach, to have some success that will boost your morale, that is, at first stage, send the request as AJAX, the server should only respond with the inner HTML of the body tag, rather than the whole HTML and you could do a
document.body.innerHTML = response;
in your callback.
The reasonable expectation is that your page is not reloaded by the browser, but it is refreshed. If you reach this stage, then you might decide that it is good-enough for you, or you can decide to improve it, change the server-side to respond to the AJAX request with a JSON and implement some client-side functions to handle the request and refresh the content.
I of course advise the latter, but you of course have the liberty of choice here.
Now, let's understand what a request method is.
A GET request is a request defined by a URL (Unified Resource Locator) and the parameters are passed as GET parameters, that is, inside the URL, after the ? mark, like
https://www.yourpage.com?yourparameter=yourvalue&yoursecondparameter=yoursecondvalue
A POST request is a request where POST parameters can also be defined. In PHP you have neat ways to determine the request type, see this excellent page: Detecting request type in PHP (GET, POST, PUT or DELETE)
Now, when you load the page for the first time, a GET request is being send. Once the form is submitted (via AJAX), you need to specify that you are sending a POST request and then the server will know that it will need to send only the data (rather than the HTML) as a response.
What you want isn't achievable using PHP. As quick explanation, PHP is a server side scriptiong language, which means that only the server can execute your code. So whenever you press Login is has to go to the server (doing a request) and then you'll get back the new HTML from your server.
How to do this
Is quite an investment but if you really want to learn or build this you should look into Javascript AJAX requests. In a nutshell, AJAX is how you communicate with your server without any page reload.
Alternative
You could also try to use some plugins that try to do this. I have no experience with them but here's one that claims to do exactly what you want: https://nl.wordpress.org/plugins/login-with-ajax/
If that one doesn't fit your needs, you can at least continue searching using the term AJAX.
I hope this helps :)
TLDR
With PHP, you can't. Use an AJAX WordPress plugin or build a custom solution using Javascript and AJAX.

Call Modal when PHP form submits

I have a php form that works perfectly. However, when the form submits, I want to display a modal and take the user back to the homepage. I have looked this past two hours online but have found no conclusive evidence. My current code is;
if($sentMail) //output success or failure messages
{
?><script>
$(function() {
$("#thankyouModal").modal();
});
</script>
<?php
}else{
die('Could not send mail!');
}
The form collects data then sends all data as an email. I have tried using only php, jquery, amongst everything else. I simply want a modal that says a brief thank you, your form has submitted whilst re-directing the user to the index.html page. Does anyone have any ideas?
Regards,
Michael
If you want to show the message while the form is posting (whether or not it will succeed), use jquery to swallow the onSubmit() event.
$('form').on('submit', function(e){
e.preventDefault();
$("#thankyouModal").modal();
$('form').submit();
});
If you care about if the email is successful, pass a variable back to the view and conditionally show the modal, but this will be serverside validation (will only know after form submission and re-rendering of the view). Otherwise look into doing an asynchronous post with $.ajax

IsPostBack is always True when we Submit the form using Javascript

I am using below code in .js file using asp.net from page1.aspx page
Form1.action = "testpage.aspx";
Form1.submit();
When the form is submitted the IsPostBack is always True when it's redirected to "textpage.aspx"
Is there any things which i am missing here?
You are submitting a form. That's what postback exactly is.
Redirect would be e.g.:
window.location.href = 'testpage.aspx';
EDIT:
It's not clear from your post whether the testpage.aspx is the same page as the one containing the submitted form. If you want to avoid postback then you'll have to build a querystring, attach it to the URL and perform a redirect. Then you can access the parameters using Request.Params.

javascript form.submit() losing querystring created by GA _linkByPost

We have a booking form that POSTs to the parent company website. Because this is a different domain we need to implement the GA _linkByPost to pass the GA tracking cookie info across domains.
As the booking form is in a .NET user control it does a postback. On postback we validate, wrap up the booking info, and write a form back to the client with hidden elements required by the target booking engine and add line of javascript to submit the form.
Below is the javascript function I'm using to submit the form:
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
thisForm.submit();
}
And the relevant form info:
<form id="PostForm" name="PostForm" action="ClientBookingEngineUrl" method="post" >
booking form info in here
</form>
The result is that we fill in the form, hit submit which does a round trip to the server generates a new form and POSTs the info. This all works fine apart from the URL loses the GA cookie info from the query string. If I comment out the form submit line and look at source code I can see the GA cookie info on the querystring - but when posting, I do not see the querystring (using Fiddler).
To clarify:
The above technique works and does what we want with regards to POSTing form data to the booking engine and taking the user there.
If the submit line is commented out you can see the form with the modified action that has the GA stuff appended (using Firebug).
If the form is submitted with the submit line, the querystring info is removed (confirmed by Fiddler).
Am I missing something obvious? Are there some gotchas regarding JS submit, form POSTs and querystrings? Or is there a simple trick I'm missing?
Cheers
EDIT 1
An oddity has occured.
If I alert the form action before and after the _gaqPush then we can see the URL in its before and after state and it's as expected.
alert('1 form action = ' + thisForm.action);
_gaq.push(['_linkByPost', thisForm]);
alert('2 form action = ' + thisForm.action);
Alert 1 shows the pre-modified action and alert 2 shows the action with the GA info.
With the alerts in place it submits WITH the GA info in the query string.
If I comment out the alerts the GA info is NOT in the query string...
I'm starting to think the form or something is not ready so I'm trying it with JQuery's document ready.
EDIT 2
Wrapping the method call in document ready doesn't help. I'm confused as to why action URL is correct AFTER displaying it in an alert but incorrect if I don't alert it.
Answering this for posterity.
The problem is the _qaq (Google Analytics Queue) hasn't had time to modify the form before the call to submit() the form.
The solution is to push a function onto the _gaq object that submits the form so it will happen directly after the form modification is done.
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
_gaq.push(function() { thisForm.submit(); });
}
I tried a simple HTML page that calls _gaqPush and submits immediately. This also fails.
Adding a 1000ms delay works (for the most part) so I suspect the alerts just gave the GA script time to modify the form.
I'm closing/accepting this as it seems down to submitting the form too quickly after the GA call.

Have jQuery fire Ajax request when when back button is pressed

I have a page with 80+ dynamically generated input boxes, when the user submits the form to another .php page and one of the inputs contains a value that is not numeric, it will send them back to the inputs page using: <?php header("Location: javascript:history.back()"); ?>, at the same time it registers the error in a session variable. The reason why I'm using javascript:history.back(), is because it stores the values that were in the form, even when you press the back button. But because it is caching the page I can't output the error in the same .php script, so I added a an element and some Ajax code. The Ajax code retrieves another file called error.php, this contains:
<?php
header("Cache-Control: no-cache");
session_start();
if(isset($_SESSION['error']))
{
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
This is retrieved when the page is loaded on it own, but not when history.back() is used, it looks like the following isn't firing:
<script type="text/JavaScript">
$(document).ready(function(){
$("#error p").load("error.php");
});
</script>
Any ideas?
Thanks,
Justin
Using header("Location: javascript:history.back()") is generally ill-advised.
Use an absolute path i.e.
header('Location: /forms/input.php');
You could avoid submitting the form entirely and send the data via an AJAX call - the server could validate the data and send back either "success" or a list of validation errors.
If success, move on to the next URL (possibly specified alongside the success message)
If failed, modify the current page to indicate what the problems were. This avoids you having to re-create the whole form (as you never leave the page) but also allows for reliable server-side validation

Categories

Resources