AJAX get() data - javascript

I have a block of jQuery which uses the $.get() method in a setInterval(). I don't understand how to get data from the second URL to the jQuery code.
Jquery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
setInterval(function() {
$.getJSON("check_time.php", function(update) {
if (update) {
$("#slideshow").load("phppage.php");
}
});
}, 600000);
</script>
PHP - check_time.php
<?php
require_once('connect_pdo.php');
header('Content-type: application/json');
$stmt = $conn->prepare("$sqlst = $conn->prepare("SELECT COUNT(*) AS count
FROM ads
WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$sqlst->execute();
$row = $sqlst->fetch();");
$stmt ->execute();
$row = $stmt ->fetch();
$update = $row['count'] > 0;
$updtstatus = json_encode($update);
echo "$updtstatus";
?>
I am not getting the variable from check_time.php to the update variable in function(update).

Small alter in php page
$updtstatus = json_encode(array('count'=>$update));
echo $updtstatus;
Now your JSON is in fact something like this {"count":"true"}.
So change your if statement slightly.
$.getJSON("check_time.php", function(update) {
if (update.count===true) {
$("#slideshow").load("phppage.php");
} else {
console.log("No results");
}
});
This fiddle simulates the above answer

Your jQuery functions expects data to be returned in JSON format, so simply do so :) I've also found some flaws within your PHP code. This should do the trick:
$.get('check_time.php', function(data) {
console.log(data); // Console logging is always good
if (data.status) {
alert('Load slideshow');
}
});
check_time.php
<?php
require_once('connect_pdo.php');
$json = []; // The JSON array which will be returned
$stmt = $conn->prepare("SELECT COUNT(*) AS count FROM ads WHERE lastupdate > NOW() - INTERVAL 10 MINUTE");
$stmt->execute();
$json['status'] = (bool) $stmt->rowCount(); // Status is either false (0) or true (> 0)
echo json_encode($json);

Related

Ajax insert data not returning response - PHP & MySQL

I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.
Inside the script / Ajax - query is the variable I used to get the data (name)
var query = $('#scanned-QR').val();
fetch_customer_data(query);
$(document).on('keyup', '#scanned-QR', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '')
{
$.ajax({
url:"validScan.php",
method: 'GET',
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
if (data.status == '1') {
decoder.stop();
alert('Sucess!');
}
else if(data.status=='0'){
decoder.stop();
alert('Fail!');
}
},
error:function(err){
console.log(err);
}
});
}
My Input/Textarea
<textarea id="scanned-QR" name="scanQR" readonly></textarea>
MySQL
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
}
mysqli_close($link);
?>
For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result
So you can simply check by below, whether it is inserted or not:
if ($res) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose);
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose);
exit;
}
mysqli_close($link);
You should use exit try following code :
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
exit;
}
mysqli_close($link);
exit;
mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.
You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.
<?php
// Configure MySQLi to throw exceptions on failure
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];
// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();
// Check the number of inserted rows
if ($stmt->affected_rows) {
$response['status'] = 1;
} else {
$response['status'] = 0;
}
// Close the statement and connection
$stmt->close();
$link->close();
echo json_encode($response);

How to get an value from a php page with js

