get the data from database with ajax - javascript

i want to get the data from database through ajax but its gives me only one record not other but i want all the records from database i have search too much to understand the problem
but can't get that
that is database image
php code
//--------------------------------------------------------------------------
// Example php script for fetching data from mysql database
//--------------------------------------------------------------------------
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "search";
$tableName = "ajax01";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
//--------------------------------------------------------------------------
// 3) echo result as json
//--------------------------------------------------------------------------
echo json_encode($array);
?>
html
<!-------------------------------------------------------------------------
1) Create some html content that can be accessed by jquery
-------------------------------------------------------------------------->
<h2></h2>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
// var id = data[0]; //get id
// var vname = data[1]; //get name
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+name); //Set output element html
//recommend reading up on jquery selectors they are awesome
// http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>

You only ever get one row.
$array = mysql_fetch_row($result);
You need to loop that line and keep going until you run out of rows (creating an array of row arrays as you go).
Then json_encode that final array.

THe best way to do this, use 3 different files;
php_page.php
script.js
php_handler.php
In the php_page.php you have have actually the HTML
In the script.js you make the request with ajax
In php_handler.php you give the response and there you can make the connection and take all the data from your database that you need!
php_page.php
<!doctype html>
<html>
<head>
<title></title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<ul id="list">
<!-- In here comes the data! -->
</ul>
<button id="button">Get Data</button>
</body>
</html>
script.js
$(document).ready(function() {
$("#list").on("click", function() {
$.ajax({
url: "php_handler.php"
}).done(function(data){
$(this).empty().append("<li>"+ data +"</li>");
});
});
});
php_handler.php
<?php
$con = mysqli_connect($host, $user, $pass, $db);
$query = mysqli_query($con, "SELECT [FIELD_NAME] FROM [TABLE_NAME]");
foreach($query as $data)
{
echo '<li>' . $data . '</li>';
}
?>

The mysql_fetch_row takes only one record from result of query. You need to store each row of query result in an array, then finally convert the array to its JSON representation.
$records = [];
while( $row = mysql_fetch_row( $result ) ){
array_push( $records, $row );
}
echo json_encode( $records );
Substitute the mysql_fetch_row and json_encode lines of your code with this to achieve it.

Related

Using AJAX to get an SQL WHERE query into javascript

I am trying to pass a javascript variable into an SQL WHERE query and I keep getting null in return.
On-click of a button, the buttonClick function is ran:
<script>
var var1;
function buttonClick(elem){
var1 = elem.src //this gets the url from the element
var path = var1.slice(48); //this cuts the url to img/art/9/1.jpg
ajax = theAjax(path);
ajax.done(processData);
ajax.fail(function(){alert("Failure");});
}
function theAjax(path){
return $.ajax({
url: 'info.php',
type: 'POST',
data: {path: path},
});
}
function processData(response_in){
var response = JSON.parse(response_in);
console.log(response);
}
</script>
Here is the code stored in the info.php file:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$json = json_encode($result3);
echo $json
?>
As you can see, once I click the button, the buttonClick() function is ran and a variable stores the image path or src. That path variable is send to theAjax() function where it is passed to the info.php page. In the info.php page, the SQL WHERE query is ran and returned to the processData() function to be parsed and printed in the developer console. The value printed shows null.
Below is a picture of what I am trying to get from the database:
1.Check that path is correct or not? you can check inside jquery using console.log(path); or at PHP end by using print_r($_POST['path']);
2.Your Php code missed connection object as well as record fetching code.
<?php
if(isset($_POST['path'])){
$path = $_POST['path'];
$conn = mysqli_connect ('provide hostname here','provide username here','provide password here','provide dbname here') or die(mysqli_connect_error());
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'");
$result = []; //create an array
while($row = mysqli_fetch_assoc($result3)) {
$result[] = $row; //assign records to array
}
$json = json_encode($result); //encode response
echo $json; //send response to ajax
}
?>
Note:- this PHP query code is wide-open for SQL INJECTION. So try to use prepared statements of mysqli_* Or PDO.
mysqli_query() required 1st parameter as connection object.
$result3 = mysqli_query($conn,"SELECT itemName from images WHERE imgPath='$path'"); // pass your connection object here
I think your issue is that you're trying to encode a database resource.
Try adjusting your PHP to look like the following:
<?php
$path = $_POST['path'];
$result3 = mysqli_query("SELECT itemName from images WHERE imgPath='$path'");
$return_data = [];
while($row = mysqli_fetch_assoc($result3)) {
$return_data[] = $row;
}
$json = json_encode($return_data);
echo $json
?>

How to return array in php to $.ajax success function

