display result only if payload=1 - javascript

I need help with the script. I want to show the result on page only when payload=1,if payload=0 do not display..
I've tried messing with mysql statements and I realized I need to change that in my script
this is my php:
<?php
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully<br>';
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 ORDER
BY id DESC LIMIT 1 ";
$retval = mysqli_query( $conn, $sql );
if(! $retval ) {
die('Could not get data: ' . mysqli_error());
}
while($row = mysqli_fetch_assoc($retval)) {
echo "ID: " . $row["id"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
mysqli_free_result($retval);
echo "Fetched data successfully\n";
mysqli_close($conn);
my database is:
rooms
table:room1
ID
topic
payload
DateTime_created
and my index.html
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
sendRequest();
function sendRequest(){
$.ajax({
url: "vineri.php",
success:
function(data){
$('#listposts').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setInterval(sendRequest, 5000); // The interval set to 5 seconds
}
});
};
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
How do I get the result to display only when the payload is 1 ?

Try this code. I have re-written it for you. I run and tested it and it works for me.
First create table and insert as follows..
create table room1(ID int primary key auto_increment, topic varchar(30), payload int(11), DateTime_created timestamp);
insert into room1(topic, payload) values ('nancy topic 1', 1);
insert into room1(topic, payload) values ('nancy topic 2', 0);
here is vineri.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='1' ORDER BY ID DESC LIMIT 1";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
echo "ID: " . $row["ID"]. "<br>";
echo "Topic: " . $row["topic"]. "<br>";
echo "Payload: " . $row["payload"]. "<br>";
echo "Timestamp: " . $row["DateTime_created"]. "<br>";
}
?>
index.html
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
// set for formality. though you can pass it to backend as a variable
var payload= 1;
var datasend = "payload="+ payload;
$.ajax({
type:'POST',
url:'vineri.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
$('#listposts').fadeIn('slow').prepend(msg);
}
});
});
</script>
</head>
<body>
<div id="listposts"> </div>
</body>
WARNING: ID and id may not be the same as its cap intensive. You can see that In my table creations and sql queries I used ID instead of id. so becareful of capital and small letter that you use
Updated content
Sorry for being late. I don not understand properly what you want. Here is just what I guessed you want
if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
by using limit 1, only one rows will be retrieved.
if you want to get last rows with last id of 200 where payload is 0
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
Here is how I edited the code. you can test various sql queries that i commented
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pass";
$dbname = "rooms";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where payload='0'";
//if you want to get last rows with last id of 200 where payload is 0
//$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' and payload='0' ";
//if you want to get last rows with last ID of 200 then
$sql = "SELECT ID, topic, payload, DateTime_created FROM room1 where ID='200' ";
$retval = mysqli_query($conn,$sql);
while($row = mysqli_fetch_array($retval)){
$ID = $row["ID"];
$topic = $row["topic"];
$payload = $row["payload"];
$DateTime_created = $row["DateTime_created"];
}
if($payload ==0){
// insert record here
// return payload to the screen
echo "success<br><br>";
echo "ID: " . $ID. "<br>";
echo "Topic: " . $topic. "<br>";
echo "Payload: " . $payload. "<br>";
echo "Timestamp: " . $DateTime_created. "<br>";
}else{
//cannot insert record
echo "failed";
}
?>

Related

How do get php array in javascript variable

I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>

Script not posting information from dropdown to textbox