I am trying to capture a value that is calculated on a PHP page called "classes_day.php" at the same time as I pass a value per GET, "? Day = YYYY-mm-dd" to it. How do I do this with JS or JQuery?
<?php
// aulas_dia.php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT * FROM `task` WHERE `dia` LIKE ".$data."";
$result = mysqli_query($link,$query);
$soma = 0;
while ($row = mysqli_fetch_assoc($result)) {
$soma = $soma+$row['duration'];
}
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}
?>
I already tried using an iframe and contentwindow, but iframe gets the value and the contentwindow is empty (weird isn't it?).
Following Barmar's tip, I'm using $ .get, but I don't know why this loop is not working, can anyone help me?
for (i = 0; i < num_days; i++) {
x = (first_day+i)%7;
y = (first_day+i-x)/7;
h_dia(String(y)+String(x),i+1);
data_c = ano+"-"+mes+"-"+String(i+1);
$.get("aulas_dia.php?data="+data_c, function(data){
console.log(String(y)+String(x)+" - "+data_c+" - "+data);
set_aulas_fun(String(y)+String(x),data);
});
}
Use $.get() to send an AJAX request.
$.get("classes_day.php?data=YYYY-MM-DD", function(response) {
console.log(response);
});
BTW, you can add up all the durations in the SQL query instead of using a PHP loop. And you should use a prepared statement to prevent SQL injection.
<?php
include '../config.php';
$exped_duration = 14*60;
if (isset($_GET['data'])) {
$data = $_GET['data'];
$query = "SELECT SUM(duration) AS total FROM `task` WHERE `dia` LIKE ?";
$stmt = $link->prepare($query);
$stmt->bind_param("s", $data);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$soma = $row['total'];
$aulas_free = floor(($exped_duration-$soma)/50);
echo $aulas_free;
}

How can I trigger PHP if a MySQL gets a new highest ID?

Im trying to make my Webpage do an action (in this case play a sound) on the event of the highest ID (auto_increment) in my SQL table increasing, which happens when a new user is registered. E.g. : 3 users registered, highest ID = 3. When a new user registers, highest ID = 4. Webpage echos/plays sound if this happens.
The Js and PHP, respectively:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#show').load('data.php')
}, 3000);
});
</script>
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['firstName'];
echo $row['lastName'];
echo $row['inOrOut'] . '<br>';
$numId = $row['ID'] . '<br>';
echo $numId;
}
$value = 1;
$value = $numId;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
}
else
echo "nothing detected";
}
}
?>
As you can tell, I tried doing something with comparing the last and the newest ID value but failed miserably.
My attempt would be to store an initial value for oldID and then comparing this to newID before replacing it.
You can't do that only with PHP. But you could do it like this:
If you have a website, you set the current highest ID in the output of php. You can use javascript to call another php script every 5 minutes (or any other time span you find meaningful) that gives you back the current highest number. If the number from the php script is higher, than the number you have in javascript, you can let javascript play a sound for you.
Assuming your php script returns an id like this:
{"id":4}
an example for the javascript call would be this:
<html>
<head></head>
<script>
let highestId = 2;
window.setInterval(async function(){
const response = await fetch('http://localhost/jstest/index.php');
const myJson = await response.json();
console.log(console.log(myJson.id));
if (highestId < myJson.id) {
highestId = myJson.id
// here you can play your sound
$s = document.getElementById('myId');
$s.innerHTML = highestId;
}
}, 5000);
</script>
<body>
<span id="myId">0</span>
</body>
</html>
You can use a cookie variabale to do this. Set the cookie value using php and send the cookie value with php file call. This way you can identify a new highest id.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
var id = getCookie("highest_id");
$('#show').load('data.php?id='+id)
}, 3000);
});
</script>
Add set cookie in the code if the value is changed.
<?php
include ('../includes/dbh.inc.php');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM signs WHERE id = (SELECT MAX(id) FROM signs)");
if ($result->num_rows > 0) {
$numId = 0;
if ($row = $result->fetch_assoc()) {
$numId = $row['id'];
}
$value = $_GET['id'] ?? 0;
if ($value < $numId) {
//echo '<script type="text/javascript">play_sound();</script>';
echo "increased";
setcookie("highest_id", $numId, time() - 3600);
} else {
echo "nothing detected";
}
}
?>
Note the points :
In PHP : setcookie("highest_id", $numId, time() - 3600);
In Script : getCookie("highest_id");

Javascript timer refresh and php function [duplicate]

I am building a website and I can not figure out one thing. I need a script that checks if 10 seconds have past since load time, then it would run another PHP script. But I am not sure if it is possible. I have attached my attempt at this problem. Any ideas? Thanks in advance!
if (
<script type="text/javascript">
function viewplus(){
}
setTimeout(viewplus, 10000);
</script>
)
$query = "SELECT * FROM users WHERE id=" . $rws2['id_user'];
$result2 = mysqli_query($db, $query);
$rws2 = mysqli_fetch_array($result2);
$views_total = $rws2['views_total'] + 1;
$views_week = $rws2['views_week'] + 1;
$views_today = $rws2['views_today'] + 1;
$id = $rws2['id'];
$query = "UPDATE users SET views_total='$views_total',views_week='$views_week',views_today='$views_today' WHERE id='$id'";
mysqli_query($db, $query);
It is possible using jQuery like this:
Put your code in a php file and call it after 10 seconds after page load with
<script type="text/javascript">
// Check if the page has loaded completely
$(document).ready( function() {
setTimeout( function() {
$('#some_id').load('index.php');
}, 10000);
});
</script>
Example of updating a table and receiving a status message:
if (isset($_POST['id'])&&
isset($_POST['var'])){
$con = new mysqli("localhost", "my_user", "my_password", "world");
$id = $con->real_escape_string($_POST['id1']); //In our example id is INT
$var = $con->real_escape_string($_POST['var']);
$result = $con->query("UPDATE table SET value = '$var' WHERE id = $id);
(!$result) ? echo "Update failed!" : "Update succeeded";
}
This will load the output of your php file(Update filed or succeeded) in a element (this case one with id some_id).
Another way which I DO NOT recommend is using PHP's sleep() function PHP Documentation

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Categories

Resources