Send php while loop variables to javascript file - javascript

My file.js is calling a php file to fetch from database and return an encoded JSON object so I can put it on a table. Here is the file.js -
url = "backend.php"
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
And the backend.php file goes -
$sql_stmt= "SELECT * FROM TABLE ";
$result = odbc_exec($conn_id, $sql_stmt);
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
This works completely fine, but I have to wait for the PHP while loop to finish, which takes too long with large number of entries. I want to be able to return the JSON within the loop, not at the end.
Is there any way I can make the xmlhttp request and keep receiving JSON while the PHP while loop runs, not having to wait for it to finish and then send across all the rows together? Thanks

I think you should use mysql limit
JS:
var hasData = true;
var loop = 0;
while(hasData){
url = "backend.php?page="+loop;
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
if(this.reponseText != ""){
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}else{
hasData = false; //if no data retrieved
}//end if
}//end if
}
loop++; //increment loop
}//end while
PHP:
$loop = $_GET['loop'];
if($loop != ""){
$max_output = 10; //how many rows you want to display per query
$starting_row = $max_output * $loop;
// LIMIT 0, 10 = if loop is 0
// LIMIT 10, 10 = if loop is 1
// LIMIT 20, 10 = if loop is 2
$sql_stmt= "SELECT * FROM TABLE LIMIT {$starting_row}, {$max_output}";
$result = odbc_exec($conn_id, $sql_stmt);
if($result){
while ($row = odbc_fetch_array($result)) {
$age=$row['age'];
$ages[] = array('age'=> $age);
}
$myJSON = json_encode($ages);
echo $myJSON;
}else{
exit; //make sure nothing is echoed/print
}
}
{
myJSONObj = JSON.parse(this.responseText);
for ( i=0;i<myJSON.length;i++)
{
var x = document.getElementById("datatable").rows[i].cells;
x[6].innerHTML =obj[i].age;
}
}
}
Hope this helps

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

Use JavaScript to write data in a text file

I'm working on a project to make sure that users finish a video. I would like to have it just add something like "user has finished video" to an already existing text file.
Here is what I have in my JavaScript file.
var video = document.getElementById("video");
var timeStarted = -1;
var timePlayed = 0;
var duration = 0;
// If video metadata is laoded get duration
if (video.readyState > 0)
getDuration.call(video);
//If metadata not loaded, use event to get it
else {
video.addEventListener('loadedmetadata', getDuration);
}
// remember time user started the video
function videoStartedPlaying() {
timeStarted = new Date().getTime() / 1000;
}
function videoStoppedPlaying(event) {
// Start time less then zero means stop event was fired vidout start event
if (timeStarted > 0) {
var playedFor = new Date().getTime() / 1000 - timeStarted;
timeStarted = -1;
// add the new ammount of seconds played
timePlayed += playedFor;
}
document.getElementById("played").innerHTML = Math.round(timePlayed) + "";
// Count as complete only if end of video was reached
if (timePlayed >= duration && event.type == "ended") {
document.getElementById("status").className = "complete";
}
}
function getDuration() {
duration = video.duration;
document.getElementById("duration").appendChild(new Text(Math.round(duration) + ""));
console.log("Duration: ", duration);
}
video.addEventListener("play", videoStartedPlaying);
video.addEventListener("playing", videoStartedPlaying);
video.addEventListener("ended", videoStoppedPlaying);
video.addEventListener("pause", videoStoppedPlaying);
var data = "This user has finished the video";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
//sends hearder info along with the request
http.setRequestHeader("content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(data);
and Data.php has
<?php
$data = $_POST['data'];
$file = fopen('names.txt', 'a');
fwrite($file, $data);
fclose($file);
?>
As of now, there are no errors in the console, but it does not write the data to the text file.
Please let me know what i'm doing wrong
Since you are using http.setRequestHeader("content-type", "application/x-www-form-urlencoded");, the request expects the data to be formatted like serialized HTML form data. Change the following line to provide the data in the proper format:
var data = "data=This%20user%20has%20finished%20the%20video";

AJAX function gives void, fread (php) output to html div

This is a PHP function that reads first the title then the content of a txt file that has been uploaded,
<?php
$q = $_REQUEST["q"];
$output = "";
if ($q !== "") {
$bestand = fopen("Blogs.txt", "r");
if (!$bestand) {
echo "Kon geen bestand openen";
}
while (!feof($bestand)) {
$blog = fgets($bestand);
$blog = explode(",", $blog);
$i = 0;
foreach ($blog as $key) {
$i++;
if ($i % 2 == 0) {
$output = $key;
}
elseif (!$i % 2 == 0) {
$Blogname = fopen("Blogs/$key", "r");
$Blogtext = fread($Blogname, filesize("Blogs/$key"));
$output = $Blogtext;
}
}
}
fclose($bestand);
}
?>
but then i wanted to have it show up in html instead of php so i search solution and found AJAX but have been struggling for hours on why it doesn't work
function Getblog() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "Blogreader.php?q=" + str, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var para = document.createElement("div");
var t = document.createElement(this.responseText);
para.appendChild(t);
document.getElementById("BlogDiv").appendChild(para);
}
};
}
This is the Javascript code that gives a void function.
What i want it to do is make a DIV of the output of a the php function
<a> <input type="button" onclick="Getblog()"></a>
<div id="BlogDiv"></div>
And this is the refresh button and the div where they are going to be showed

