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);
?>
Related
Currently, I made script, which after onclick event,sending question to the database and showing data in console.log( from array ). This all works correctly, but.. I want to show data from array in the different position in my code. When I try to use DataType 'json' and then show some data, then it display in my console.log nothing. So, my question is: How to fix problem with displaying data? Is it a good idea as you see?
Below you see my current code:
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
//console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "text",
data: {id:id},
success: function(data){
console.log(data);
}
});
});
});
:
public function GetPlayer($id){
$id = $_GET['id'];
$query = "SELECT name,surname FROM zawodnik WHERE id='".$id."'";
$result = $this->db->query($query);
if ($result->num_rows>0) {
while($row = $result->fetch_assoc()){
$this->PlayerInfo[] = $row;
}
return $this->PlayerInfo;
}else {
return false;
}
}
:
$info = array();
$id = $_GET['id'];
$vv = new AddService();
foreach($vv->GetPlayer($id) as $data){
$info[0] = $data['name'];
$info[1] = $data['surname'];
}
echo json_encode($info);
I think it would be better to change the line fetch_all in mysqli to rm -rf. That information in the DB is all obsolete, or completely not true.
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class="profile" data-id="1">Click</button>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$(".profile").click(function(){
var id = $(this).data('id');
console.log(id);
$.ajax({
method: "GET",
url: "../functions/getDataFromDB.php",
dataType: "json",
data: {id:id},
success: function(data){
console.log(data);
$.each(data, function(idx, item) {
console.log(item.surname);
});
}
});
});
});
</script>
</body>
</html>
PHP side:
<?php
class AddService {
public function GetPlayer($id) {
if (filter_var($id, FILTER_VALIDATE_INT) === false) {
return false;
}
$query = "SELECT name, surname FROM zawodnik WHERE id={$id}";
$result = $this->db->query($query);
if ($result->num_rows <= 0) {
return false;
}
// assumming you are using mysqli
// return json_encode($result->fetch_all(MYSQLI_ASSOC));
// or
WHILE ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return json_encode($data);
}
}
if (isset($_GET['id'])) {
$id = $_GET['id'];
$vv = new AddService();
// you don't need foreach loop to call the method
// otherwise, you are duplicating your results
echo $vv->GetPlayer($id);
}
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'];
}
im having a little problem, i have a form, with three fields, my problem is this one:
on the 2 and 3 input i get via javascript values for countries and cities, what i want to do is to make the city input throw the values from the country i have selected in the country input, heres the javascript
<script>
var availableTags = [
<?php
$sql = "select * from citys ";
$rsd = mysql_query($sql);
while($row = mysql_fetch_array($rsd))
{
$pid=$row['cid'];
$city=$row['city'];
$state=$row['state'];
?>
"<?php echo $city; ?>,<?php echo $state; ?>",
<?php } ?>
];
$( "#inputsearch21" ).autocomplete({
source: function( request, response ) {
var matches = $.map( availableTags, function(tag) {
if ( tag.toUpperCase().indexOf(request.term.toUpperCase()) === 0 ) {
return tag;
}
});
response(matches);
}
});
</script>
and the country script is the same, changing the php for country database.
i know i have to get the country id from the first form and in the second query i should be "select * from citys where countryid="$countryid"
any idea how to do this?
Probably the best thing to do is to work with an cobmination ajax and json. Then It should be something like this.
getCities.php
<?php
/* your connection ofc. */
$con = database_connection();
/* example unsecure please use PDO */
$sql = "SELECT ID, Name FROM City WHERE Country = '" . $_GET['country'] . "'";
$rsd = mysql_query($sql);
$res = mysql_fetch_array($rsd);
/* Return output in json format */
echo json_encode($res);
?>
Javascript
$.ajax({
type: "GET",
url: "getCities.php",
data: { country: "Germany" }
}).done(function( output ) {
/* Example for select inputs */
var cities = eval('(' + output + ')');
var length = cities.length;
for(var i = 0; i < length; i++)
{
var newOption = $('<option/>');
newOption.attr('text', cities[i].Text);
newOption.attr('value', cities[i].Value);
$('#ID-OF-SELECTBOX').append(newOption);
}
});
So I created an auto complete box using jQuery and PHP to pull the content from the database, and it's working fine, except when I go to type in the input box it pulls back all the results, instead of the results similar to what I'm typing.
So if you type Test it pulls back:
This
is
a
Test
Instead of displaying
Test
Here is my HTML
<input type="text" id="group_name" name="group_name">
Here is the jQuery I'm using
<script>
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream/group_names",
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
Here is my php page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
Recent Updates
New jQuery
<script>
var availableName;
$.getJson('/wuzhapnn/php/data_stream',function(response){
availableName = response;
});
$(document).ready(function() {
$( "#group_name" ).autocomplete({
source: availableName,
select: function(event, ui) {
$("#f").submit(); }
});
});
</script>
New PHP Page
if ($_GET['run'] == 'group_names') {
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
if (db_num_rows($result) > 1) {
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
} else {
}
echo json_encode(array_values(array_unique($group_names_array)));
}
You need to add LIKE clause.
"SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
because "SELECT group_name FROM groups" this will give all the result from database but you need only those who match with typed words so use LIKE MySQL clause.
Other Person Comment Response.
if you want to create json object before use it you can do it as below,
var availableName;
$.getJson('/wuzhapnn/php/data_stream/group_names',function(response){
availableName = response;
});
after this just use below code for autoComplete.
$( "#group_name" ).autocomplete({
source: availableName ,
Your PHP snippet doesn't actually use the value sent by the autocomplete plugin.
If you are using JQuery's plugin then the value send is a GET parameter called terms.
This needs to be included in your PHP.
$term = $_GET['term'];
You then need to include that in your query something like the following, but first please escape this value before using it directly in an SQL statement.
SELECT group_name FROM groups WHERE group_name LIKE %<term>%
Got it working right
New jQuery
<script>
$(function() {
$( "#group_name" ).autocomplete({
source: "/wuzhapnn/php/data_stream",
minLength: 2,
});
});
</script>
New PHP (thanks to Dipesh Parmar)
// pulls live data from database
$db = db_open();
$query = "SELECT group_name FROM groups WHERE group_name LIKE '%".$_GET['term']."%'";
$result = db_query($db, $query);
$result = db_fetch_all($result);
foreach ($result as $key=>$value) {
$group_names_array[] .= $value['group_name'];
}
echo json_encode(array_values(array_unique($group_names_array)));
I have a variable that I am retrieving upon a users button press (artist_id), which I am successfully getting. I would like to use this artist_id to find the artist name, which I have in a database. So far I have been unsuccessful exporting the artist name to the javascript as a varaible.
Here is the javascript/jquery:
<script>
$(function() {
$( "#dialog-modal" ).dialog({autoOpen: false, height: 250, width: 400, modal: true});
$( "#opener" ).click(function() {
$( "#dialog-modal" ).dialog( "open" );
$.get('/like_artist.php', {artist_id : $(this).data('artist_id'), stage_name : $stage_name}, function(data) {
alert("Data Loaded: " + data.artist_id);
var text = '';
var artistId = data.artist_id;
var stage_Name = data.stage_name;
text = 'You have liked ' + artistId + stage_Name;
$('#dialog-modal').text(text);
}, "json");
});
});
</script>
Here is the php (like_artist.php):
<?php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";
$current_user = current_user();
include_once("config.php");
$artist_id = $_GET['artist_id'];
$query_two = "SELECT stage_name FROM artists WHERE id='.$artist_id.'";
$stage_name = mysql_fetch_row(mysql_query($query_two));
$stage_name = $stage_name[0];
echo json_encode(array('artist_id' => $artist_id));
echo json_encode(array('stage_name' => $stage_name));
$user_id = $current_user['id'];
$query = "INSERT INTO `user_artists`
(`artist_id`, `user_id`)
VALUES
('$artist_id', '$user_id')";
$result = mysql_query($query);
?>
Thank you for the help!
You want to use JSON to bundle up your information in your PHP code and then parse it with JavaScript:
http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP
On a side note, you should also look into using Prepared Statements for your queries.
Edit: Here is a better link showing a simple demo:
http://www.caveofprogramming.com/php/php-json-an-example-javascript-json-client-with-php-server/