"$.get" for retrieving information - javascript

I'm trying to get a simple javascript popup script going anytime the database is updated in real-time. I'm not sure as to what to do next, because I'm still a newbie with jQuery and ajax, but the following code is what I have right now:
PHP MySQL query page:
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql = "SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
//$callArray = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
if(!empty($row)) {
$number = $row['phone_number'];
}
}
$sql="SELECT Username, Password FROM tblUsers WHERE PhoneHome='$number' OR PhoneCell='$number' OR PhoneWork='$number'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" => $row['Username'], "password" => $row['Password']);
//echo json_encode($userArray);
}
echo json_encode($userArray);
mysqli_close($con);
?>
HTML page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function getCall(){
$.get("phonecall.php", function(data){
var loginInfo = jQuery.parseJSON(data);
var user = loginInfo.username;
var pass = loginInfo.password;
$('#username').html(user);
$('#password').html(pass);
});
/*$.getJSON("phonecall.php", function(data){
for (var i=0, len=data.length; i < len; i++) {
$('#username').html(data);
}
});*/
}
setInterval(getCall,5000);
</script>
<div id="username"></div>
<div id="password"></div>
</body>
</html>
One of the problems I am having is that when there are 2 or more users with the same phone number for say like a house phone, depending on where the json_encode is, will either return the last entry in the table, or return nothing at all. If the json_encode is in the while loop, I can check the console, it says the information is being retrieved, but something must not be right with my "$.get" syntax to allow more than one entry to be displayed. Any ideas?