I am trying to get data from a dropdown and post it to a textbox. But by some reason I dont get any response also the Error message that needs to be shown in the textbox.
First of all, this is my dropdown:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM products";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control' id='product1' name='product1' onChange='getProduct1(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["article_id"]. " | " . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
After selecting a item in the dropdown the scripts needs to paste . $row["name"]. into the following textbox:
<input type="text" class="form-control" id="product11" name="product11">
The jquery script that I am using to paste the name is the following script:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getProduct1(selectedItem) { // Do an Ajax request to retrieve the information
console.log("getProduct1 before ajax", jQuery('#product1').val());
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'product1' : jQuery('#product1').val()},
success: function(response){
// and put the price in text field
console.log("getProduct1 after ajax", jQuery('#product1').val());
jQuery('#product11').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
The script uses the following PHP script that connects with the database and retrieves the relevant information:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$product1 = isset($_POST['produc1t'])?$_POST['product1']:'';
$product11 = isset($_POST['product11'])?$_POST['product11']:'';
$query = 'SELECT * FROM products WHERE id="' . mysqli_real_escape_string($conn, $product1) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['product11'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo "Error";
}
}
?>
When I run the script by selecting an option in the dropdown, nothing is happening. Does anyone know what is wrong with my script?
I am not sure you should query the database again for a value you already retrieved. Something like this should work:
jQuery( document ).ready(function() {
jQuery( "#product1" ).change(function(){
var name = jQuery( "#product1 option:selected" ).text().split('|')[1];
jQuery("#product11").val(name);
});
});
You don't need the javascript/jQuery command in the HTML

Sending Variable from php file to jquery file

I am trying to pass a php variable located in a php file to a separate JavaScript file. I'm trying to pass the variables at the end of the php file in the input functions into the jQuery variables called $message and $username.
Here is where I'm at so far:
chat.php
<?php
//form data
$username = $_POST['username'];
$password = $_POST['password'];
//sql server connection credentials
$servername = "localhost";
$serverusername = "suser11";
$serverpassword = "suser11";
$databasename = "chat_database";
// Create connection
$conn = new mysqli($servername, $serverusername, $serverpassword, $databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br /><br />";
$username = $conn->real_escape_string($username);
$password = $conn->real_escape_string($password);
$sql = "SELECT Salt FROM users WHERE Username='$username'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$salt = $row["Salt"];
}
$sql = "SELECT * FROM users WHERE Username='$username' AND Password=MD5('$password$salt')";
$result = $conn->query($sql);
if($result->num_rows === 0) {
$conn->close(); //close the db connection
header('Location: login.html'); //redirect to login.html
} else {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
}
// Close the database connection
$conn->close();
?>
<textarea id="myChat" type="text" style="width:500px; height:500px;"></textarea>
<br/>
<br/>
<input id="myText" name="myText"/>
<input type="hidden" value="<?php echo $username; ?>"/>
<button id="add">
<b>Add to chat</b>
</button>
</body>
</html>
Here is my jquery file
$(document).ready(function() { //start 1
//alert("hello world, jQuery is working");
setInterval(function(){$("#myChat").load("chat.txt")},100); //update the textarea with the text file contents every 10th of a second
var $message = '';
var $username = '';
$('#add').click(function(){ // start 2
var $message = $('#myText').val();
var $username = $('$username').val();
//alert("Got the message");
$.ajax({ // start 3
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
//success: function(r){ // start 4
//alert('Got it');
//}, // end 4
//error: function (xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError: " + err);
//alert ("Error: " + err);
//}
}); // end 3
$('#myText').val(""); //clears value of text box on click of button with id=add
}); // end 2
//forming proper xml
$xmlString ='<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlString += '<message><user>' + username + '</user><text>' + $message + '</text></message>';
}); // end 1
In php you can pass like:
Just replace your code:
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
with below code:
while($row = $result->fetch_assoc()) {
echo $row["user_id"]."||".$row["username"];
}
and in ajax:
$.ajax({
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
success: function(data){
details = data.split("||");
username = details[0];
password = details[1];
}
});

Uncaught ReferenceError: getPrice is not defined