I want to return a json array back to the calling $.ajax function, but I only get the last item of the expected array. Maybe I don't produce an array?
If I click the button with the id "btn_getAnswers" the "$("#btn_getAnswers").click" gets fired and the code of "DBCOMANSWERS" will be executed. I want "$result" in "DBCOMANSWERS" to be an array filled with the values of my MYSQL-Database. I return "$result" formatted as JSON. The returned result should append to the paragraph with the id "output". So far, that works fine, but I except three strings to be returned and appended to the paragraph, now just a single one, the last catched entry from the database, gets appended.
I dont really can see where i have to put a loop for appending or whatever. Is the returned $result maybe not an array just the last entry of database because it gets overwritten?
Index.html:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.12.3.js"></script> <!-- Import the jquery extension -->
<script>
$(document).ready(function () {
$("#btn_getQuestion").click(function () {
$.ajax({
type: "POST",
url: "DBCOMQUESTIONS.php?q=" + $("#input").val(),
success: function (result) { //Performs an async AJAX request
if (result) {
$("#output").html(result); //assign the value of the result to the paragraph with the id "output"
}
}
});
});
$("#btn_getAnswers").click(function () {
$.ajax({
type: "POST",
url: "DBCOMANSWERS.php?q=" + $("#input").val(),
success: function (result) { //Performs an async AJAX request
if (result) {
$("#output").append(result);
}
}
});
});
});
</script>
</head>
<body>
<p id="output">This is a paragraph.</p>
<input id="input"/>
<button id="btn_getQuestion">Question</button>
<button id="btn_getAnswers">Answers</button>
</body>
</html>
DBCOMANSWERS.php:
<!DOCTYPE HTML>
<head>
</head>
<body>
<?php
include("connection.php"); //includes mysqli_connent with database
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement
$query = mysqli_query($con,$sql); // get the data from the db
while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
$result = $row['answer'];
}
echo json_encode($result); // return value of $result
mysqli_close($con); // close connection with database
?>
</body>
<html>
You need to do 2 thing
remove html and add array collection. This is how your DBCOMANSWERS.php must be look like
<?php
include("connection.php"); //includes mysqli_connent with database
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_answers WHERE QID ='".$q."'"; //define sql statement
$query = mysqli_query($con,$sql); // get the data from the db
$result = [];
while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
$result [] = $row['answer'];
}
mysqli_close($con); // close connection with database
header('Content-Type: application/json');
echo json_encode($result); // return value of $result
?>
Then in your html as #madalinivascu suggests
success: function(result){ //Performs an async AJAX request
result.forEach(function(i,v){
$("#output").append(v.answer);
})
}}
try:
remove all html tags
and
include("ErrorHandler.php"); //includes error handling function
set_error_handler("ErrorHandler"); //set the new error handler
from the ajaxed php file, create a array of results and append each result to it
$result = []
while ($row = $query->fetch_array(MYSQLI_ASSOC)) { // fetches a result row as an associative array
$result[] = $row['answer'];
}
header('Content-Type: application/json');//change header to json format
In your ajax function you need to do a loop:
success: function(result){ //Performs an async AJAX request
result.forEach(function(i,v){
$("#output").append(v.answer);
})
}}
TRY:
$result = []
while ($row = $query->fetch_assoc()) { // fetches a result row as an associative array
$result[] = $row['answer'];
}
Reference:
http://php.net/manual/en/mysqli-result.fetch-array.php

Insert row with Ajax and then can't see new row with straight PHP in same page refresh

From a body onload event I get AJAX to insert a row into a database with PHP and then get PHP to read the row count number. Then only PHP is used to get a row count. The counts are shown by using DOM into 2 elements onto the page. The Ajax count is always 1 higher than the straight PHP count. What am I missing here?
The include('connect.inc.php') line returns a new mysqli connection into a $con variable.
index.php - Uses body onload event to start insertEvent function.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!doctype html>
<html lang ="en">
<head>
<meta charset="utf-8" />
<title>Query Test</title>
</head>
<body onload='insertEvent()'>
<a id='ajaxphp'; >AJAX + PHP Row Count:</a><br>
<a id='straightphp'; >Straight PHP Row Count:</a>
</body>
<script type="text/javascript">
function insertEvent()
{
$.ajax({
url: 'insertEvent.php',
type: 'post',
data: {'x': '1', 'y': '1'},
success: function(data) {
document.getElementById("ajaxphp").innerHTML= "AJAX + PHP Row Count: " + data;
}
});
var numrows = 0;
<?php
include('connect.inc.php');
$con = ConnectToDatabase();
$query = "SELECT * FROM events ORDER by id ASC";
if ($stmt = $con->prepare($query))
{
// execute query
$stmt->execute();
//Transfers a result set from the last query
$stmt->store_result();
// number of results returned
$num_rows = ($stmt->num_rows);
echo "numrows = $num_rows;";
}
mysqli_close($con);
?>
document.getElementById('straightphp').innerHTML = "Straight PHP Row Count: " + numrows;
}
</script>
insertEvent.php - PHP for AJAX call
<?php
include('connect.inc.php');
$con = ConnectToDatabase();
$x = $_POST['x'];
$y = $_POST['y'];
$query = "INSERT INTO events (x, y) VALUES (?,?)";
if ($stmt = $con->prepare($query))
{
// bind parameters for markers
$stmt->bind_param("ss", $x, $y);
// execute query
$stmt->execute();
//Transfers a result set from the last query
$stmt->store_result();
}
$query = "SELECT * FROM events ORDER by id ASC";
if ($stmt = $con->prepare($query))
{
// execute query
$stmt->execute();
//Transfers a result set from the last query
$stmt->store_result();
// number of results returned
$num_rows = ($stmt->num_rows);
}
mysqli_close($con);
echo $num_rows;
?>