You're only ever saving one row of data:
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" etc...
^^^^---here
If you have multiple rows of data, each row you fetch will overwrite the previous row in $userArray.
You probably want
$userArray[] = array("username" etc...
^^---- note these
so you're creating an array of results.
You'll also have to modify your JS code to accept an array of arrays, since right now you only handle one username/password.

Related

JavaScript to PHP variable value pass error (document.write command is not working)

After sending the country name "US" in JavaScript to PHP code, I will try to receive the results of PHP's work back to JavaScript and use them.
To do this I used the below code.
$ctryNm_php_temp = "document.write(ctryNm);";
As a result, it seemed that the value 'US' of the ctryNm variable was well transfered to php code.
The cryNm value and $SQL value printed on the screen contain 'US'.
However, the results of the SQL query were returned to an empty value, so we checked.
The IF statement shows that ctryNm and 'US' are different values.
(The output on the screen shows the same value and data type as string.)
I printed $result_obj and found no value.
echo and console.log command result for checking:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
var ctryNm = "US";
</script>
<?php
$ctryNm_php_temp = "<script language='javascript'>document.write(ctryNm);</script>";
$ctryNm_php = $ctryNm_php_temp;
echo $ctryNm_php . "<br><br>";
echo "--------------" . "<br>";
echo gettype($ctryNm_php) . "<br>";
if ($ctryNm_php == 'US') {
echo "Same" . "<br>";
} elseif ($ctryNm_php != 'US') {
echo "Different" . "<br>";
}
$conn = new mysqli("...", "...", "...");
mysqli_select_db($conn, '...');
mysqli_query($conn, "set names utf8");
$sql = "SELECT * FROM acst_covid_who WHERE country_code = '$ctryNm_php'";
echo $sql . "<br>";
$result_obj = mysqli_query($conn, $sql);
echo "result_obj :" . $result_obj . "<br>";
$date_adjust = 0;
$latestDate_trend = '';
while ($row = mysqli_fetch_array($result_obj)) {
if ((int)$row['confirmed_new'] !== 0) {
$latestDate_trend = $row['date'];
$date_adjust = 1;
} elseif ((int)$row['confirmed_new'] === 0) {
$latestDate_yester_trend = strtotime($row['date'] . "-1 days");
$latestDate_trend = date("Y-m-d", $latestDate_yester_trend);
$date_adjust = 0;
};
};
$result_obj = mysqli_query($conn, $sql);
$total_rows_trend = mysqli_num_rows($result_obj) - $date_adjust;
$arr_trend = array();
while ($row = mysqli_fetch_array($result_obj)) {
array_push($arr_trend, $row);
}
echo $total_rows_trend;
echo json_encode($latestDate_trend);
?>
<script>
var latestDate_js_trend = <?php echo json_encode($latestDate_trend) ?>;
var arr_js_trend = <?php echo json_encode($arr_trend) ?>;
var arr_length_trend = <?php echo $total_rows_trend ?>;
console.log(latestDate_js_trend);
console.log(arr_js_trend);
console.log(arr_length_trend);
</script>
</body>
</html>
this sadly does not work like this.
PHP code is executed first on the server, so before the website is even shown in the browser. The order you write it does not matter.
The process is like this:
You type the address in the browser and it asks the server for the page.
The server literally runs an app called php, that reads what you wrote in the code, reads only what is between <?php and ?>, nothing else (technically the first one can be <?=)
When it is done, the server sends the page to browser
The browser reads html and fires JavaScript, long after PHP was already changed.
This is simplified but show why your code will not work.

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");

Getting the value of dropdownlist in php

I have the following the html/php code :
<!DOCTYPE html>
<html>
<head>
<title>Voiture</title>
</head>
<body>
Welcome<br>
<form method="post" action="">
Liste de voiture<select name="selected" id="selected">
<?php
$sql = 'select Type from voiture';
$result = $conn->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
if(!in_array($row['Type'], $json)){
$json[] = $row['Type'];
echo '<option name = "'.$row['Type'].'">'.$row['Type'].'</option>';
}
}
?>
</select> <br>
<span id="sel" name="sel"></span>
<table border="1">
<tr id="header">
<td>Type</td>
<td>Model</td>
<td>Couleur</td>
<td>Prix</td>
<td>User</td>
<td>Action</td>
</tr>
</table>
<input type="submit" name="submit" hidden>
</form>
<script src="jquery-3.2.1.js"></script>
<script>
$(function(){
$('#selected').on('change',function(){
$('#sel').text(document.getElementById('selected').value);
$.getJSON('phpVoiture.php',function(data){
for (var x = 0 ; x < data.length ; x++){
$('<tr><td>'+data[x]['type']+'</td>'+'<td>'+data[x]['Model']+
'</td><td>'+data[x]['Couleur']+'</td>'+
'<td>'+data[x]['Prix']+'</td>'+'<td></td></tr>').insertAfter($('#header'));
}
});
});
});
</script>
</body>
</html>
And the following php page :
<?php
require_once ('./dbConnect.php');
include ('./Voiture.php');
$sel = $_POST['selected'];
$conn = mysqli_connect(servername, username, password, db ,port);
$query = "select * from voiture where Type = '".sel."'";
$result = mysqli_query($conn, $query);
$json = array();
if(mysqli_num_rows($result)>0){
while($row = mysqli_fetch_assoc($result)){
$json[] = [
'type' => $row['Type'],
'model' => $row['Model'],
'couleur' => $row['Couleur'],
'prix' => $row['Prix']
];
}
}
else{
echo mysqli_num_rows($result);
}
echo json_encode($json);
The problem is that when I select an option in the drop down list nothing happens. I want the query in the second php page to select the cars that have the type that I selected in the drop down list. I tried troubleshooting by echo an alert in both pages that have the value of the selected option, but this step also failed, so I think there is an issue with retrieving the value of the selected option. Any help would be appreciated.
You're not sending the selected value to the server. Add it to the AJAX call:
$.getJSON('phpVoiture.php', { selected: $('#selected').val() }, function(data){
//...
});
Also, your <option> elements don't have values. You used name instead, but that belongs on the <select>. Use value:
echo '<option value="'.$row['Type'].'">'.$row['Type'].'</option>';
Additionally, you're using a GET request instead of a POST request. So you need to look for the value in the $_GET array:
$sel = $_GET['selected'];
You have other typos too, such as an incorrect use of a variable in PHP:
"...".sel."..."
would be:
"...".$sel."..."
Though this brings up a point about SQL injection. You really shouldn't be directly concatenating the variable like that at all. Instead, use prepared statements with query parameters.
It's entirely possible that there continue to be other mistakes in the code I simply haven't spotted yet. You'll want your debugging to include two things:
Looking at your PHP logs for errors.
Using your browser's debugging tools to observe the AJAX request/response.

