Using AJAX for query to MySQL database - javascript

I'm using the JavaScript function setInterval every 30 seconds to check the MySQL table with AJAX. Using AJAX it updates the page with new results without reloading the page.
I would like to use the effect highlight to colour certain records, in the example below this highlights ID 1 and 10:
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
I would like to highlight all new records that have been added since the last load.
index.php
// Run polling function every 60 seconds
var myVar = setInterval(myfunction, 30000);
// Load data from check_status page
function myfunction() {
$.ajax({
url: "check_status.php", success: function(result2) {
$("#div2").html(result2);
$("#title").html("Food Items AUTO Poll");
$("#image_li_1").effect("highlight", {}, 25000);
$("#image_li_10").effect("highlight", {}, 25000);
}
});
}
check_status.php
// Include and create instance of db class
require_once 'DB.class.php';
$db = new DB();
<?php
// Fetch all items from database
$data = $db->getRows();
if (!empty($data)) {
foreach ($data as $row) {
?>
<li id="image_li_<?php echo $row['id']; ?>" class="ui-sortable-handle">
<a href="javascript:void(0);" style="float:none;" class="image_link">
<?php echo $row['name']; ?>
</a>
</li>
<?php
}
}
?>
DB.class.php
<?php
class DB {
// Database configuration
private $dbHost = "###";
private $dbUsername = "###";
private $dbPassword = "###";
private $dbName = "###";
private $itemTbl = "###";
function __construct() {
if (!isset($this->db)) {
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if ($conn->connect_error) {
die("Failed to connect with MySQL: " . $conn->connect_error);
} else {
$this->db = $conn;
}
}
}
// Get rows from data table
function getRows() {
$query = $this->db->query("SELECT * FROM ".$this->itemTbl." ORDER BY img_order ASC");
if ($query->num_rows > 0) {
while ($row = $query->fetch_assoc()) {
$result[] = $row;
}
} else {
$result = FALSE;
}
return $result;
}

send ajax request to server each some second
respond json-formatted data, not html from your server controller
if this is first request, save it into "current" and "previous" variables
if this is not first request, save it into "current" variable
Display your data in your html page. During this operation compare "current" and "previous" variables, if something new in "current" highlight it
before next request to server, make assignment: previous = current
profit
Try to search and read something like "create REST service php". You should get main idea of such approach. Generally, your code should look like this:
php.php
<?php
$yourDatabaseClass = new YourDatabaseClass("localhost", "username", "password", "database");
$data = $yourDatabaseClass->getTable("select * from table");
echo json_encode($data);
Your js:
var oldData = [];
var currentData = [];
var yourElement = document.getElementById('application');
client.doRequest("php.php").then(function(response){
currentData = response;
renderData();
})
function renderData() {
yourElement.innerHTML = '';
currentData.forEach(function(item){
if(isNew(item)) {
yourElement.apendChild(createHighlightedData(item));
} else {
yourElement.apendChild(createOrdinarData(item));
}
})
}
function createHighlightedData(item) {
return ...
}
function createOrdinarData(item) {
return ...
}

Related

Integrate 2 functions for 1 button and keep input fields disabled after reload

A) I would like to have 2 different functions for 1 button.
For first click function 1 should start, for second click function 2, for third click function 1, fourth click function 2 ...
For now I need 2 buttons, one disables and the other one enables the possibility to input data in a form field. The best would be to have both functions for 1 button (as explained above).
Does anyone has an idea how to do that?
B) All data get saved and can be reopened in the datamanagementsystem. I would like that disabled fields stay disabled (after reopening the form again) for input. Is there a possibility to do so?
<script>
var nav = false;
function disable18() {
document.getElementById("field1").style.color = "red";
document.getElementById("field1").value = "X";;
document.getElementById("field1").disabled = true;
nav = true;
}
function enable18() {
document.getElementById("field1").disabled = false;
document.getElementById("field1").value = "";
document.getElementById("field1").style.color = "black";
nav = false;
}
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
</script>
How I get the data from database:
<?php
session_start();
require_once 'sc/functions.php';
$user_home = new USER();
if(!$user_home->is_logged_in())
{
$user_home->redirect('index.php');
}
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$_SESSION['userSession']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<?php
// php search data in mysql database using PDO
// set data in input text
$user = "xxx";
$pass = "xxxx";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO('mysql:host=localhost;dbname=xxx;charset=utf8', $user, $pass); //mysql:host=localhost;dbname=test_db","root","")
$pdoConnect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$ID = $_POST['ID'];
// mysql search query
$pdoQuery = "SELECT * FROM dabase WHERE ID = :ID";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your ID to the query ID
$pdoExec = $pdoResult->execute(array(":ID"=>$ID));
if($pdoExec)
{
// if ID exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$ID = $row['ID'];
$field1 = $row['field1'];
}
}
// if the id not exist
// show a message and clear inputs
else{
header( "Location: nodatasearch.php" ); die;
}
}else{
echo 'ERROR Data Not Inserted';
}
} ?>
Submitting/Saving data:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require("php/tc.php");
$ID = $_POST['ID'];
$field1 = $_POST['field1'];
$sql = "UPDATE pdbase SET
field1 = :field1
WHERE ID = :ID";
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':ID', $ID);
$stmt->bindValue(':field1', $field1);
$stmt->execute();
// var_dump($_POST['user']);
?>
My asnwer will solve problem A however problem B is a little more complicated. You will need a flag for this, for example this is your html
<input type="text" id="field1">
<button id="toggler" class="btn btn-success" onclick="toggleNav()">Toggler</button>
in your js start off with creating your flag, let's set it to false
var nav = false;
When your 1st function is called change your flag to true
function disable18() {
document.getElementById("field1").disabled = true;
nav = true;
}
Now for the second function we will set it back to false
function enable18() {
document.getElementById("field1").disabled = false;
nav = false;
}
Now we create the function that toogles between the 2 of them
function toggleNav() {
if(nav==false){
disable18();
} else {
enable18();
}
}
After that, all that's left is make sure your toggleNav() function is in the onclick() in your button. Now for problem B I have more questions than answers. Need more details about how do you want to do achieve that

