Display a 'Page Loading' message between pages - javascript

I have a form on my site that when submitted takes the user from Page1.html to Page2.html.
I would like to display a message between the form being submitted and "Page2 loading".
Can someone provide me with an example of this?

If your form submit data via ajax then you could try something this:
$('form#myform').submit(function(e) {
e.preventDefault();
$('#message').html('Sending....'); // #message may be a div that contains msg
$ajax({
url: 'url_to_script',
data: 'your_data',
success: function(res) {
// when submit data successfully then page reload
window.location = 'page2.html'
}
});
});

What you're looking to do can't be done by standard form submission.
You'll want to submit the form using ajax, and display a "Please wait" message while you are waiting for a response. Once the response is received and validated to be OK, you can then redirect the user to the page you now call page2.
The easiest way to submit a form via ajax is to serialize it to a string and pass it along. Then, you'll need a page to process the received data, and return an OK or and ERR.
The JS will then need to decipher next action.
This is not tested, but copied and pasted from various working projects.
You'll need to download and include the json2.js project.
page1
<div id='pleaseWait'>Please Wait...</div>
<form id="theForm" onsubmit="doAjaxSubmit();">
<input type='text' name='age' id='age' />
<input type='submit' value='submit'>
</form>
<script type="text/javascript">
function doAjaxSubmit(){
var j = JSON.stringify($('#theForm').serializeObject());
$('#pleaseWait').slideDown('fast');
$.post('processor.php?j=' + encodeURIComponent(j), function(obj){
if(obj.status=='OK'){
window.location='page2.php';
}else{
$('#pleaseWait').slideUp('fast');
alert('Error: ' + obj.msg);
}
}, 'json');
return(false);
}
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
processor.php
<?php
$j=json_decode($_POST['j'], true);
if ((int)$j['age']<=0 || (int)$j['age']>120){
$result = array('status'=>'ERR', 'msg'=>'Please Enter Age');
}else{
//Do stuff with the data. Calculate, write to database, etc.
$result = array('status'=>'OK');
}
die(json_encode($result));
?>
This is essentially very similar to the answer below (by #thecodeparadox), but my example shows how to pass the entire for without having to manually construct your data object, shows how to validate on the PHP side as well as return the appropriate JSON data to either redirect the user, or to display an error, and uses animations to display the message.

Related

I am Having Problems Updating My MySQL table value From my Modal form Sing PHP

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}

How do I redirect the user with PHP after using jQuery's preventDefault() on a form?

I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();

How do I resend data from previous url after reCAPTCHA passed in the same page?

Data sent from this
www.example.com/modules/liaise/index.php?form_id=xxx
In normal condition, after submit, the page redirects to
www.example.com/modules/liaise/index.php
and sends mail.
Wantedly, I placed the reCAPTCHA in the same file (index.php).
Google captcha :
require_once "recaptchalib.php";
// your secret key
$secret = "secret key";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
//send mail
} else {
echo '
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<div id="html_element"></div>
<script>
var onloadCallback = function() {
grecaptcha.render("html_element", {
"sitekey" : "sitekey",
"callback" : correctCaptcha
});
};
var correctCaptcha = function(response) {
location.reload();
};
</script>';
}
Whenever I pass reCAPTCHA and page reloads, reCAPTCHA shows again.
I know data from previous page www.example.com/modules/liaise/index.php?form_id=xxx is still there by using
foreach($_POST as $key=>$value)
{
echo "$key=$value";
}
Is there any way by which I can resend data from previous url after reCAPTCHA is passed in the same page?
I am newbie in coding. Please be specific.
Thank you so much!
If your talking about re-sending your data as mail you can use something like this:
if (isset($_POST['form-input'])) {
// Send mail
}
and every time you reload the page and the Post data is not null or blank, it will run that code.
If you are wanting the reCAPTCHA to reload as success, I would say that's defeats the security of reCAPTCHA
Also I see that you have a typo esle should be else.

How to check if USERNAME already exists in PHP/MYSQL?

I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.

Redirect page after Submitting Form

I have a form, which can either be submitted via AJAX or usual way, working with the submit button. The Ajax part is here:
parentForm.onsubmit = function(e) { // e represents trigering event
if(srteValidateMode()){ // works only in WYSIWYG mode
var outputString = srteEditArea.innerHTML; // first we prepare the text output data
outputString = outputString
.replace(/<(\/?)strong>/gi, '<$1b>') // unify output tags for all browsers -> B I P (instead of strong em div)
.replace(/<(\/?)em>/gi, '<$1i>')
.replace(/<(\/?)br>/gi, '<p>')
.replace(/<(\/?)div/gi, '<$1p');
document.getElementById('simpleRTEoutput').value=outputString; // pass output string to hidden form field
if (srteAjaxSubmit) { // ajax version - filling FormData
e.preventDefault(); // canceling the submit function - we will call it with Ajax
var srteFormData = new FormData(e.target); // getting form data from submitted form
var ajaxRequest = new XMLHttpRequest(); // now going to invoke AJAX
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText); // return message and display as info window
}
}
ajaxRequest.open("POST", e.target.action); // getting target script from form action
ajaxRequest.send(srteFormData); // send FormData
}
else { // Standard submit
return true; // true = standard submit will proceed (works ok)
}
}
else {return false;} // on false return form will not be submitted
};
It works fine. Now I want to add redirection functionality - clicking on another (non submit) button with some onclick function to SAVE (do the predefined submit) AND redirect. I have such Idea (not tested), but not sure it this might work especially in the AJAX part.
function srteSubmitForm(redirectTo) {
if (srteAjaxSubmit) { // redirect when submitted via Ajax Call
parentForm.submit(); // save form data
window.location.href = redirectTo; // change location - does it wait for previous function ?
}
else {
parentForm.action = parentForm.action + '?redirect=' + redirectTo; // rest handled by target PHP
parentForm.submit();
}
}
Button in HTML then would look like:
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=A\")" value="Redirect A">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=B\")" value="Redirect B">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=C\")" value="Redirect C">
I am not sure, if I need to wait for the AJAX to be finished somehow before redirect ? Or any other way how redirect after the submit?
no jQuery solutions, please.
Thanks, Jan
Why not add a 'callback' parameter to your submit method that gets called when the call completes.
parentForm.submit(function(status){
//The call completed, you can display a confirm message 'Form submitted,
//now redirecting' (because it's not nice to redirect without warning ;)
window.location.href = redirectTo;
});
And in your submit:
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText);
if(callback instanceof Function) callback(ajaxRequest.responseText);
}
}

Categories