I have an email sign-up form on my site that I recently added validation to.
Now, the form will not send or provide an error message. When I check the inspector I see the following error:
TypeError: null is not an object (evaluating 'document.getElementById(update[0]).innerHTML = update[1]')
This is my contact.php file
<?php
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(!isset($_GET['action']))
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = trim($_GET['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
mail($to,$subject,$message,"From: ".$email."");
echo 'contactarea|<div id="thanks">Thank you. We promise you won’t regret it.</div>';
else {
echo("$email is not a valid email address");
}
?>
This is my form in HTML
<div id="contactarea">
<span style="font-family: 'Old Standard TT', serif;">Newsletter</span>
<form id="contactform" name="contactform" >
<input class ="email" type="text" name="email" id="inputbox" value="E-Mail"
onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
<input type="submit" value="Submit" name="send" onclick="sendemail(); return false; " class="signup" >
</form>
</div>
and this is my javascript
<script language="javascript">
function createRequestObject() {
var ro;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} else {
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled = true;
http.open('get', 'contact.php?email=' + email + '&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
setTimeout(function() {
jQuery(document).find("#thanks").fadeOut();
}, 3000);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
var update = new Array();
if (response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}
</script>
Any insight would be greatly appreciated.
I think this is what you are looking for:
document.contactform.send.disabled=false;
add another div in html page with id = "msg"
replace
document.getElementById(update[0]).innerHTML = update[1];
with
you can add conditions here
depending on what you want to display upload[0] or upload[1]
document.getElementById('msg').innerHTML = update[0]+update[1];
and in contact.php
there is '}' missing before else.
Multiple errors, client and server-side.
Changes to javascript. Your form data wasn't being sent in the php call.
I have made changes to your call type get/post and used new FormData(). If you want to add more to your call formdata.append("ParamName", Value/Variable); and use $something=$_POST['ParamName']; to get the post in PHP.
var formdata = new FormData();
formdata.append("email", email);
formdata.append("action", "send");
http.open('POST', 'contact.php');
http.onreadystatechange = handleResponse;
http.send(formdata);
Changes to PHP. You missed the opening/closing of the if statements.
The way you have your javascript setup, you split the php reply (|) if the email posted wasn't valid you would cause a JS error because you didn't have the divID and bar(|) in your echo.
$to = "hello#interzonestudio.com";
$subject_prefix = "";
if(isset($_POST['action'])){ // ***** Missing ({)
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_POST['email']); //The senders subject
$email = trim($_POST['email']); //The senders email address
if (!filter_var($email, FILTER_VALIDATE_EMAIL)===false) {
mail($to,$subject,$message,"From: ".$email."");
// **** Div ID Missing with Bar (contactarea|)
echo 'contactarea|<div id="thanks">Thank you. We promise you won\'t regret it.</div>';
// **** Else missing (})
}else {
echo("contactarea|$email is not a valid email address");
}
}// **** Close if issset (})
I hope I have covered all your problems in this answer.
If you don't understand anything please leave a comment below, i will update the answer to help you understand anything within this answer. I would rather you take this source code understand it, not just a copy paste. You won't learn from copy/paste.
Tip: Clean your php string before putting them into mail().
I hope this helps. Happy coding!
Related
I wanted to ask how can i get the values of the Javascript Input and store it into a php value so i can post this data into Sqlite3. Im receiving user inputs from the Javascript Prompts. Is there another way to accomplish this also. Any help would be greatly appreciated.
function myFunc(){
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
if(code==""||code==null||code!="1234"){
//Handle Error
window.location.href="error.html";
}
}
document.onreadystatechange = () => {
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
myFunc();
}
});
}
Using jquery you can use the $.post method:
function myFunc() {
var code = prompt("Please enter authorized code twice for security purposes: ");
var email = prompt("Please enter email twice to continue: ");
var url = "phpToGetInputs.php";
var data = {
code: code,
email: email
}
$.post(url, data); // "send the data to the php file specified in url"
// code...
}
document.onreadystatechange = () => {
// code...
}
Then, in your PHP file (that you specified as the url)
phpToGetInputs.php:
<?php
if(isset($_POST['email'])) {
$email = $_POST['email']; // get the email input (posted in data variable)
$code = $_POST['code']; // get the code input (posted in data variable)
// do code that requires email and code inputs
}
?>
Use a jQuery post request to send the variable from javascript to php.
$.post([url], { "data" : text });
Look at this website for more information: https://api.jquery.com/jquery.post/
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
I have a really simple login form that I want to check if the credentials are right (so I don't have to reload a page if the credentials are wrong) before submitting the form.
The problem I'm running into is the response from the AJAX call. When the program decides that the user has supplied the correct credentials, this code works like a charm. In addition, when performing the two checks prior to the AJAX call (whether the user filled in the password input field or if the username is valid), the code works perfectly. It returns an error message and returns the false boolean value, preventing the form from submitting. But, when the response from the server comes back and it is found that the credentials are not correct, the error message displays, but the page also reloads (therein displaying an additional error message). Why is the form still submitting, even though I'm returning false? I've checked the JavaScript console, there are no errors. I've also tried inverting the if statement, checking if ajax.responseText === "true", to the same result. I've tried adding a return false beneath the ajax.onreadystatechange call, but that just prevents the form from submitting at all (regardless of the response from the server).
Here is the form code:
<form method="POST" action="/afton/" onsubmit="return checkForm()">
<label for="username">Username:</label>
<input type='text' id='username' name='username' placeholder='Enter username...' required>
<label for="password">Password:</label>
<input type='password' id='password' name='password' placeholder='Enter password...' required>
<div class="form-buttons">
<button type='submit' name='action' id="loginButton" value='login'>Login</button>
<button type='button' id='register'>Register</button>
</div>
</form>
Here is the js function:
// Function that checks whether the user supplied correct credentials
function checkForm() {
// Get the password provided and the server message div on the page
const messageBox = document.getElementById("server-message");
const password = document.getElementById("password").value;
// If password is blank, return error message and return false
if (password === "") {
messageBox.innerHTML = "<p class='badMessage'>Please fill in the password!</p>"
return false;
}
// If the username input tag doesn't contain the 'goodBorder' class received upon validation of username, return error and false
if (!usernameInput.classList.contains("goodBorder")) {
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
return false;
}
// AJAX call that posts the info via JSON to check
const ajax = new XMLHttpRequest();
ajax.open("POST", "index.php?action=ajaxLogCheck", true);
ajax.setRequestHeader("Content-type", "application/json");
ajax.send(JSON.stringify({"username":usernameInput.value, "password":password}));
// Handles the AJAX response
ajax.onreadystatechange = function () {
if (ajax.readyState === 4 && ajax.status === 200) {
if (ajax.responseText !== "true") {
messageBox.innerHTML = ajax.responseText;
return false;
}
return true
}
}
}
And here is the PHP code that handles the AJAX:
// Get posted JSON encoded data
$data = json_decode(trim(file_get_contents("php://input")), true);
// Filter and sanitize the supplied username and password
$username = filter_var($data['username'], FILTER_SANITIZE_STRING);
$password = filter_var($data['password'], FILTER_SANITIZE_STRING);
// Get user data by the username and check the username against the password
$userData = getClient($username);
$hashCheck = password_verify($password, $userData['password']);
// Check response from the hashCheck and return the result
if ($hashCheck) {
echo "true";
exit;
}
logAtt($username, $_SERVER['REMOTE_ADDR'], false, getBrowser($_SERVER['HTTP_USER_AGENT']));
sleep(0.5);
$rands = array("Sorry, the username and/or password doesn't match our database. Please try again.", "Sorry, we don't recognize those login credentials. Please try again.", "Sorry, that login was incorrect. Please try again.", "Incorrect, please try again");
$randResult = array_rand(array_flip($rands));
echo "<p class='badMessage'>$randResult</p>";
// Just the point in AJAX function where you were returning True or
// False...Just Assign RESULT = 0 for False and
// RESULT = 1 for True
// .....SUppose You password matches so you were returning True..
// Dont do that...Instead Just Assign RESULT = 0 in that place and
// and out of the ajax Block paste this 'return Boolean(RESULT)'
// if RESULT = 0 then it will return False else it will return True
// Function that checks whether the user supplied correct credentials
function checkForm()
{
// Initialize a Variable Here Say RESULT
var RESULT = 0;
if (password === "")
{
RESULT = 0;
}
else if (!usernameInput.classList.contains("goodBorder"))
{
messageBox.innerHTML = "<p class='badMessage'>Please provide a valid username!</p>"
RESULT = 0;
}
// After this Put the ajax function and if you want to return False
// then simply assign RESULT = 0 instead of 'return false' else assign
// RESULT = 1 instead of 'return true'
return Booelan(RESULT);
// THis line is main Part this is returned by checkForm() function
}
// If I am still not clear, then I'll be happy to explain it on Google Meet.! :)
I am finishing up a form for user registration, and I wanted to know how to clear messages generated dynamically by AJAX, when the user clears the input (backspace). For example, let's say they enter a valid input, but then clear it with all backspaces - my code currently shows the valid input message, but I want that to switch to an empty string / no message when that happens:
if ($nameCheckCount < 1) {
if (preg_match("/^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/", $email)) {
echo 'This email is available.';
exit();
} else {
echo 'You entered an email with an invalid format.';
exit();
}
} else {
echo 'This email is taken.';
exit();
}
Is there some way I can change the above code I currently have to clear the message if there is no input after a backspace?
Secondly, once all the input is validated (I have one main HTML file for the form, and then three PHP files to check username, password, and email validity through the use of MySQL, or in the case of the passwords, a simple string match), can I set some sort of flag to then allow the user to submit? For example, the code that checks the email is as such:
function checkEmail() {
"use strict";
var status = document.getElementById("email_status");
var email = document.getElementById("email").value;
if (!(email == "")) {
status.innerHTML = "Checking...";
var request = new XMLHttpRequest();
request.open("POST", "email_check.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
status.innerHTML = request.responseText;
}
}
var verify = "emailToCheck=" + email;
request.send(verify);
}
}
This is within my HTML file with the form. Once all fields are validated, is there a way to then allow the user to submit? One user may only have a unique combination of the username and email fields which are stored in the user table along with other data, and no username can be associated with multiple usernames, and vice versa. Thank you in advance for any tips!
I have an email submit form using a javascript and contact.php code
Here is the javascript
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled=true;
http.open('get', '/contact.php?email='+email+'&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}
and here is a section of the contact.php
<?php
$to = ""; //This is the email address you want to send the email to
$subject_prefix = ""; //Use this if you want to have a prefix before the subject
if(!isset($_GET['action']))
{
die("You must not access this page directly!"); //Just to stop people from visiting contact.php normally
}
$subject = "Newsletter Sign Up"; //The senders subject
$message = trim($_GET['email']); //The senders subject
$email = ""; //The senders email address
mail($to,$subject,$message,"From: ".$email.""); //a very simple send
echo 'contactarea|<div id="thanks">thank you</div>'; //now lets update the "contactarea" div on the contact.html page. The contactarea| tell's the javascript which div to update.
?>
and the HTML
<div id="contactarea">
<form name="contactform" id="contactform">
<input class ="email" type="text" name="email" id="inputbox" value="e-mail"
onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/>
<input type="submit" value="sign up" name="send" onclick="sendemail(); return false; " class="signup" >
</form>
</div>
I am trying to fade the "Thank You" after 5 seconds but I am having some trouble.
If I set it to fade on the click of the submit button it doesn't seem to work because it it is not there until the button is clicked.
If I set it to fade on load, it only works if the button is clicked before the fade time
IS there a way to fade out not on the load of the page, but on the load of the div itself?
Try
echo 'contactarea|<div id="thanks">thank you</div>';
to
echo '
contactarea|<div id="thanks">thank you</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
setTimeout(function(){
$("#thanks").fadeOut();
},5000);
});
</script>
';
How about:
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled=true;
http.open('get', '/contact.php?email='+email+'&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
}
to:
function sendemail() {
var email = document.contactform.email.value;
document.contactform.send.disabled=true;
http.open('get', '/contact.php?email='+email+'&action=send');
http.onreadystatechange = handleResponse;
http.send(null);
setTimeout(function(){
$(document).find("#thanks").fadeOut();
},5000);
}