Javascript dynamicly change DOM using PHP - javascript

PHP code
<?php
...
//Extract the data that was sent to the server
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$findemail = [
"email" => $email,
"password" => $password,
];
$cursor = $collection->findOne($findemail);
if($cursor){
if($cursor['email'] == $email and $cursor['password'] == $password){
// I Know these two lines don't work but I want to show what I want to do
echo "success";
header('location: cms-view-products.html');
}
else {
echo "failed";
header('location: login.php');
}
}
?>
AND this is my HTML code
<?php include('demo2.php') ?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="demo2.php" onsubmit="return false"; method="post">
Email: <input type="email" name="email" required >
name: <input type="password" name="password" required >
<button type='submit' onclick="loadContent()">Load</button>
</form>
<div id="ServerContent">
<p>Dynamically loaded content goes here</p>
</div>
<script>
function loadContent(){
var url = "demo2.php";
var email = document.getElementsByName('email').value;
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById("ServerContent").innerHTML = this.responseData;
}
else
alert("Error communicating with server");
}
var data = `JSON.stringify({
"email": "document.getElementsByName('email').value",
"name": "document.getElementsByName('name').value"
})`;
xhr.send(data);
}
</script>
</body>
</html>
I've currently tried to echo the message via JS, the specific element <p id=" feedback"></p>, nevertheless it doesn't work. With PHP the process works, nevertheless, I can't redirect users using headers. I've found $_SESSION could resolve this issue. However, my question is to use JS to open a pop-up and then redirect the user to x page?
I edited the post since comments advised me about using Ajax and so this is my first attempt. I can always achieve one of the two either redirect the user to x page or show an error massage. but I can't do both.
Also, I don't want to alert the massage, but to change HTML element dynamically.
Thanks guys for your time and comments.

Related

run PHP script in JS file

I have minimal knowledge in php and js. Im trying to get value from my form once submit button has been click then trigger my php script.
Js file:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Here's my php script:
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
if (isset($_REQUEST['submit'])) {
$to = "example#mail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {
// Verify the reCAPTCHA response
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=' . $secretKey . '&response=' . $_POST['g-recaptcha-response']);
// Decode json data
$responseData = json_decode($verifyResponse);
// If reCAPTCHA response is valid
if ($responseData->success) {
$headers = "From:" . $name . '<' . $from . '>' . PHP_EOL;
$headers .= "Reply-To:" . $to . PHP_EOL;
$headers .= "MIME-Version 1.0" . PHP_EOL;
$headers .= "Content-Type: text/html; charset=UTF-8" . PHP_EOL;
$headers .= "X-Mailer: PHP/" . phpversion();
$status = mail($to, $subject, $message, $headers);
echo "<pre>";
var_dump($status);
if ($status) {
echo '<p>Your message has been sent. We will get in touch with you soon. Thank you!</p>';
} else {
echo '<p>Something went wrong. Please try again!</p>';
}
} else {
echo 'error';
}
} else {
echo 'Please check on the reCAPTCHA box.';
}
}
?>
Here's my form code in index.php. I have 3 fields name, email and message:
<?php include_once 'form-to-email.php';?>
<form id="form" method="post" action="">
<div class="input-group">
<input type="text" id="name" name="name" class="input-demo" placeholder="Your Name">
<span id="invalid-name">
Please enter at least 2 chars
</span>
</div>
<div class="input-group">
<input id="email" type="email" name="email" class="input-demo" placeholder="Email Address">
<span id="invalid-email">
Please enter valid email
</span>
</div>
<div class="input-group">
<textarea id="message" name="message" placeholder="Message">
</textarea>
<span id="invalid-message">
Please write something for us
</span>
</div>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>">
</div>
<input type="submit" name="submit" id="button" class="demo" value="Book a Demo">
</form>
I get console.log empty values. Is this the right path or calling php is simply not doable?
Update
It now echos true and message sent.
Based on your question you are looking simply to submit a form and access the value in your php script. But it seems you are trying to submit the form via an ajax request. The first place to start is in your javascript code. The first thing I see is that you are calling a couple functions that are not defined so you never pass the if check and get to where it is supposed to say 'got here':
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
console.log('got here'); // you never get to this point
grecaptcha is not yet defined and I don't see any function definition for validateFields() so that fails as well. As a temporary fix while you are debugging it, comment out the if check like this so you can focus on the xhr request:
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
// Comment out the following two lines
// so you can focus on getting the XHR request to work
// let response = grecaptcha.getResponse();
// if (validateFields() && !response.length == 0) {
console.log('got here');
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.open('POST', 'form-to-email.php');
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
// } Comment out the closing bracket to match the comments from above
document.getElementById('button').style.cursor = 'not-allowed';
});
Ok, now when you hit submit, you should be sending the form data to your php script. To test out what shows up in the php script you can bail out early to see the contents of your $_POST variable.
<?php
// Google reCAPTCHA API key configuration
$siteKey = 'siteKey';
$secretKey = 'secretKey';
// Echo out the word success to make sure you got to this point.
// Then echo out the contents of your $_POST variable to see what is in it.
echo "Success";
var_dump($_POST);
exit; // exiting here bails out early.
// When you var_dump out your $_POST variable you will notice that
// $_POST['submit'] is not set since you don't have an input field
// for that value.
if (isset($_POST['submit'])) {
$to = "example#email.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$name = $_POST['name'];
$subject = "Form submission";
$message = $name . " wrote the following:" . "\n\n" . $_POST['message'];
. . .
Now, since you decided to do this via ajax, it will be a bit trickier to see the echo statement and the var_dump. To find out if it is working you need to use your dev tools network tab (F12 -> Network). Under the network tab you will see something like this:
Each time you hit submit, it should show a new line representing that request to the server. You can select a line and inspect the payload, preview, response tabs to see what was sent and what was received.
I hope this helps point you in the right direction. I'm not going to get into the issues with validating re-captcha and form validation. Those are topics for another question once you get the basic form working.
Cheers!
Based on this answer, change the way you're calling the php function.
document.getElementById('form')
.addEventListener('submit', function (event) {
event.preventDefault();
let response = grecaptcha.getResponse();
if (validateFields() && !response.length == 0) {
var data = new FormData(document.getElementById('form'));
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
}
xhr.open('POST', 'form-to-email.php?submit'); //don't forget submit here
xhr.send(data);
}
document.getElementById('button').style.cursor = 'not-allowed';
});
Also, try using $_REQUEST instead of $_POST in PHP file, as in:
if (isset($_REQUEST['submit'])) {
echo 'HERE IN PHP';
}

Decode JSON package from PHP using AJAX

I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don't know how to have the AJAX call, decode the JSON, and then have some if statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm">
<h1 class="title" unselectable="on">Login</h1>
<input placeholder="Username" type="text" name="username" class="form" id="username"/>
</br>
<input placeholder="Password" type="password" name="password" class="form" id="password"/>
</br>
<input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/>
</br>
</form>
JS/AJAX (Same page):
function SubmitFormData() {
var username = $("#username").val();
var password = $("#password").val();
$.post("submit.php", { username: username, password: password},
function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]);
$password = mysqli_real_escape_string($connect, $_POST["password"]);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if(password_verify($password, $row["password"]))
{
$Obj->error = "three";
$myJSON = json_encode($Obj);
}
else
{
$Obj->error = "two";
$myJSON = json_encode($Obj);
}
}
}
else {
$Obj->error = "one";
$myJSON = json_encode($Obj);
}
//error one=user not found
//error two=wrong password
//error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don't know if or how I can do this in JS or AJAX.
decode JSON package
if error=one, do something
if error=two, do something else
if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
//passes results to a function
start(JSON.parse(this.responseText));
}
}
xmlhttp.open("POST", "PHP WEBSITE URL", true);
//sends the request with a FormData object based on the form
xmlhttp.send(new FormData(document.getElementById("myForm")));
function start(object) {
alert(object);
}
For this to work, your PHP script will have to echo your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") {
//echo javascript object
echo json_encode(['success'=>true]);
} else {
//echo javascript object
echo json_encode(['success'=>false]);
}
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.

loop through JSON file using ajax, PHP & Javascript

I'm creating a small game where users must register or login before playing. I have a separate json file that stores already registered users.
Once a user enters their username and password into a field I make an AJAX call to retrieve the data using PHP with the intent of checking whether their details are on file. Firstly I tried sending back a JSON encoded object to parse through in Javascript. This is the code I have so far:
JSON:
{"LogIns":[
{
"Username":"mikehene",
"password":"123"
},
{
"Username":"mike",
"password":"123"
}
]
}
HTML:
<fieldset>
<legend>Please log in before playing</legend>
<form>
Username: <br>
<input type="text" placeholder="Enter a Username" id="username1" name="username"><br>
Password: <br>
<input type="password" placeholder="Enter a password" id="password" name="password"><br>
<input type="submit" value="Submit" onclick="return checkLogin();">
</form>
</fieldset>
PHP:
<?php
$username = $_POST['username'];
$str = file_get_contents('logins.json'); // Save contents of file into a variable
$json = json_decode($str, true); // decode the data and set it to recieve data asynchronosly - store in $json
echo json_encode($json);
?>
Javascript & AJAX call:
var usernamePassed = '';
function checkLogin(){
usernamePassed = document.getElementById("username1").value;
callAJAX();
return false;
}
function callAJAX(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp.responseText);
}
}
xhttp.open("POST", "LogInReg.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=" + usernamePassed);
}
function myFunction(response) {
var arr = response;
var objJSON = JSON.parse(arr);
var len = objJSON.length;
for(var key in objJSON){
console.log(key);
}
}
But it only prints out "LogIns". I also tried this:
for (var i = 0; i < objJSON.length; ++i) {
if(objJSON[0].Username == usernamePassed){
console.log("found it");
}
else{
console.log("didn't find it!");
}
}
Therefore I tried another approach (parse the data in the PHP file) like so:
foreach ($json['LogIns'][0] as $field => $value) {
if($json['LogIns'][0]['Username'] == $username){
echo "Logged In";
break;
}
else{
echo "No user found";
break;
}
}
But when I enter "mike" as a user name it is echoing "No user found". So I'm lost! I'm new to coding and trying to learn myself. I would love to learn how to do it both methods (i.e. PHP and Javascript).
Everything I've found online seems to push toward JQuery but I'm not quite comfortable/good enough at JQuery yet so would like to gradually work my way up to that.
I haven't even got to the register a user yet where I'm going to have to append another username and password on registration.
Any help would be GREATLY appreciated.
Thanks in advance
Try this
$json = json_decode($str, true);
$password = $_POST['password'];
foreach($json['LogIns'] as $res)
{
if($res['Username']==$username && $res['password']==$password)
{
echo json_encode($res['Username']);
//echo 'user found';
}
}

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

Many spaces before javascript result

I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.

Categories

Resources