PHP variable not being passed to AJAX call?

Im trying to get my PHP script called from AJAX (that is in my main php file).
Here's an example of what it is supposed to do: http://jsfiddle.net/xfuddzen/
The HTML source code shows only desk_box DIV being created (which is in my main.php). station_info DIV (being created in the display_station.php) is not there. How can I fix this? thanks in advance
Problem: DIVs from my display_stationinfo.php are not being created by using the AJAX call.
main.php with JQuery/AJAX part:
<div id="map_size" align="center">
<?php
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
?>
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$('.desk_box').each((function(){(this).click(function() {
var id = $(this).attr("data")
$("#station_info_"+id).toggle();
$.ajax({
url: 'station_info.php',
data: { 'id': id },
type: 'POST',
dataType: 'json',
success: function(json) {
$("#station_info_"+id).css({'left':json.x_pos ,'top': json.y_pos}).append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}//end success
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
$html = '';
if($station_result->num_rows > 0){
while($row = $station_result->fetch_object()) {
$id = $row->coordinate_id;
$html .= "<div class='station_info_' id='station_info_$id' style='position:absolute;left:{$row->x_coord}px;top:{$row->y_coord}px;'>Hello the id is:$id</br>Section:{$row->section_name}</br></div>";
}
}
else{
// no results - may want to do something with $html
$html = "no result given";
}
$station_result->free();
$conn->close();
echo $html;
?>
Why dont you filter the coordinate in the query? Like this:
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id = " . $_GET['coordinate_id'];
And in jquery code:
url: 'display_stationinfo.php?coordinate_id=' + id,
Let's start with your database connection, which should be on a separate secure page.
connect.php:
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Obviously, your host will not be 'host'.
Now main.php:
<?php
// only use for PHP on this page for initial page load - target other pages with AJAX
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>This is Where Your Title Goes</title>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script>
<script type='text/javascript' src='main.js'></script>
<link rel='stylesheet' type='text/css' href='main.css' />
</head>
<body>
<div id='map_container'>
<div id='map_size'>
</div>
</div>
</body>
</html>
Now for main.js:
//<![CDATA[
$(function(){
var ms = $('#map_size');
$.post('main_init.php', {init:'1'}, function(d){
for(var i in d){
var di = d[i], x = di.x, y = di.y;
var sti = $("<div class='station_info_' id='station_info_"+i+"'></div>").css({
left:x,
top:y
});
// HTML id, class, and name attributes cannot start with a number
$("<div class='desk_box' data='"+i+"'>id:"+i+'</div>').css({
left:x,
top:y
}).appendTo(ms).append(sti).click(function(){
var info = $(this).next();
$.post('live_info.php', {station_id:info.attr('id').replace(/^station_info_/, '')}, function(r){
// do stuff with r
info.html('love:'+r.love+'<br />hate:'+r.hate).toggle();
}, 'json');
});
}
}, 'json');
});
// use CSS to do `.desk_box,.station_info_{position:absolute;}`
//]]>
Now for main_init.php:
<?php
if(isset($_POST['init']) && $_POST['init'] === '1'){
include_once 'connect.php'; $db = db(); $json = array();
$q = $db->query("SELECT * FROM table WHERE"); // example only
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$json[strval($r->coordinate_id)] = array('x' => $r->x_coord, 'y' => $r->y_coord);
}
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// could be a hack
}
?>
Here's what live_info.php might look like:
<?php
if(isset($_POST['station_id'])){
include_once 'connect.php'; $db = db(); $json = array();
// example only - you will only get one `$row` if query is done specific, so while loop is not needed
$q = $db->query("SELECT love,hate FROM some_table WHERE id='{$_POST['station_id']}'");
if($q->num_rows > 0){
$row = $q->fetch_object();
// it's okay to overwrite array in this case
$json = array('love' => $row->love, 'hate' => $row->hate);
}
else{
// no results
}
$q->free(); $db->close();
echo json_encode($json);
}
else{
// may be a hack
}
?>

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories