Simple application php ajax not working [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I made a simple application php & ajax and I don't know why it is not working.
My code:
<?php
$grId = $_GET["groupId"];
$limit = $_GET["limit"];
if ($limit <= 0) {
$limit = 10;
}
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "productsdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $grId, $limit);
$stmt->execute();
$stmt->bind_result($id, $displayName, $role, $groupId);
$users = array();
while($stmt->fetch()) {
$user = new StdClass();
$user->id = $id;
$user->displayName = $displayName;
$user->role = $role;
$user->groupId = $groupId;
array_push($users, $user);
}
echo json_encode($users);
$stmt->close();
$conn->close();
?>
json-client-get.html:
<html>
<head>
<script src="jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$('#students').hide();
$("#getStudentsButton").click(function() {
$.ajax({
dataType: "json",
type: "GET",
url: "getStudentsJson.php",
data: {
groupId: 1,
limit: 7
},
success: renderTable
});
});
function renderTable(data) {
var trHTML = '';
$.each(data, function(i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.displayName + '</td><td>' + item.role + '</td> <td> ' + item.groupId + ' </td></tr>';
});
$('#students').append(trHTML);
$('#students').show();
}
});
</script>
</head>
<body>
Lista studentilor din grupul 1:
<div id="maindiv">
<table id="students" border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Role</th>
<th>GroupId</th>
</tr>
</table>
</div>
<input id="getStudentsButton" type="button" value="Load students" />
</body>
</html>
I craete in phpmyadmin a new database productsdb with the table user and a single value inserted.
When I run localhost/folder/json-client-get.html and press the button Load student nothing is happening.
EDIT(picture with my db but I don't know why the photo is not working)

I tested your code and there is an issue with SQL which you have:
$sql = "SELECT id, displayName, role, groupId FROM user where groupId = ? limit ?";
check table structure and ensure which you have these fields
for sure run this query in your phpmyadmin and see result
SELECT id, displayName, role, groupId FROM user where groupId = 1 limit 7

This answer will not solve your issue but simply show you how to debug your ajax call. I think you will benefit more from knowing how to solve it than getting it solved.
Take a look at the following ajax call:
$(document).ready(function(e) {
$.ajax({
url: 'ajaxScript.php',
type: 'POST',
data: {
'somevar': 'somevalue'
},
success: function(result)
{
alert('Successfully called');
},
error: function(exception)
{
alert('Exeption:'+exception);
}
})
})

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>

PHP MYSQL, Simple notification

can someone help me how to get rid the counts or number on notification after I read or open it... I hope you understand, sorry if its vague and to my bad English tho. Just here my sample codes..
/index.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
$('#notification_count').html(msg);
}
function waitForMsg(){
$.ajax({
type: "GET",
url: "select.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<span id='notification_count'></span>
Notifications
<div id="HTMLnoti" style="textalign:center"></div>
<br>
<p style="font-weight: bold; font-size: 20px; font-family: Tahoma;">Admin panel</p>
<form action="index.php" method="post">
<input type="text" required name="notification" autofocus="on" autocomplete="off">
<br>
<br>
<input type="text" name="status" value="unread" style="display: none;">
<input type="submit" name="btnsub" value="Submit">
</form>
and then my /select.php where why my notification counts..
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "messageTest";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * from messageTest where status = 'unread'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$conn->close();
?>
please! all I want is get rid of the counts on the notification after
the user open or read it. Thanks!
my database name = "messageTest" my database table =
"messagetest" inside my table =
id notification status
If you don't want to show the count if there are no unread values, you simply don't show it. Easy as that.
if ($count > 0) {
echo $count;
} else {
// Do nothing
}
You may also want to consider checking out some basic programming tutorials.
When you are displaying the notification count:
$count = $result->num_rows;
echo ($count > 0) ? $count : 0;
Now call the addmsg function only when the count is not == 0 meaning there actually are some unread notifications.
success: function(data){
if(data >0){ // unread notification
addmsg("new", data);
}
setTimeout(
waitForMsg,
1000
);
}
Now your notification link has a
onclick = "return getNotification()"
You would not need the return keyword. You can now have the ajax function as:
function getNotification(){
$.ajax({
type: "GET",
url: "notification.php",
success: function(data){
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
}
});
};
Now your notification.php should handle the update query by something like:
//Connection part
$sql = "UPDATE messageTest Set status = 'unread'";
$conn->query($sql);
echo 1;
$conn->close();
However, there is a lot more efficient way to handle this, just trying to fit the code you already have in place. You would not need separate pages for each ajax call. You can create all of them in a single file and create different functions. Try searching for php ajax notification example.

How to display data from database by getting inputs from user in php mqsql? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How to display data from database by user specified date range and also comparing user input value with database field value.
The query is like this:
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
assuming $date_min and $date_max are the values of your user input, and table the DB table where you want to query.
The php will be something like:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM table WHERE date between '".$date_min"' AND '".date_max"'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Provided you made the part for user input.
These is from http://www.w3schools.com/php/php_mysql_select.asp.
Some research before making a question is required.
Regards
Now, you could try something like this, using an ajax request (jQuery required):
JS:
/**
* Created by evochrome on 26-3-2016.
*/
$( document ).ready(function() {
var timer;
$('#reset').click(function(e) {
$('input').val(""); //set value equal to zero
});
$('input').on("input", function (e) {
clearInterval(timer);
timer = setTimeout(getTableContents,2000);//Execute function `getTableContents` after 3s
});
});
function getTableContents() {
$('td').fadeOut(500, function(){ $(this).parent().remove();});
setTimeout(function() {
var inputs = {};
$(".theader input").each(function () {
if ($(this).val() != '') {
inputs[$(this).attr('name')] = $(this).val();
}
});
$.ajax({ //ajax request
method: "POST",
url: "../php/fetch.php",
data: inputs,
dataType: 'json',
cache: false,
success: function (data) {
var tmpObject = {};
var i = 0;
data.forEach(function (row) {
var obj = data[i];
$('table').append("<tr id='t" + i + "'></tr>");
Object.keys(obj).forEach(function (key) {
$('#t' + i).append("<td style='display: none;'>" + row[key] + "</td>");
});
i++
});
$('td').fadeIn(500);
}
})
}, 500);
}
CSS:
table {
width: 80%;
}
td {
width: 40%;
background-color:green;
height: 40px;
text-align: center;
}
.theader{
width:100%;
justify-content:space-around;
display:flex;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>T-Test</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Input Some Data</h1>
<div class="theader">
<input name="FromDate" type="date"/>
<input name="ToDate" type="date"/>
<button id="reset">Reset</button>
</div>
<table>
<tr>
<td>2</td>
<td>John</td>
<td>Appleseed</td>
</tr>
</table>
<script src="js/jquery-2.2.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
PHP:
<?php
/**
* Creator: evochrome
* Date: 26-3-2016
* Time: 15:40
*/
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', '1');
$conn = new mysqli('localhost', $db_name, $db_password, $db_user);
if (! $conn){
echo 'Oh damn a crash!';
die(' Connection failed :(');
}
$fields = array(
'FromDate', 'ToDate'
);
$where = "1=1"; //true
foreach ($fields as $field) {
if ($value = $_POST[$field]) {
$where .= " AND $field = '$value'"; //for each field add clause
}
}
$query = $conn->query("SELECT * FROM $table_name WHERE $where"); //insert tablename and where clause
$array = array();
while($row = $query->fetch_assoc()){ //fetch from db
$array[] = $row;
}
echo json_encode($array);
$query->close();
$conn->close();

Displaying MYSQL table data dynamically through JSON, Jquery and PHP

I am trying to display the contents of a "users" table in my MYSQL database using PHP,JQUERY and JSON.
Here is the PHP file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ITSM";
$tableName = "signup_and_login_table";
include 'database_connection.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
On my HTML page i have a simple table im trying to target:
<table id="personDataTable">
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
This is the jquery ajax, I want it to loop through all the users and other table entities to display all the contents of the Database table on the page, Im currently just getting "undefined".
$(function ()
{
$.ajax({
url: 'CMGetdata.php',
data: "",
dataType: 'json',
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
console.log("test");
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
}
Any assistance to be pointed in the correct direction would be greatly appreciated thanks.
Try This-
$result =$con->query("SELECT * FROM tableName");
$array = $result ->fetch_all(MYSQLI_ASSOC);
foreach($array as $array)
{
$array['example'];
//another
}

jQuery keyup function stops working when trying to insert into a database

This is a weird problem and I'm not sure how to approach it.
At the moment I'm trying to have the user enter an ingredient - a list of ingredients appears as you type with buttons next to them to add them which should insert them into SQL database.
The list population ceases to function when I uncomment
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
In the .click function of the add button.
Which is strange because it's like the .keyup function just stops working.
<html>
<head>
<title>Cocktails</title>
<script src="http://assets.absolutdrinks.com/api/addb-0.5.2.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="ingredientinput" id="ingredientinput"><br>
</form>
<div id="ingredientlist">
</div>
<script>
$(document).ready(function(){
//ajax call to query cokctail DB
//handleData is callback function that handles result
function get_ingredients(query,handleData){
var apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
var rooturl = "http://addb.absolutdrinks.com/";
$.ajax({
type: "GET",
url: rooturl + "/quickSearch/ingredients/" + query + "/",
dataType: 'jsonp',
data: {apiKey:apikey},
success: function(data) {
handleData(data);
},
error: function(){
//error
}
});
}
//when text is entered - quicksearch the database
$("#ingredientinput").keyup(function(){
query = $(this).val(); //value of textbox
divlist = ""; //list of ingredients
objectlist = {};
if (query.length > 0){
//set loading image on keypress
$("#ingredientlist").html("<img src='images/spinner.gif' alt='loading' height='24' width='24'>");
//pass query to ajax call and handle result
get_ingredients(query,function(data){
console.log(data);
//build list of ingredients
$.each(data["result"], function(key, value){
divlist += "<div id='" + value["id"] + "'>" + value["name"] + "<button class='addbutton' type='button' id = '"+value["id"]+"'>+</button></div>";
objectlist[value["id"]] = value;
//clicking button dumps object to file?
});
$("#ingredientlist").html(divlist); //populate div ingredientlist with results
divlist = ""; //clear html builder
});
console.log("input query:" + query);
}
else{
$("#ingredientlist").html(""); //if no input clear list
}
});
$("#ingredientlist").on('click','button.addbutton',function(){
$("#ingredientlist").on('click','button.addbutton',function(){
current = objectlist[this.id];
sqlquery = current["description"] + "," + current["id"] + "," + current["isAlcoholid"] + "," + current["isBaseSpirit"] + "," + current["isCarbonated"] + "," + current["isJuice"] + "," + current["languageBranch"] + "," + current["name"] + "," + current["type"];
console.log(sqlquery);
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES ('test','test','test','test','test','test','test','test','test',)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
});
});
});
</script>
</body>
</html>
You can't just embed a save query from within javascript like you are doing. This is a server side function that needs to happen, and return a result (Almost like you're doing with your get_ingredients function.)
My suggestion, is create a save_ingredients function that works through ajax to pass the information (In this case, the ingredient to save) to the server.
in saveingredients.php:
<?php
$servername = "localhost";
$username = "root";
$password = "**";
$dbname = "ingredients";
$conn = new mysqli($servername, $username, $password, $dbname);
$description = filter_input(INPUT_GET, 'description', $_GET['description'], FILTER_SANITIZE_SPECIAL_CHARS);
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
$isAlcoholic = filter_input(INPUT_GET, 'isAlcoholic', FILTER_VALIDATE_BOOLEAN);
$isBaseSpirit = filter_input(INPUT_GET, 'isBaseSpirit', FILTER_VALIDATE_BOOLEAN);
$isCarbonated = filter_input(INPUT_GET, 'isCarbonated', FILTER_VALIDATE_BOOLEAN);
$isJuice = filter_input(INPUT_GET, 'isJuice', FILTER_VALIDATE_BOOLEAN);
$languageBranch = filter_input(INPUT_GET, 'languageBranch', FILTER_SANITIZE_SPECIAL_CHARS);
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$type = filter_input(INPUT_GET, 'type', FILTER_SANITIZE_SPECIAL_CHARS);
$sql = "INSERT INTO cocktails (description, id, isAlcoholic, isBaseSpirit, isCarbonated, isJuice, languageBranch, name, type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ( $stmt = $conn->prepare($sql) )
{
$stmt->bind_param('sdsssssss', $description, $id, $isAlcoholic, $isBaseSpirit, $isJuice, $languageBranch, $name, $type);
if ($stmt->execute($sql) === TRUE) {
echo json_encode('error' => false);
} else {
echo json_encode('error' => 'MySQL Error: ' . $conn->error);
}
}
$conn->close($conn);
?>
A sample AJAX function:
function saveingredients(current) {
$.ajax({
url: 'saveingredients.php',
data: {
description: current["description"],
id: current["id"],
isAlcoholid: current["isAlcoholid"],
isBaseSpirit: current["isBaseSpirit"],
isCarbonated: current["isCarbonated"],
isJuice: current["isJuice"],
languageBranch: current["languageBranch"],
name: current["name"],
type: current["type"]
},
success: function(res) {
if ( res.error )
{
console.log(res.error);
}
else
{
//Do something here because it inserted correctly.
}
},
failure: function(err) {
console.log(err);
}
});
}

Categories