I'm trying to get data from my database using ajax and php, but whenever I try to get it I get an error with ajax. Here is my code:
HTML
Here is my code where I request the php file.
<body>
<div id="wrapper">
<h2>Coffe Shop</h2>
<p class="bold">Drink orders:</p>
<ul class="orders">
</ul>
<p class="bold">Add an order:</p>
<p>Drink: <input type="text" id="name"/><input type="submit" id="submit"/></p>
<button id="refresh">CLICK ME</button>
</div>
<script>
$(function (){
$("#refresh").on("click", function() {
$.ajax({
type: "GET",
url: "data.php",
dataType: "json",
success: function(names){
$.each(names, function(name){
alert(name);
});
},
error: function(){
alert("error");
}
});
});
});
</script>
</body>
PHP
Here is my PHP file
<?php
$conn = mysqli_connect("localhost:8080", "root", "", "test1")
or die("Error with connection");
$sql = "SELECT ime FROM users;";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$names = array();
while($row){
$name = array(
"name"=> $row['ime']
);
$names[] = $name;
}
echo json_encode($names);
You have an infinite loop in your PHP. You're just fetching one row, and then looping over that same row. Since you never change $row in the loop, it never ends. It should be:
while ($row = mysqli_fetch_assoc($result)) {
$name = array('name' => $row['ime']);
$names[] = $name;
}
Once you fix that, the JSON you'll be sending will look like:
[{"name": "Some name"}, {"name": "Another name"}, {"name": "Fred"}]
In your Javascript, you're not accessing the name property. Change
alert(name);
to:
alert(name.name);
Or you could change the PHP so it just sends an array of strings instead of objects:
while ($row = mysqli_fetch_assoc($result)) {
$names[] = $row['ime'];
}
Related
I'm using a jQuery $.ajax method to fetch some data from a PHP script (card-data.php), and output it to a another PHP page.
When the jQuery runs, I receive an Internal Server Error, and when I console.log the xhr response I get this: [object Object]
Edit I can now view the entire xhr object thanks to #CBroe's comment
I've simplified and removed some "extra" code when posting here to simplify it a bit, but when I recreated my website with the code below I still got the same errors.
jQuery:
$(document).ready(function(){
const cardsHidden = $('#cards-hidden');
$.ajax({
url: '../../php/includes/card/card-data.php',
type: 'GET',
success: function(data){
cardsHidden.html(data);
},
error: function(xhr, status, error) {
console.log("AJAX error:", status, "Error:", error, "XHR:", xhr);
}
});
});
The PHP script (card-data.php):
<?php
$sql = 'SELECT username, name, age, FROM database ORDER BY RAND() LIMIT 3';
$result = $conn->query($sql);
if($result->num_rows > 0) {
$username = [];
$fullName = [];
$age = [];
while($row = $result->fetch_assoc()) {
$username[] = $row['username'];
$fullName[] = $row['name'];
$age[] = $row['age'];
}
} else {
echo '<p>No posts to show...</p>';
}
$conn->close();
?>
The PHP page (output page):
<?php include 'card-data.php'; ?>
<div id="cards-hidden" class="card-wrapper --center-align">
<?php
for ($i = 0; $i < 3; $i++) {
echo '
<div class="card'.$i.' card">
<div class="card__title">
<h5>'.$fullName[$i].', <span class="card__title--age">'.$age[$i].'</span></h5>
<p class="card__title--username">('.$username[$i].')</p>
</div>
</div>';
}
?>
</div>
I'm working on a live search and i need to transfer php data to ajax using json, but the problem is i can't pass an array contain 2 or more identical values, this is the php code:
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
}
}
}
}
?>
And this is the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data){
$('#feedback').html(json_data.name);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
So, if my array contain 2 or more identical names ajax wont get any data back, I hope someone have an answer.
You should create array with all results in your search function and then in ajax response loop results to get all names and print it separated by comma.
Search function
<?php
class search{
public function gettingvalues($search_value){
require_once('db_conx.php');
$dir = "http://localhost/usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
$results = []; //<!---
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json; //<!---
}
}
}
echo json_encode($results); //<!---
}
}
?>
Ajax
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var names = [];
$.each(json_data, function(index, element) {
names.push(element.name)
})
$('#feedback').html(names.join(','));
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Change this:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
echo json_encode($json);
}
To:
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json[] = array('img' => $img, 'name' => $name, 'username' => $username);
}
echo json_encode($json);
Inside your response for jQuery, retrieve your json data by looping it. Make sure to use var obj = jQuery.parseJSON( json_data ); before looping
I am trying to post a variable clicked by an user to a PHP script in order to run a query which will further extract information from the database. I am able to get the value that has been clicked by an user without any issue. However I believe it is not getting processed within the query hence why when I run it in Firebug it shows an empty response and HTML.
I think I need some changes with my test.php script or may be ajax part of index.php
Index.php
<?php
$test = $_GET['product'];
$q = "SELECT * FROM prdct_categories WHERE product = '$test' ";
$r = mysqli_query($dbc, $q);
$path_info = get_path();
$test1 = $path_info['call_parts'][1];
while ($list = mysqli_fetch_assoc($r)) { ?>
<li class="nav" <?php if ($test1 == $list['slugs']) { echo'id="actives"'; } ?>>
<a href="<?php echo $test;?>/<?php echo $list['slugs'];?> ">
<?php echo $list['subgroup'] . "(" . $list['contains'] . ")" . '<br/>'; ?>
</a>
</li>
<?php } ?>
</div>
<div class="col-md-4" id="testing"></div>
<script>
$(document).ready(function() {
$(".nav > a").click(function(e){
e.preventDefault();
$.post("test.php", { value:$(this).text() }, function(data) {
$("#testing").html(data);
});
});
//var classprod = $(this).text();
//$("#testing").text(classprod);
});
</script>
test.php
<?php
require('../config/connection.php');
if (isset($_POST['value'])) {
$value = $_POST['value'];
$query = "SELECT * FROM prdct_categories WHERE class = '$value'";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($result)) {
$prdct = print_r ($row['product']);
echo $prdct;
}
}
?>
remove "<br>" from
<a href="<?php echo $test;?>/<?php echo $list['slugs'];?> ">
<?php echo $list['subgroup']."(".$list['contains'].")".'<br/>';?></a>
and try
or try in js as
$.post("test.php", {value:(($(this).text()).trim())},
Change this:
$prdct = print_r ($row['product']);
To this:
$prdct = $row['product'];
Also change this:
$(".nav > a").click(function(e){
e.preventDefault();
$.post("test.php", {value:$(this).text()},
function(data) {$("#testing").html(data);});
});
To this:
$(".nav > a").click(function(e){
$.ajax({
type: "POST",
url: "test.php",
data: {value: $(this).text()},
success: function( msg ){$("#testing").html(msg);}
})
});
Guys i have a problem actually my php code is correct but i dont know why it display undefined into my client side script. Could somebody help me
here is my api.php this is where i put my php
<?php
$dbcon = mysqli_connect("localhost", "root", "", "orms") or die("Server not available" . mysql_error());
$data = array();
$result = mysqli_query($dbcon,"SELECT * FROM cottages") or die(mysqli_error()); //query
//$array = mysqli_fetch_row($result);
$data = array();
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
echo json_encode( $data ) //fetch result
?>
here is my client.php code
<?php
$dbcon = mysqli_connect("localhost", "root", "", "orms") or die("Server not available" . mysql_error());
?>
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"> </script>
</head>
<body>
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output"></div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', data: "POST", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var cot_id = row[0];
var image = row[1];
$('#output').append("<b>cottage: </b>"+cot_id+"<b> image: </b>"+image)
.append("<hr />");
}
}
});
});
</script>
</body>
</html>
Thanks for your help in advance..
You're using mysqli_fetch_assoc, so the row will be an associative array, which turns into a Javascript object. But in the Javascript code you're accessing row as if it's an array, not an object. You need to use the column names:
var cot_id = row.cot_id;
var image = row.image;
(I'm just guessing the column names, because you used SELECT * so I can't see the actual names in your table.)
arrayI am getting no search results from my mysql database using php.
PHP Code:
require_once "connectmysql.php";
$belongsto=$current_user->businessname;
$q = trim(strip_tags($_GET["term"]));
if (!$q) return;
$sql = "select clientname as value from zb_clients where clientname LIKE '%".$q."%' AND belongsto='".$belongsto."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['value']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;
}
echo json_encode($row_set);
JQuery Code:
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$("#search").autocomplete({
source: "../searchclient.php",
minLength: 1,
});
});
</script>
Input Field:
<input type="text" name="search" id="search" placeholder="Search for Business Name" />
I believe the php code is correct. If I run the php code on its own and use
/searchclient.php?term=a
as an example, it returns the results that I want in an array.
e.g. [{"value":"Hello World"},{"value":"East Meets West JV"}].
If I replace the Jquery line
source: "../searchclient.php",
with
source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ],
then the automocomplete works with that source. So there must be an issue with the array passing back into JQuery.
I cant quite put my finger on it. Am I missing something crucial?
Ive tried debugging with firebug but its not returning any errors.
Any help would be greatly appreciated!
Edited PHP Code:
require_once "connectmysql.php";
$belongsto=$current_user->businessname;
$q = $_GET["term"];
if (!$q) return;
$sql = "select clientname as value, idzb_clients as id from zb_clients where clientname LIKE '%".$q."%' AND belongsto='".$belongsto."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id']=htmlentities(stripslashes($row['id']));
$row['value']=htmlentities(stripslashes($row['value']));
$row['label']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;
}
echo json_encode($row_set);
Try this:
$("#search").autocomplete({
source: "../searchclient.php",
minLength: 1,
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li>").data("item.autocomplete", item).append("<a>" + item.value + "</a>").appendTo(ul);
};
I went down the AJAX route and this seemed to work:
HTML
$( "#search" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "../searchclient.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 1
});
SEARCHCLIENT.PHP
<?php
require_once "connectmysql.php";
$belongsto = $current_user->businessname;
$q = $_GET['q'];
$sql = "select clientname as value, idzb_clients as id, has_ledger_setup from zb_clients where clientname LIKE '%".$q."%' AND belongsto='".$belongsto."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = htmlentities(stripslashes($row['id']));
$row['value'] = htmlentities(stripslashes($row['value']));
$row['label'] = htmlentities(stripslashes($row['value']));
$row_set[] = $row;
}
header('Content-Type: application/json');
echo json_encode($row_set);
?>