I created a google sign in using Google OAuth 2.0, I configure it using Xamp and php to build the database, I built it outside my project, now I want to include the google sign in button in my project but I kept getting errors. From my localhost, I want to add it to my file first and see how it would look in my page before uploading it. Below is my index.php file
<?php
require_once('config.php');
require_once('core/controller.Class.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="uft-8">
<meta name="viewport" content="width=device-width, inital-scale=1">
<title>Login with Google</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 100px">
<?php
if(isset($_COOKIE["id"]) && isset($_COOKIE["sess"])){
$Controller = new Controller;
if($Controller -> checkUserStatus($_COOKIE["id"], $_COOKIE["sess"])){
echo $Controller -> printData(intval($_COOKIE["id"]));
echo 'Logout';
}else{
echo "Error!";
}
}else{
?>
<img src="img/20210908_214559.jpg" alt="Logo"
style="display: table; margin: 0 auto; max-width: 150px;">
<form action="" method=:POST>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label>
<input type="email" class="form-control" id="exampleInputEmail1"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1"
placeholder="Enter password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
<button onClick="window.location = '<?php echo $login_url;?>'" type="button" class="btn btn-danger">Login with Google</button>
</div>
</form>
<?php } ?>
</body>
</html>
It looks like you're expecting to collect the google username and password and then pass that to the google auth engine? That's not the way I've implemented the solution.
Google provide instructions for integrating their sign-in service.
I recommend following those instructions. This will require the following files:
A login page which contains the google sign-in button. You could conceivably add this to any of your existing pages. The relevant code is:
<div class="g-signin2" data-longtitle="true" data-onsuccess="onSignIn"></div>
A javascript file which contains the onSignIn function and a signOut function if you want one. This file handles the redirect to a successful logged in page and also passes the attributes you want to collect from the user's Google account. I'm using XMLHttpRequest, but you could use POST if you wish. This page contains the page that the user will be directed to upon successful login, set in xhr.onreadystatechange = function() {}:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id_token = googleUser.getAuthResponse().id_token;
// console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'includes/oauth.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
window.location = "../loggedin.php"; //Redirect to loggedin page on completion of oauth.php. Determine if new user or existing user and process accordingly
}
xhr.send('idtoken=' + id_token + '&googleId=' + profile.getId() + '&name=' + profile.getName() + '&imageURL=' + profile.getImageUrl() + '&email=' + profile.getEmail());
}
function signOut() {
gapi.load('auth2', function() {
gapi.auth2.init().then(function(){
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
document.location.href = 'includes/logout.php';
});
});
});
}
A file to handle the authentication (referred to as includes/oauth.php in my javascript file above). Note the settings for $leeway - this caused me a lot of grief figuring out that the clock on my server was slower than the Google auth server's clock!):
require_once '../vendor/autoload.php';
$jwt = new \Firebase\JWT\JWT; //Allow for discrepancies between server and auth times
$jwt::$leeway = 60;
$CLIENT_ID = "ENTER_YOUR_CLIENT_ID_HERE";
$client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$client->setRedirectUri("http://localhost/includes/oauth.php");
$client->addScope("email");
$client->addScope("profile");
if (isset($_POST['idtoken'])){
$id_token = $_POST['idtoken'];
$attempt = 0;
do {
try {
$payload = $client->verifyIdToken($id_token);
$retry = false;
} catch (Firebase\JWT\BeforeValidException $e) {
error_log("JWT server time mismatch. Retry attempt: " . strval($attempt) . "Error: " . $e, 0);
$attempt++;
$retry = $attempt < 3;
}
} while ($retry);
if ($payload) {
$userid = $payload['sub'];
...
YOUR VALIDATION, SESSION SETTING, ETC. CODE HERE
...
} else {
// Invalid ID token
print("Invalid ID token");
}
} else { //Attempt to access this page directly, redirect to Google login page
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
The page that will displayed upon successful login. I used an interstitial page here because the authenticated user could be new to my site and need to create a profile, or could be an existing user and want to go about their activities. I look to verify whether a SESSION has been started and whether this includes a successful authentication.
I'd like to use a style sheet from Wikipedia. For that, I'm fetching this style sheet. When trying to
pass the url fetched using ajax to the head of my html document, the url retrieved behave unexpectedly.
First, I simply try to use the url as it is fetched :
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
Here is the full code :
<!DOCTYPE html>
<!-- testing purpose file, used for trying to print a correctly formatted wikipedia page -->
<html>
<head>
<meta charset="utf-8"/>
<title> game setup </title> <!-- Titre de l'onglet -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
</head>
<body style="background-color:white;">
<div class='container'>
<h1 id="title">MiniWiki</h1>
<div id="content"></div>
</div>
<script>
function loadPage() {
"use strict";
var url, doc;
console.log("IN LOADPAGE")
url = 'https://en.wikipedia.org:443/api/rest_v1/page/html/' + 'Ancient_Egypt';
// fetch the article data
return $.ajax(url).then(function (data) {
doc = (new DOMParser()).parseFromString(data, 'text/html');
// Use mediawiki content stylesheet
var stylesheetElem = doc.querySelector('head link[rel="stylesheet"]');
console.log("SHOW stylesheetElem");
console.log(stylesheetElem);
$('head').append(stylesheetElem);
//Update content
var contentElem = document.getElementById('content');
var $content = $(contentElem).empty();
Array.from(doc.body.attributes).forEach(function (attr) {
$content.attr(attr.name, attr.value);
});
$content.append(Array.from(doc.body.children));
});
}
loadPage();
</script>
In this case, the url fetched is
<link rel="stylesheet" href="/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
I was expecting that it would also include https://en.wikipedia.org/ at the beginning of the url like this :
<link rel="stylesheet" href="https://en.wikipedia.org/w/load.php?lang=en&modulening.con...%7Cext.cite.styles&only=styles&skin=vector">
Since it dit not, I thought I could add it myself by simply adding this line of code just
before the line
console.log("SHOW stylesheetElem");
stylesheetElem.href = "http://en.wikipedia.org" + stylesheetElem.href
when printing the stylesheetElem url, this unexpectedly returns the following url :
http://en.wikipedia.orgfile//en.wikipedia.org/w/load.php?...kin=vector
What happened here ? Why didn't I get the following correct url ?
http://en.wikipedia.org/w/load.php?...kin=vector
The dots (...) indicate that the developer tools have left out part of the url. You copy that instead of the real url, which you can see when you do "View Page Source":
/w/load.php?lang=en&modules=ext.uls.interlanguage%7Cext.visualEditor.desktopArticleTarget.noscript%7Cext.wikimediaBadges%7Cskins.vector.styles.legacy&only=styles&skin=vector
I want to create common header and footer pages that are included on several html pages.
I'd like to use javascript. Is there a way to do this using only html and JavaScript?
I want to load a header and footer page within another html page.
You can accomplish this with jquery.
Place this code in index.html
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
and put this code in header.html and footer.html, at the same location as index.html
click here for google
Now, when you visit index.html, you should be able to click the link tags.
I add common parts as header and footer using Server Side Includes. No HTML and no JavaScript is needed. Instead, the webserver automatically adds the included code before doing anything else.
Just add the following line where you want to include your file:
<!--#include file="include_head.html" -->
Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?
If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php
<?php include('header.php'); ?>
Do the same in the footer of each page to include the content from your footer.php file
<?php include('footer.php'); ?>
No JavaScript / Jquery or additional included files required.
NB You could also convert your .html files to .php files using the following in your .htaccess file
# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
You could also put: (load_essentials.js:)
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
I tried this:
Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.
I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.
JS Function
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
Get the content
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
index.html
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
views/header.html
<!-- This element will replace #header -->
<header id="new-header"></header>
The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page
The question asks about using only HTML and JavaScript. The problem is that a second request to the server using JavaScript or even jQuery (requesting the extra header.html "later") is:
Slow!
So, this is unacceptable in a production environment. The way to go is to include only one .js file and serve your HTML template using only this .js file. So, in your HTML you can have:
<script defer src="header.js"></script>
<header id="app-header"></header>
And then, in your header.js put your template. Use backticks for this HTML string:
let appHeader = `
<nav>
/*navigation or other html content here*/
</nav>
`;
document.getElementById("app-header").innerHTML = appHeader;
This has also the benefit, that you can change the content of your template dynamically if you need! (If you want your code clean, my recommendation is not to include any other code in this header.js file.)
Explanation about speed
In the HTTP/2 world, the web server "undestands" what additional files (.css, .js, etc) should be sent along with a specific .html, and sends them altogether in the initial response. But, if in your "original" .html you do not have this header.html file imported (because you intend to call it later with a script), it won't be sent initially. So, when your JavaScript/jQuery requests it (this will happen much later, when HTML and your JavaScript will get "interpreted"), your browser will send a second request to the server, wait for the answer, and then do its stuff... That's why this is slow. You can validate this, using any browser's developer tools, watching the header.html coming much later.
So, as a general advice (there are a lot of exceptions of course), import all your additional files in your original .html (or php) file if you care about speed. Use defer if needed. Do not import any files later using JavaScript.
I think, answers to this question are too old... currently some desktop and mobile browsers support HTML Templates for doing this.
I've built a little example:
Tested OK in Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 and Adblocker Browser 54.0
Tested KO in Safari 10.1, Firefox 56.0, Edge 38.14 and IE 11
More compatibility info in canisue.com
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
Your can get more examples in this HTML5 Rocks post
Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.
I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)
So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.
I hope this helps!
It is also possible to load scripts and links into the header.
I'll be adding it one of the examples above...
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
For a quick setup with plain javascript and because not answered yet, you could also use a .js file to store your redundant pieces (templates) of HTML inside a variable and insert it through innerHTML.
backticks are here the make it easy part this answer is about.
(you will also want to follow the link on that backticks SO Q/A if you read & test that answer).
example for a navbar that remains the same on each page :
<nav role="navigation">
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
</nav>
You can keep inside your HTMl :
<nav role="navigation"></nav>
and set inside nav.js file the content of <nav> as a variable in between backticks:
const nav= `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
` ;
Now you have a small file from which you can retrieve a variable containing HTML. It looks very similar to include.php and can easily be updated without messing it up (what's inside the backticks).
You can now link that file like any other javascript file and innerHTML the var nav inside <nav role="navigation"></nav> via
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
If you add or remove pages, you only have to update once nav.js
basic HTML page can be :
// code standing inside nav.js for easy edit
const nav = `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
`;
nav[role="navigation"] {
display: flex;
justify-content: space-around;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<!-- update title if not home page -->
<meta name="description" content=" HTML5 ">
<meta name="author" content="MasterOfMyComputer">
<script src="nav.js"></script>
<!-- load an html template through a variable -->
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<nav role="navigation">
<!-- it will be loaded here -->
</nav>
<h1>Home</h1>
<!-- update h1 if not home page -->
<script>
// this part can also be part of nav.js
window.addEventListener('DOMContentLoaded', () => {
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
});
</script>
</body>
</html>
This quick example works & can be copy/paste then edited to change variable names and variable HTML content.
another approach made available since this question was first asked is to use reactrb-express (see http://reactrb.org) This will let you script in ruby on the client side, replacing your html code with react components written in ruby.
Use ajax
main.js
fetch("./includes/header.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./includes/footer.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Liks</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header></header>
<main></main>
<footer></footer>
<script src="/js/main.js"></script>
</body>
</html>
You can use object tag of HTML with out use of JavaScript.
<object data="header.html" type="text/html" height="auto"></object>
Credits : W3 Schools How to Include HTML
Save the HTML you want to include in an .html file:
Content.html
Google Maps<br>
Animated Buttons<br>
Modal Boxes<br>
Animations<br>
Progress Bars<br>
Hover Dropdowns<br>
Click Dropdowns<br>
Responsive Tables<br>
Include the HTML
Including HTML is done by using a w3-include-html attribute:
Example
<div w3-include-html="content.html"></div>
Add the JavaScript
HTML includes are done by JavaScript.
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
Call includeHTML() at the bottom of the page:
Example
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>
I have two seperate perl documents:
mailcheck.pl
loggingpage.pl
Mailcheck prints out a form in html where the user can put in her/his email and checks if the input is a valid email address. Then it calls upon the loggingpage.pl which saves the email in a logfile and gives out information to the user if the email address was successfully stored.
These are the two documents:
mailcheck.pl:
#!/usr/bin/perl
use strict;
use warnings;
print "Content-type: text/html\n\n";
print <<HTML;
<html>
<head>
<title>Mailcheck</title>
</head>
<body>
<form name="ec" action ="./loggingfiles.pl" method="get">
Email: <input type="text" name="email"> <br>
<input type="button" value="Pruefen" onclick="javascript:emailcheck();">
</form>
<script language="javascript" type="text/javascript">
function emailcheck()
{
var emailoutline = /^[a-z0-9._%+-]+\#[a-z0-9.-]+\.[a-z]{2,4}\$\/\;
var x = document.ec.email.value;
if (emailoutline.test(x))
{
open("./loggingpage.pl);
}
else
{
alert("Dies ist keine richtige eMailadresse!");
}
}
</script>
</body>
</html>
HTML
exit;
loggingpage.pl:
#!/usr/bin/perl
use strict;
use warnings;
use CGI qw(:standart);
#reads the input of the form called "email"
$emailinput = param('email');
#saves the email in the logfile
open(my $ml, ">", "./../logs/maillog.txt") or die "Fehlermeldung";
print $ml scalar(localtime()), " Email: ", $emailinput;
close($ml);
#gives out information about the saving process
if (...) #saving the email in the logfile succeeded
{
print <<HTML;
<html>
<head></head>
<body>
<script language="javascript" type="text/javascript">
alert("Your input has been saved under the following email: " + $emailinput);
</script>
</body>
</html>
HTML
exit;
}
else #gives out warning if information was not stored right
{
print <<HTML;
<html>
<head></head>
<body>
<script language="javascript" type="text/javascript">
alert("Error while saving your input.");
</script>
</body>
</html>
HTML
exit;
}
(I know that the <<HTML (..) HTML blocks cannot have spaces in front of them - in my actual document I have edited the block the right way)
My questions are now:
a. How can I write the if-conditions when I want to see if the email got saved in the logfile?
b. I am not quite sure if the part $emailinput = param('email'); works since I was not able to try it, is it the right way to get the input of the form in mailcheck.pl or do I need to write the code differently?
For you information:
- mailcheck.pl works correctly.
- the saving of the email in the logfile also works fine (i tried it through defining a variable as an email and saving that into the logfile together with the current date...)
So I have solved question a) like this (it seems to be working):
open(my $ml, ">", "./../logs/maillog.txt") or die "Saving Error";
print $ml scalar(localtime()), " Email: ", $emailinput;
close($ml);
#print "\nYour eMail was successfully logged!", $emailinput, "\n\n";
print "Content-type: text/html\n\n";
print <<HTML;
<html>
<head>
<title>Mailcheck2</title>
</head>
<body>
<p>Es wurde die folgende eMail erfolgreich gelogged:</p>
</body>
</html>
HTML
exit;
Now I only need help with question b).
After performing the validation, submit the form using:
document.ec.submit(); // 'ec' is the name of your form
This will send the form data to the page defined in the action attribute of your form.
Better yet, use the onsubmit attribute of the form tag to perform the validation:
<form name="ec" action ="./loggingfiles.pl" method="get" onsubmit="return emailcheck()">
Then modify the validation method to return false on failure:
function emailcheck()
{
var emailoutline = /^[a-z0-9._%+-]+\#[a-z0-9.-]+\.[a-z]{2,4}\$\/\;
var x = document.ec.email.value;
if (!emailoutline.test(x))
{
alert("Dies ist keine richtige eMailadresse!");
return false;
}
}
Do not rely on JavaScript in this way. JS is useful an additional sanity check for your form, but it should not be the only nor the primary means of validating your data.
Instead, put all your data into a single page, and for initial development, remove any JS. Make your form a POST request, and detect when the form is posted to determine if you need to do the validation. You'll need to use your JS validation regex in your perl instead, although eventually you should upgrade to Email::Valid.
After your form and post is working without JavaScript, you can add an onSubmit method if you want to do some clientside verification to duplicate what you've done in perl.
I'm a beginner in jQuery area and I have simple question like this :
I want to load (AJAX) MySQL result in array, let's say :
$row[0] = first name
$row[1] = last name
$row[2] = phone number
I have no problem with PHP part, but I have difficulties to display each of that array content on different id. because syntax I found loads everything processed by PHP :
<script type="text/javascript">
$(document).ready(function(){
$('#mysql-result').load('ajax.php');
});
</script>
how to get 'First Name', 'Last Name' and 'Phone Number' from PHP with only one time load and still I can put the result in different . thank you.
UPDATE
I give you real example about what I need. Here's my HTML file named ajax.html :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax Trial</title>
</head>
<body>
<div id = "fistname"><!-- ajax result goes here --></div>
<div id = "lastname"><!-- ajax result goes here --></div>
<div id = "phonenumber"><!-- ajax result goes here --></div>
</body>
</html>
and here's my PHP file, named ajax.php :
<?php
require_once 'config-min.php';
$con = mysql_connect($DbServer,$DbUser,$DbPassword);
mysql_select_db($DbName, $con);
$result = mysql_query("SELECT FirstName, LastName, PhoneNumber FROM User WHERE ID = '201' LIMIT 1");
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
mysql_close($con);
?>
now, my question still same... how to get this PHP result (3 echos), load once, then displayed in those 3 different divs
I too wanted to do something like you wish to.And I did the following code and It worked. Hope this helps you too.
<script type="text/javascript" src="/jquery.js"></script>
<script>
$(document).ready(function(){
$("#form_plat").submit(function(e){
var str = $(this).serialize();
row[0]=$('#First_name').val();
row[1]=$('#last_name').val();
row[2]=$('#phonenumber').val();
$.ajax({
type: "POST",
url : 'Insert_Into.pl', //if you wish to store in database
data : {'firstname_name':row[0],'last_name': row[1],'phonenumber':row[2]},
beforeSend: function() {
console.log("hey i am here");
},
success: function(){
$('#note').html('Thank you for your submission!');
$('#note').hide();
$("#fields").fadeOut('slow');
}
});
return false;
});
});
</script>);
Have you tried adding to your php code:
echo $firstname.' '.$lastname.' '.$phonenumber;