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

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();
}

Related

Javascript dynamicly change DOM using PHP

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.

Retrieving large data amount as datalist from Remote PC

I have a simple HTML page that allows the user to select the amount of fields to enter information. Once the user selects a number, a Javascript onchange method is called that sends the parameter to a PHP page where data is retrieved from a database and stored in a datalist, that is dynamically appended to the HTML page.
When I access this function on the host PC, everything works perfectly. However, when I access this from a remote client, the input fields dont generate automatically.
Here is the code:
<html>
<head>
<script>
function GetInfo(str) {
if (str == "") {
document.getElementById("items").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("items").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/Return-List.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form method="POST" action="../php/Submit.php">
<label>Number of Items</label>
<input type="number" name="numberofitems" onchange='GetInfo(this.value)'>
<br/>
<div id="items"></div>
<input type="submit" value="Go" />
</form>
</body>
</html>
PHP:
<?php
include("connection.php");
if($conn->connect_error) {
die("Connection Failed");
} else {
$items = $_GET['q'];
$fields = "";
$query = mysqli_query($conn,"SELECT name, desc FROM ItemTB");
for($i=1; $i<=$items ; $i++) {
$fields .= "<label>Input</label>
<input list='items' name='items[]' />
<datalist id='items'>";
while($row = mysqli_fetch_array($query)) {
$fields .= "<option value='" . $row['name'] . " | " . $row['desc'] . "'> " . $row['desc'] . "</option>";
}
$fields .= "</datalist>";
}
echo $fields;
}
?>
I have tried using relative and fixed locations in the JavaScript, and limiting the results to 500. Limiting the database results works, and it is important to note that the table returns upwards of 170 000 results. This seems to be the issue here.
How do I retrieve the entire dataset? Is there a way to do this more efficiently, to pack all data without lag?
Thanks in advance.

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';
}
}

Store different value in the database from the forms created dynamically using PHP?

Have a look at the screenshot below.
As per the screenshot, I have the data fetched into the different blocks based on the database. For example, based on the username and password, these values are fetched from the database and displayed in different blocks. I have the PHP to store the value into the database, but the problem that I am facing is that when i try to upload it from other block, it still saves the value from the first block.
Codes as as below:
<?php
include('includes/config.php');
$upload = 'uploads/';
session_start();
$_SESSION['$userid'];
$sql = "SELECT * FROM tbl_store INNER JOIN tbl_job ON tbl_store.store_code = tbl_job.store_code WHERE username = '$userid'";
$result = mysqli_query($conn,$sql);
$rowcount=mysqli_num_rows($result);
// echo "$rowcount";
$stores = array();
$stores_add = array();
$stores_chain = array();
$job = array();
$client = array();
$brand = array();
$week= array();
$x = 1;
$imgCnt =1;
while($row = mysqli_fetch_array($result)){
echo "工作".'<br/>';
echo $row['jobs'].'<br/>'.'<br/>';
$job[] = $row['jobs'];
echo "客戶".'<br/>';
echo $row['Client'].'<br/>'.'<br/>';
$client[] = $row['Client'];
echo "牌子".'<br/>';
echo $row['Brand'].'<br/>'.'<br/>';
$brand[] = $row['jobs'];
echo "週數".'<br/>';
echo $row['week'].'<br/>'.'<br/>';
$week[] = $row['week'];
$target = $upload.'/'.$row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$testpath = $row['Client'].'/'.$row['Brand'].'/'.$row['jobs'].'/'.$row['store_code'].'/';
$_SESSION['target1'.$x] = $target;
if(!file_exists($target))
{
mkdir($target,0777,true);
}
?>
<form id='uploadForm-<?php echo $imgCnt; ?>' action = '' enctype='multipart/form-data' method = 'POST' class="form<?php echo $imgCnt; ?>">
<input type="file" class="image<?php echo $imgCnt; ?>" name="img" onChange="readURL(this);" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type='button' id = '<?php echo $imgCnt; ?>' class='uploadPicture<?php echo $imgCnt; ?> btn btn-primary' value = '上載'>
<!-- <input type="button" value="上載" class="uploadPicture" id="upload_btn<?php echo $imgCnt; ?>"/> -->
</form>
<form enctype="application/x-www-form-urlencoded">
<table width="200" border="1">
<tr>
<td>Product</td>
<td>Promotional Price</td>
<td>Regular Price</td>
<td>Stacking</td>
</tr>
<tr>
<td><input type="text" id="product"></td>
<td><input type="text" id="pp1"></td>
<td><input type="text" id="rp1"></td>
<td><input type="text" id="stacking"></td>
</tr>
</table>
<div id ="div1">
<input type="button" value="Submit" onClick="PostData();"/><br/>
</div>
</form>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function PostData() {
// 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 product = document.getElementById("product").value;
var pp1 = document.getElementById("pp1").value;
var rp1 = document.getElementById("rp1").value;
var stacking = document.getElementById("stacking").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'report.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("product=" + product + "&pp1=" + pp1 + "&rp1=" + rp1 + "&stacking=" + stacking);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
<?php
echo "-------------------------------------------------------".'<br/>';
$x = $x+1;
$imgCnt++;
}
?>
I have removed the code for image upload from it as it works completely fine. The problem is the data from the other block is not stored to the database. only the value for the first block is stored second time even. How to solve this problem.
PHP to store data:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "testing";
$conn = new mysqli($servername, $username, $password,
$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO tbl_report (product,pp1, rp1,stacking)
VALUES ('$product', '$pp1', '$rp1','$stacking')";
if ($conn->query($sql) === TRUE) {
echo "Successful";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
To expand on what #Logan Wayne pointed out...
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element in the source code.
So, in your JavaScript, when you grab references to your table data elements, you'll always get the FIRST instance of a Document object with whatever id you provide.
// 2. Define what to do when XHR feed you the response from the server - Start
var product = document.getElementById("product").value; <-- will always return the same element
var pp1 = document.getElementById("pp1").value; <-- will always return the same element
var rp1 = document.getElementById("rp1").value; <-- will always return the same element
var stacking = document.getElementById("stacking").value; <-- will always return the same element
You'll either have to assign unique ids to your td objects, or, again as #Logan Wayne mentioned, utilize the class property of HTML DOM objects.
Classes can be used to group like elements. After assigning class names to the different columns in your table (Product, Promotional Price, Regular Price, Stacking) you can use getElementsByClassName() to get an array of the td elements.
...
var products = document.getElementsByClassName("product"); <-- array of product td elements
...

Trying to add form data to a database using an Ajax request with PHP

I cant quite get my form to add its data to a local database I have setup.
I have a addproducts.php page:
<?php
$title = "Products";
include("Header.php");
include("PHPvalidate.php");
?>
<script src="AjaxProduct.js"></script>
<article>
<section>
<fieldset><legend><span> Add a product to the database </span> </legend>
<form id ="productsform" method="post" onsubmit="return false;">
<input type="hidden" name="submitted" value="true">
<label> Enter a product name: <input type="text" id="name" name="name"/> </label>
<label> Enter a product quantity: <input type="number" id="quantity" name="quantity"/> </label>
<label> Enter a product description: <input type="text" id="description" name="description"/> </label>
<label> Enter a product price: <input type="text" id="price" name="price"/> </label>
<label> Upload a image of the product: <input name="image" accept="image/jpeg" type="file"></label>
<input id="submit" name="submit" type="button" class="reg" value="Add Product">
<div id="check"></div>
</form>
</fieldset>
</section>
</article>
I then have a ajax fetch request to gather up the data to get ready to be posted to the database:
fetch = function () {
var xhr, name, quantity, description, price, target;
xhr = new XMLHttpRequest();
target = document.getElementById("check");
name = document.getElementById("name").value;
quantity = document.getElementById("quantity").value;
description = document.getElementById("description").value;
price = document.getElementById("price").value;
var vars = "name="+name+"&quantity="+quantity+"&description="+description+"&price="+price;
changeListener = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
target.innerHTML = xhr.responseText;
} else {
target.innerHTML = "<p>Something went wrong.</p>";
}
};
xhr.open("POST", "addSQL.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = changeListener;
xhr.send(vars);
}
pageLoaded = function() {
var fetchbutton = document.getElementById("submit");
if(fetchbutton) {
fetchbutton.addEventListener("click", fetch);
}
}
window.onload = pageLoaded;
And finally an addSQL.php
That send the data to the database:
//Stores all information passed through AJAX into the query
$name = $_POST['name'];
$quantity = $_POST['quantity'];
$description = $_POST['description'];
$price = $_POST['price'];
//Adds information to database
$query = "INSERT INTO products (name, quantity, description, price) VALUES ('$name','$quantity','$description','$price')";
//Runs the query
$result = $mysqli->query($query) OR die("Failed query $query");
echo $mysqli->error."<p>";
//
?>
When i try to add dummy data into the form and submit nothing happens with no errors or anything so Im not sure where the point of failure is.
Any help would be appreciated.
I think you're missing this:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
Edit: also now that I look at it, you're vulnerable to SQL injection and an apostrophe in your data will break the query:
$name = $mysqli->real_escape_string($_POST['name']);
$quantity = $mysqli->real_escape_string($_POST['quantity']);
$description = $mysqli->real_escape_string($_POST['description']);
$price = $mysqli->real_escape_string($_POST['price']);
You add some alert() in your code to find the error.
add alert in the every line when you get a value in variable like alert(vars); after the assign value in vars variable

Categories

Resources