How to display the result of my php in ajax - php

I want to do is display the result of my count.php in my index page. My plan is to auto count the number of rows of user_code and display the result in the index page everytime the page is visited or viewed.
My problem is that the ajax script doesnt recieve the result of count.php to display it in count inputbox on index page.
index page:
<input type="text" value="1" name="countValue" id="countValue" style="width: 12px;" /><br />
Count: <input type="text" name="count" id="count" readonly="readonly" /><br /><br /><br />
<script>
$(document).ready(function(){
var countTimer = setInterval(
function ()
{
codeValue();
}, 500);
var $count = $('#count');
function codeValue(){
$.ajax({
url:"count.php",
type:"GET",
data: { term : $('#countValue').val() },
dataType:"JSON",
success: function(result) {
$("#count").val(result.user_code);
}
});
};
});
</script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $_GET['term'];
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT user_code FROM students";
$query = $dbc->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows));
}
?>

Your problem
echo $_GET['term'];
This breaks the expected JSON format that your script is meant to produce. Also, you aren't even using any request parameters so I don't know why you'd even bother.
Here's your PHP, all cleaned up
<?php
try {
$dbc = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $dbc->query('SELECT COUNT(1) FROM students');
header('Content-type: application/json');
echo json_encode(['user_code' => $stmt->fetchColumn()];
} catch (Exception $e) {
http_response_code(500);
echo $e->getMessage();
}
I'd also suggest adding an error callback to your $.ajax options to handle HTTP errors.

i try your code and it works for my table i have (4) records! check your query if there is data
make sure you have jquery file in your header. I did not change anything your html file. I just create my own query on my table. then okay.

You need to create a div in indexfile and id of that div is provided in ajax file,so as to populate data form count.php in that div.
Here i will give you a similar type of example, Try it by making your related changes
index.php
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'count.php',
success: function(data) {
$('#content').html(data);
}
});
<script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$con=mysqli_connect($host,$user,$pass,$db);
$result = mysqli_query($con,"SELECT user_code FROM students");
?>
<table>//this table will be loaded in div
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['user_code']; ?></td>
</tr>
<?php
}
?>
</table>
You can also add autorefresh ajax script which will only reload only particular div after specific time interval(1 sec in below code) without reloading whole page
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#content').load('count.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>

Related

run a constant query against mysql using php without refreshing HTML page

Im looking at outputting mysql query results into a table on a php page where the 1st column of the table is the result and the 2nd column is populated with a Javascript timer
however my goal is to have it so that when data comes into the mysql database it display on the table and then when it stops being picked up by the query remove it from the table
the issue i face however is im not sure how to do this without resetting the javascript timer everytime the query is run,
I have gone through a couple of questions that have mentioned to use ajax and this would be fine but im not sure what i would put the HTML side
EDIT:
the below is now my second attempt code using ajax but i cant get the table to display it errors as unexpected token < line 27
my current page load Code to call the data is as followed:
PHP
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT
*
FROM
(SELECT
beacon,location,
COUNT(location) AS counter
FROM `track`
WHERE `date` = CURDATE() and `time` > NOW() - interval 60 second
GROUP BY beacon) AS SubQueryTable
ORDER BY beacon + 0 ASC;";
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML
$.get('vendor/fetch.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
(unexpexted token here)
<table id="table">
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr style="background-color: <?php echo $row['item.location'];?>">
<td><?php echo $row['item.beacon'];?></td>
<td> <span class='minutes'>00</span>:<span class='seconds'>00</span>
</td>
</tr>
<?php }
mysqli_close($con);
?>
</table>
});
});
function updateTable() {
//console.log('function called');
$.get('vendor/fetch.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
});
});
var updateTableInterval = setInterval(updateTable, 100);
};
</script>
</head>
<body>
<script>
var sec = 0;
function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function () {
$(".seconds").html(pad(++sec % 60));
$(".minutes").html(pad(parseInt(sec / 60, 10)));
}, 1000);
</script>
</body>

Getting value from database using jquery on change event