I am trying to run a script. The script needs to show me data from the database. In my script I am using 1 dropdown and 1 textbox. When I change the selected value (product) in my dropdown it needs to show the price of the selected value. The price needs to be shown in the textbox.
The script is not working. I tried to figure out what the problem is. I used developer console tool of my browser. The developer console tool gives me the error:
Uncaught ReferenceError: getPrice is not defined | onchange # (index):1
Can someone help me with this problem?
The pages that I am using for this script are the following pages:
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo "<input type='text' value='";
echo json_encode($result['price']);
echo "'>";
}
else
{
echo "<input type='text' value='";
echo json_encode('no results') ;
echo "'>";
}
}
?>
First close <script> tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Your scripts tags should be before </html> and inside <body> tag :
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
The PHP condition could be simple and you don't need any json encoding, e.g:
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
Hope this helps.

Dynamically show SQL query on a PHP page on click, using AJAX

Basically, I want to retrieve a certain product after clicking on an element. I'm using AJAX to pass the variable, and PHP to display the SQL query. I will use the product id on a WHERE statement, to retrieve and display the correct product.
Here is part of my code so far:
<html>
<head>
<title>Left Frame</title>
<link href='http://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<link href="stylesheets/main.css" rel="stylesheet" type="text/css">
<script src="javascripts/jquery-1.11.2.js">
</script>
</head>
<body>
<div class="container">
<div id="bottomHalf">
<img id="blank" src="assets/bottom_half.png" style= "z-index: 5" >
<img src="assets/frosen_food.png"
usemap="#Map2"
border="0"
id="frozen"
style="z-index: 0;
visibility:hidden;" >
<map name="Map2">
<area shape="rect" coords="7,95,126,146" alt="Hamburger Patties" href="#" id="hamburgerPatties">
</div>
</div>
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(){
//display something if it succeeds
alert( hamburgerPatties );
}
});
});
</script>
</body>
</html>
Part of my PHP code:
<?php
$product_id =(int)$_GET['variable1'];
$servername = "************";
$username = "************";
$password = "*************";
$dbname = "poti";
$tableName = "products";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM $tableName ";
$result = $conn->query($sql);
// Display all products on the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
}
} else {
echo "0 results";
}
// Display product I clicked on the other frame
if (isset($GET['variable1'])) {
$sql = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = $conn->query($sql);
if ($result) {
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', "Product ID: " . $row["product_id"]. " - Product Name: " . $row["product_name"]. " Unit Price:" . $row["unit_price"]. "<br>";
echo '</tr>';
}
echo '</table>';
}
}
$conn->close();
?>
I'm able to display all the products. But starting from the ifsset statement, the code no long works. I get no error message or anything. How can I solve this? I'm pretty new to PHP.
EDIT: Ok, I managed to get the product I want when I hard code the product id. Now I need to get this variable using javascript.
You have syntax errors in your if statements.
When you're setting if, you should enclose the statement in braces:
instead of if something : do if(something): and then end it with endif; (when using colons :)
// Display product I clicked on the other frame
if (isset($GET['variable1'])):
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result):
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
endif;
endif;
Or, use {} braces instead of colons :
// Display product I clicked on the other frame
if (isset($GET['variable1'])){
$query = "SELECT * FROM $tableName WHERE product_id = " . $_GET['variable1'];
$result = mysqli_query($conn, $query);
if ($result){
echo '<table>';
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td>', $row['product_id'], '</td>'; // and others
echo '</tr>';
}
echo '</table>';
}
}
You have syntax error in if block. use {} for if block also use echo instead of pure html tag(table). This error prevents successful state of ajax request. also don't forget to close table.
if ($result)
{
echo '<table>';
while ($row = $result->fetch_assoc())
{
echo '<tr>';
echo '<td>', $row['product_id'], '</td><td>'; // and others
echo '</tr>';
}
echo '</table>';
}
and the ajax code to display php result instead of test alert would be this:
<script language="javascript">
$("#hamburgerPatties").click(function(){
var hamburgerPatties = "1002";
$.ajax({
type:"GET",
url: "topRightFrame.php",
data: "variable1=" + encodeURIComponent(hamburgerPatties),
success: function(data){
alert(data);
}
});
});
</script>

Categories