Access Json Array from HTTP Get request and Update Page every 1s Using AJAX or JQUERY

So, I'm working on a project which involves getting data from my website into the ESP32. I came across making the Json array and updating the info from time to time, but now I need to get the specific info from my Json array so I can use it with my ESP. For some reason when I try to access the data from my page, I'm getting 0 instead of the number that is in that place, in the case of text, I don't receive anything as a response. I fixed not receiving any response from the file, I had to create a separate PHP file in which get the database info and turns that info in a datajson.json file, so the code that I have works, but I will need to update the PHP file every 1 second, I saw that Ajax was the way to go since I wouldn't need to refresh the page every time, only the content
ESP32 code:
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("https://nps-tech.com.br/receive.php"); //Specify the URL and certificate
int httpCode = http.GET();
if (httpCode > 0)//Check for the returning code
{
String payload = http.getString();
Serial.println("\nStatuscode: "+ String(httpCode));
Serial.println(payload);
char json[500];
payload.replace(" ", "");
payload.replace("\n", "");
payload.trim();
payload.remove(0,1);
payload.toCharArray(json, 500);
StaticJsonDocument<200> doc;
deserializeJson(doc, json);
int id = doc["AutoIncrement"];
const char* nome = doc["Nome Aparelho"];
int stat = doc["Status"];
Serial.println(id);
Serial.println(nome);
Serial.println(stat);
}
else
{
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(10000);
}
New response from ESP32:
Statuscode: 200
[{"AutoIncrement":"1","Aparelho":"LED","Status":"0"}]
1
LED
0
PHP Code, How can I set a SetInterval to update get_data function from php every 1 second, without reloading the page:
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "stuuf";
$dBUsername = "stuuf";
$dBPassword = "stuuf";
$dBname = "stuuf";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
setInterval(1000);
//ajax to update every 1s
</script>

Return MySQL Query as Array for Specific Table Row Clicked

I've been working on this for about 3 days and still cannot figure out how to do this even with all my searches.
Here's what I've already accomplished:
I have a table in index.php that fetches data from a MySQL Database. When a user clicks on any given row in the table, I want the eventDetail.php page to open.
Here's what I haven't figured out yet:
THEN I need eventDetail.php to run a MySQL query that fetches the data for the table row which was clicked on the previous index.php page and store it in an array so I can use the data on the eventDetail.php page where needed.
Here is the code on the index.php page that opens my eventDetail.php page:
index.php
<script>
$(document).ready(function onClickRow() {
$('.clickDetail').click(function(){
var str=$(this).attr("value"); /* Find out which button is clicked, stores
its value in variable 'str'*/
$(window.location = 'eventDetail.php').load('eventDetail.php?str='); /* To
collect data from database */
})
})
</script>
Here's what I have so far in eventDetail.php but not even sure if I've started correctly:
eventDetail.php
<?php
$db_host = '127.0.0.1'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'password'; // Password
$db_name = 'mydb'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$str=$_GET['str']; // collect the row id
$queryRow = ("SELECT id, eventName, description FROM mytable WHERE
id=:id");
I need the id, eventName, description from the row which was clicked on the previous page to be returned to an array so I can actually use that data on this page.
Finally figured this out thanks to #BobRodes.
This is the script you need in index.php:
<script>
$(document).ready(function onClickRow() {
$('.clickDetail').click(function(){
var str=$(this).attr('value'); // Find out which button is clicked, stores its value in variable 'str'
$(window.location = 'eventDetail.php?str='+str).load('eventDetail.php?str='+'/'+str); // To collect data from database
})
})
</script>
And this is the php code you need in eventDetail.php:
<?php
$db_host = '127.0.0.1'; // Server Name
$db_user = 'root'; // Username
$db_pass = 'password'; // Password
$db_name = 'mydb'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$str = $_GET['str']; // collect the row id
$queryRow = ("SELECT id, eventName, description FROM mytable WHERE id='$str'"); // SQL Statement
$result = mysqli_query($conn, $queryRow); // Execute SQL Query
$items = array(); // Create an array and store in a variable called $items
// Statement below fetches the row that was clicked and stores the data in the array $items
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
}
// Statement below separates each item in the array and converts it to a string and stores in variable named $item
foreach ($items as $item) {
echo $item['id'];
echo $item['eventName'];
echo $item['description'];
}
mysqli_close($conn);
?>
This will open eventDetail.php and return the table row in the database that was clicked in the url. You can then edit the code in the rest of the page to return the data from that row as you like on the page.