Ajax request working but no output

Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}

PHP can't populate array from selected table to json_encode and receive it on javascript

I'm build an hybrid app based on JqueryMobile. And now I'm trying to get a simple array with the categorys that I select from my mysql table. I saw many questions related to this and tired a thousand solutions but nothing worked.
Here's what I have:
PHP Code:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
//$id[] = $row['Tipo']; doesn't work either
}
echo json_encode($id);
mysql_close($conn);
with this I get blank result.
The closest I got was with this:
$id=array();
$i=0;
while ($row = mysql_fetch_assoc($sql)) {
$id[] = array("data$i" => $row['Tipo']);
echo json_encode($id[$i]);
$i++;
}
with the result:
{"data0":"Restaurantes"}{"data2":"Shopping"}{"data3":"Eventos"}{"data4":"Hoteis"}{"data5":"Oficinas"}{"data6":"Combustiveis"}
but this is obviously wrong because it has multiple json_encode invocations.
Im trying to get it with Jquery's .$get
<script type="text/javascript">
var inicio=function(argument){
$("#submit").click(function(e){
e.preventDefault();
$.get('http://myurl/get_category.php',{
},function(answer){
alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
}
$('#list').listview('refresh');
},"json"
);
});
}
$(document).on('ready',inicio);
</script>
As I said I searched into many questions and solutions but always got null values. I don't have too much experience with PhP and this is me studying and making experiences with JqueryMobile so.. something's wrong here that I can't see..
Thank you.
Found the solution here on this post
Everything on the DB must be set to UTF-8 or utf8mb4 and now it's finally working. Apreciated everyone's help :)
Try something like this...
If you want only to get the values of column 'Tipo',
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
$id["data".$i] = $row['Tipo'];
$i++;
}
echo json_encode($id);
mysql_close($conn);
If you awnt to get all the values,
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
foreach($value as $key=>$value){
$id["data".$i][$key] = $value;
}
$i++;
}
echo json_encode($id);
mysql_close($conn);
You can use the following query:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row['Tipo'];
}
echo json_encode($id);
mysql_close($conn);
It will return the categories as an array of strings in JSON. e.g. ["entry 1","entry 2"]. If you decide to use this then you would need to adjust your Javascript code.
Your javascript code contains some problems on this line:
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
In the case of you using
$id[] = $row;
In PHP, then the column name would be named Tipo, not tipo (case sensitive). The second issue is that you are trying to access answer.tipo and not the element of the array answer[i].tipo.
So with your current php code you can make it working by changing the javascript.
This line
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
To
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
Edit: Since your apparently having issues here is the full code I used.
//query.php
<?php
mysql_connect ('localhost','username','password');
mysql_select_db('db_test');
$sql=mysql_query("SELECT Tipo FROM db_test.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
}
echo json_encode($id);
mysql_close($conn);
?>
<html>
<head>
<title> JQuery db test </title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id='list' class='list'>
</div>
<script>
var debug;
$.get('http://www.example.com/test/query.php',{
},function(answer){
debug=answer;
//alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
}
// $('#list').listview('refresh');
},"json"
);
</script>
</html>
[PHP]
$id = array();
while($row = mysql_fetch_assoc($sql))
$id[] = $row['Tipo'];
echo json_encode($id);
[JS]
$(document).ready(function(){
$('#submit').click(function(e){
$.ajax({
url: '/get_category.php',
type: 'GET',
dataType: 'json'
}).done(function(res){
$('#list').html('');
for(var i=0;i<res.length;++i)
$('#list').append('<li><h3>'+res[i]+'</h3></li>');
});
});

Categories

Resources