I have a list of rooms in a table along with their rent cost. Rooms are listed in a drop down menu, and I want to get rent in "input" field value, "on page load" as well as on "dropdown value change". I wrote following code, but somehow it is not working as expected. Can someone help me with this please?
<?php
define("HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "");
define("DB_NAME", "testdb");
$conn = mysqli_connect(HOST, DB_USER, DB_PASS, DB_NAME);
if (!$conn) {
die(mysqli_error());
}
$ajax = false;
$dbValue = 1; //or the default value of your choice - matched to the default selection value of the dropdown
if (isset($_GET['action']) && $_GET['action'] == 'ajax' && isset($_GET['dd'])) {
$dbValue = intval($_GET['dd']);
$ajax = true;
$res = mysqli_query($conn, "SELECT rent FROM `rooms` WHERE roomid = '$dbValue' limit 1");
$dataTable = '';
while ($data = mysqli_fetch_assoc($res)) {
$dataTable = $data['rent'];
}
}
// if ($ajax) return $dataTable;
?>
<html>
<head>
<title>jQuery Validation for select option</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
<select class="form-control" id= "roomid" name="roomid" required="">
<?php
$troom_sql = "SELECT roomid FROM rooms WHERE (isactive='y' AND isassigned='n' AND roomid NOT IN (SELECT roomid from roomalloc))";
$troom_rs = mysqli_query($conn, $troom_sql);
while ($troom_mem = mysqli_fetch_assoc($troom_rs)) {
?>
<option value="<?php echo $troom_mem['roomid']; ?>"><?php echo $troom_mem['roomid']; ?></option>
<?php
} ?>
</select>
<input type="text" placeholder="Monthly Rent" class="form-control" id="rent" name="rent" required>
<br>
</body>
<script>
$('#roomid').change(function()
{
var first = $('#roomid').val();
var req = $.get('getDB.php', {dd: first, action: 'ajax'});
req.done(function(data)
{
console.log("asdasd");
$('#rent').val("<?php echo $dataTable; ?>");
});
});
</script>
</html>
Though you've written both PHP and JS in the same file, you still need to return the data from PHP side and handle it in JS.
if ($ajax) return json_encode($dataTable)
from PHP side
dat = JSON.parse(data)
in JS
Crate a JQuery AJAX Function that takes the parameter for POST/GET Request and call that Ajax function on JQuery Event. The Ajax Function Should be like,
function LoadComponentPage( param ){
$.ajax({
type: "POST",
url: "./controller/ajax/component_paginate.php",
data: "page="+param,
dataType: "text",
success: function(resultData){
let section = $('#ComponentsListing');
section.empty();
section.html(resultData);
},
error : function(e){
console.log(e);
}
});
}
and call that function upon event as onclick="LoadComponentPage(param)". you can post process the result of call to show result or error something as shown in example function.

withdraw my information from sql using ajax&js, dont know what's worng

I am working on a chrome extension (freshment) and have a little problem.
I have a button, and I want that when button is clicked, to show my information from my database on my extension page.
HTML :
<button class="button" id="show" style="vertical-align:middle" onclick="myAjax()"><span>Show my purchaes</span></button>
<div id="showhere">
//this is where i want to show the info
</div>
Java Script :
$(document).ready(function(){
function myAjax() {
$.ajax({
url:"http://127.0.0.1/show.php",
data:{ action:'showhere' },
method:"POST",
success:function(data) {
('#showhere').html(data);
}
});
}
});
PHP :
<?php
if($_POST['action'] == 'showhere') {
$servername = "localhost";
$username = "root";
$password = "********";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ProductName, Amount, Date, WebStore FROM budget";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ProductName"]."</td><td>".$row["Amount"]."</td><td>".$row["Date"]."</td><td>".$row["WebStore"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
}
?>
What I want it to do is pretty simple : I have a button and below I have a div called : "showhere", and in this div I want to take mysql info and write it.
your write i didnt write the exact problem, the problem is that the button doesnt do anything.
agian , thx!
I suggest you set it this way:
$(document).ready(function() {
$('#show').on('click', function(e) {
e.preventDefault();
$.ajax({
url: "http://127.0.0.1/show.php",
data: {
action: 'showhere'
},
method: "POST",
success: function(data) {
('#showhere').html(data);
}
});
});
});

Interaction between jquery,MySQL and PHP to retrieve the result

I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}

PHP - How to get the selected item from dropdown menu populated from query before POST

I would like to know how do I get the selected name from a dropdown menu, being populated by a query using phpmyadmin, to display a picture according to the selection.
For example, if the users selects "Mountains" from the drop down menu I want to be able to use that value and make another query to get the specific image URL from the database and display it, and every time the user changes selection the image changes accordingly.
And yes, I know, mysql commands are deprecated.
If you need any more details let me know.
<select name='picker'>";
<?php
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql = "...";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] ."</option>";
}
$selectoption = $_REQUEST['picker'];
mysql_connect('localhost','root','');
mysql_select_db('...');
$sql3 = "...";
$image = mysql_query($sql3);
?>
<img src="<?php echo $image; ?>">
Create 2 Files
main.php
fetchimage.php
Note: Both files should be on same location, if root folder they look like this
main.php
fetchimage.php
if inside folder assuming folder name is alpha then
alpha/main.php
alpha/fetchimage.php
Now create main.php file and put following PHP and jQuery code in it.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root','');
mysql_select_db('...');
?>
<select name="picker" id="picker">
<?php
$sql = "SELECT * FROM table";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['name'];?>"><?php echo $row['name'];?></option>
<?php } ?>
</select>
//Here Show the Images
<div id="imged"></div>
jQuery
//JQuery library always comes first.
<script>
$(document).ready(function() {
$("#picker").change(function(){
var name=$(this).val();
alert(name); //This will show an alert when value selected, remove this **alert** in production mode, use it only in development mode.
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "fetchimage.php",
data: dataString,
cache: false,
success: function(data){
$("#imged").html(data);
}
});
});
});
</script>
More information about jQuery change function and Ajax Method
Bind #picker change function with <select>
Bind Ajax success function with id="imged" to display the image
Now create second file name fetchimage.php and put following code in it nothing else.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
mysql_connect('localhost','root',''); //Put Database Connection Here
mysql_select_db('...'); //Put Database Name Here
if(isset($_POST['name'])){
$selectoption = mysql_real_escape_string($_POST['name']);
$sql = "SELECT Image FROM table WHERE name = '$selectoption'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//This will show the image inside <div id="imged"></div>
echo '<img src="'. $row["Image"] .'" alt="" />';
}
?>
Side Note: keep in mind, mysql is deprecated, should start using mysqli now.
MySQLi (Procedural Example)
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
//Conntection Credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//Run Query
$sql = "SELECT imagename FROM table";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["imagename"];
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
OP requested an example code and provided other detail e.g (database) via email.
You can use ajax on select onchange event then change the content of the image.

Categories