Database won't connect, no results returned

So I've got three PHP files, and I'm trying to connect my database through these files. It won't seem to connect, I'm trying to connect it so then my ajax in my javascript file will hopefully work.
BaseClass.php:
<?php
require("Conn.php");
require("MySQLDao.php");
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
if (empty($raw_post_data))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($raw_post_data, true);
$recieved = $body["data"];
//Gets the result of a query
//$result = $dao->MySQLDaoMethodName(parameters);
//Return the result of the query
echo json_encode($result);
}
$dao->closeConnection();
return;
}
?>
When I run this in chrome all it shows is:
{"status":false,"title":"Error","message":"No Data Recieved"}
MySQLDao.php:
<?php
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults($data)
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
//}
echo json_encode($result);
echo($result);
}
}
?>
Nothing shows when I run this in chrome. Even when I put echo statements in some of the functions.
Conn.php:
<?php
class Conn
{
public static $dbhost = "***";
public static $dbname = "***";
public static $dbuser = "***";
public static $dbpass = "";
}
?>
part of my test.html:
function callPHP() {
$.ajax ({
type: "GET",
datatype: "application/json",
url: "MySQLDao.php",
data: { action : 'getResults()' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
}
//error, function(err){console.log(err)}
});
}
I basically just want to be able to write query methods and transport the results from these querys to my js, this is because I have a few graphs in my javascript and I want to get data from the database. All this code doesn't produce any errors I believe but it's just not returning anything back.
All help appreciated! Thanks!

AJAX POST request is failing

Apologies for the generic title.
Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it.
The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price.
Here's my AJAX request:
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : 'data',
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})
Here's the PHP that generates the JSON:
<?php
function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country)
{
header("Access-Control-Allow-Origin: *");
$html = file_get_contents($list_url);
$doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($html))
{
$doc->loadHTML($html);
libxml_clear_errors(); // remove errors for yucky html
$xpath = new DOMXPath($doc);
/* FIND LINK TO PRODUCT PAGE */
$products = array();
$row = $xpath->query($product_location);
/* Create an array containing products */
if ($row->length > 0)
{
foreach ($row as $location)
{
$product_urls[] = $product_url_root . $location->getAttribute('href');
}
}
$imgs = $xpath->query($photo_location);
/* Create an array containing the image links */
if ($imgs->length > 0)
{
foreach ($imgs as $img)
{
$photo_url[] = $photo_url_root . $img->getAttribute('src');
}
}
$was = $xpath->query($was_price_location);
/* Create an array containing the was price */
if ($was->length > 0)
{
foreach ($was as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$was_price[] = "£".$stripped;
}
}
$now = $xpath->query($now_price_location);
/* Create an array containing the sale price */
if ($now->length > 0)
{
foreach ($now as $price)
{
$stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue);
$now_price[] = "£".$stripped;
}
}
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
$result = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
echo json_encode($result);
}
}
else
{
echo "this is empty";
}
}
/* CONNECT TO DATABASE */
$dbhost = "xxx";
$dbname = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_GET['id'];
/* GET FIELDS FROM DATABASE */
$result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'");
while($row = mysqli_fetch_array($result))
{
$list_url = $row['list_url'];
$shop_name = $row['shop_name'];
$photo_location = $row['photo_location'];
$photo_url_root = $row['photo_url_root'];
$product_location = $row['product_location'];
$product_url_root = $row['product_url_root'];
$was_price_location = $row['was_price_location'];
$now_price_location = $row['now_price_location'];
$gender = $row['gender'];
$country = $row['country'];
}
scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country);
mysqli_close($con);
?>
The script works fine with this much simpler JSON:
{"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it.
If you concatenate two (or more) JSON texts, you do not have valid JSON.
Build a data structure inside the loop.
json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work:
$result = array();
/* Create an associative array containing all the above values */
foreach ($product_urls as $i => $product_url)
{
// Append value to array
$result[] = array(
'product_url' => $product_url,
'shop_name' => $shop_name,
'photo_url' => $photo_url[$i],
'was_price' => $was_price[$i],
'now_price' => $now_price[$i]
);
}
echo json_encode($result);
In this example I am echoing the final results only once.
You are sending post request but not sending post data using data
$.ajax(
{
url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1',
type : 'POST',
data : {anything:"anything"}, // this line is mistaken
dataType : 'json',
success : function (result)
{
var result = result['product_url'];
$('#container').append(result);
},
error : function ()
{
alert("error");
}
})

Categories