Value not found in php

For login i'm passing mail id and password from javascript file and i've checked through console.log that the values are printed. But when i echo both values in php only password is showed not the mail. But i can't find any error.Here i'm pasting the php file.
<?php
require_once('DBconnection.php');
ini_set('display_errors', 1);
ini_set('log_errors', 1);
$datamail = $_GET["mailID"];
$datapass = $_GET["psw"];
//$datamail = isset($_GET["mailID"]) ? $_GET["mailID"] : '';
echo $datamail;
echo $datapass;
$login_query = "SELECT * FROM student_table where mail_id = '$datamail' AND password='$datapass'";
//echo $login_query;
$login_res = $db->query($login_query);
if( $login_res->num_rows == 1 ){
//if( $login_res == true ){
echo "success";
}
else {
//echo $login_res;
echo mysqli_error($db);
exit;
}
$db->close();
?>
Javascrit file Here
function globalLogin() {
checkLogInMail();
//pageEntry();
}
function checkLogInMail() {
var mailET = document.getElementById("mailID");
var mailIdError = document.getElementById("mailIdErr");
mailID = mailET.value;
var regex = /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()[\]\.,;:\s#\"]+\.)+[^<>()[\]\.,;:\s#\"]{2,})$/i;
if (!regex.test(mailID)) {
mailIdError.innerHTML = "Enter a valid Email id";
//loginFlag = 1;
}
else{
checkmailPass();
}
}
function checkmailPass() {
var passET = document.getElementById("psw");
var passError = document.getElementById("pswErr");
psw = passET.value;
console.log(mailID);
console.log(psw);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
alert(response);
if(!response.localeCompare( "success" )){
document.getElementById("loginErr").innerHTML = "Mail or Password is correct";
//alert("Successfully logged in :)");
//window.location.href = "index.html";
}
else{
document.getElementById("loginErr").innerHTML = response;
}
}
}
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID"+mailID, true);
xhttp.send();
}
you miss = in your get request in mailID
xhttp.open("GET", "passwordChecker.php?psw="+psw+"&mailID="+mailID, true);
You missed an equal sign '=' in your javascript at your mailid parameter.

Datalist not opening after repopulation

I'm using AJAX to retrieve information from a database, this was provided for me through another question on StackOverflow, and I've got it working how I want (Minus this one fluke).
Here's how this is set up:
<script>
var input = document.getElementById('search_bar');
input.addEventListener('keypress', function () {
callServer(input);
});
</script>
<script>
function callServer (input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//return the JSON object
console.log(xmlhttp.responseText);
var arr = JSON.parse(xmlhttp.responseText);
var parentDiv = document.getElementById('items');
parentDiv.innerHTML = "";
//fill the options in the document
for(var x = 0; x < arr.length; x++) {
var option = document.createElement('option');
option.value = arr[x];
//add each autocomplete option to the 'list'
parentDiv.appendChild(option);
};
}
}
xmlhttp.open("GET", "incl/search.php?value="+input.value, true);
xmlhttp.send();
}
Now, when typing into the input field I expect the datalist to update continuously, which it does, the only issue is that the dropdown list is not visible, and I can't access it until I click off of the input field, and then back on the dropdown arrow.
How can I resolve this?
PHP Code for those who are curious:
<?php
include 'connection.php';
$results = array();
if(!isset($_GET['value'])) {
array_push($results, 'No results found.');
die(json_encode($results));
}
$value = $_GET['value'];
$statement = $connection->prepare("SELECT name FROM `item_table`.`items` WHERE `name` LIKE :val LIMIT 5");
$value = '%'.$value.'%';
$statement->bindParam(":val", $value);
if($statement->execute()) {
$rows = 0;
while($row = $statement->fetch()) {
$rows++;
array_push($results, $row['name']);
}
if($rows == 0) {
array_push($results, 'No results found.');
die(json_encode($results));
}
} else {
array_push($results, 'No results found.');
die(json_encode($results));
}
echo json_encode($results);
?>
The JSON being sent to the client is being parsed correctly, just to re-iterate, the issue is that the datalist is not being shown properly.

Categories

Resources