I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
Related
I want to build an array in PHP from SQL query and send it back via ajax to my JS file.
$id = clear(filter_input(INPUT_POST, 'id'));
$sql = 'SELECT * FROM `counties` WHERE `id`="'.$id.'"';
$query = mysqli_query($con, $sql);
$array = array();
while($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$name = $result['name'];
$array[] = array('id' => $id, 'name' => $name);
}
echo json_encode($array);
This is my code. In response I have always just one element. There's a lot of more. How could i do that correctly? I was browsing whole Internet and I didn't find anything useful... :(
$id = $_POST['id'];
$query = mysqli_query($con, "SELECT id,name FROM `counties` WHERE `id`='$id'");
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo json_encode($array);
this may simplified code
I'm trying to make a program that takes 5 words from a database randomly and inserts them into an array. The page initially loads as desired, but nothing happens after the button is clicked. None of the alerts are ever triggered, so the function must never be entered, but why is beyond me. Also, I get an error saying name isn't a legitimate index (referencing line 13) the first time I try running it on a browser, so advice about that would be great too.
lingo.php:
<?php
session_start();
if (empty($_POST["name"])):
$_SESSION["error"] = "You did not enter a name.";
header("Location: entername.php");
else:
$name = $_POST["name"];
setcookie("name", "$name", time()+3600);
endif;
?>
<html>
<head>
<b>Welcome to Lingo, <?php echo $_COOKIE["name"]; ?></b><br />
<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript" language = "javascript">
var arr = [];
function collectWords() {
$.post("getWord.php",
function(data) {
arr[word1] = $(data).find("Word1").text();
alert("function reached");
alert(arr[word1]);
arr[word2] = $(data).find("Word2").text();
alert(arr[word2]);
arr[word3] = $(data).find("Word3").text();
alert(arr[word3]);
arr[word4] = $(data).find("Word4").text();
alert(arr[word4]);
arr[word5] = $(data).find("Word5").text();
alert(arr[word5]);
});
}
</script>
</head>
<body>
<table id = "theTable" border = "1" class = "thetable"> </table>
<input type = "submit" value = "Start" onclick = "collectWords()">
</body>
</html>
getWord.php
<?php
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
if ($db->connect_error):
die ("Could not connect to db " . $db->connect_error);
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word1>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word1>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word2>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word2>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word3>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word3>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word4>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word4>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word5>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word5>";
else:
die ("DB Error");
endif;
?>
You get the error on $_COOKIE["name"]; because said cookie isn't set until you set it. You don't set the cookie until someone has entered their names, so on the first load it will give an error.
http://www.thesitewizard.com/php/set-cookies.shtml
"Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:"
Found under the header: "How to get the contents of a cookie.
Fix this with a shorthand if statement, like so:
<b>Welcome to Lingo,
<?php isset($_COOKIE["name"]) ? $_COOKIE["name"] : $_POST["name"]; //Checks if the cookie is set. If not, uses the $_POST name ?>! </b><br />
I have another question:
Why are your words requested 1 at a time? Why not get all 5 words in 1 query? Also, why send them back as XML data? Since you seem to be handling the data yourself, I would personally recommend a simple loop on the PHP side, returning it as a handy pre-made JSON array.
edit: Also important, PHP does not echo any content automatically. An AJAX call can only receive printed data. You need to echo your results at the end of your php script or you will return nothing
Like so:
$query = "select word from Words order by rand() limit 5";
$result = $db->query($query);
$rows = $result->num_rows;
$array = array();
if ($rows >= 1):
$i = 0;//start the wordcount
//While there are results, loop. (Results are limited to 5, so it won't loop more than 5 times)
while($row = $result->fetch_row()){
$i++;//Put this on top so it starts with "1"
$array["word$i"] = $row[0]; //create the array
}
echo json_encode($array); //Turn array into json and echo it.
else:
die ("DB Error");
endif;
Now, you will also need to change your Javascriptside a tiny bit.
This is how you will access the new array (created by php)
<script type = "text/javascript" language = "javascript">
function collectWords() {
$.post("getWord.php",
function(data) {
alert(data); // show whether you get any data back in the first place. thanks #jDo
var arr = $.parseJSON(data);
alert(arr.word1);
alert(arr.word2);
alert(arr.word3);
alert(arr.word4);
alert(arr.word5);
});
}
</script>
As you can see, this way saves you quite a lot of code and saves you a lot of word replacements
I am making a array from values from databse in PHP then storing it into javascript array. When I alert the array the single quotes are not visible, although when PHP is seen it shows the quotes around values. What’s wrong in my code? It should be ['1','2','3','4'] but it shows [1,2,3,4].
<script>
var values = [
<?php
$conn = mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs))
{
echo "'".$row['var1']."',";
}
?>
];
window.alert(values);
</script>
<script>
var values=[
<?php
$conn =mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs)){
echo "\'".$row['var1']."\',";
}?>
];
window.alert(values);
</script>
Use this , this may help you
<script>
$(function() {
var name = [
<?php
$Database = "database name";
$DatabaseUserName = "db_user";
$DatabasePass = "db_pass";
$connect = mysql_connect("~", $DatabaseUserName, $DatabasePass);
#mysql_select_db($Database) or ("Database not found");
$query = "SELECT ~ FROM ~";
$result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "\"". $row['~']."\", ";
}
// $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
mysql_close($connect);
?>
];
$( "#~" ).autocomplete({
source: name
});
});
</script>
Basically, I'm getting correct output except the closing PHP tag "?>" is included in the output when I don't want it to be. Is there a better way to do this?
Use json_encode() to output JavaScript safe data. For example...
<script>
<?php
// connect, query, etc
$data = [];
while ($row = ...) {
$data[] = $row['~'];
}
?>
var name = <?= json_encode($data) ?>;
</script>
Here's a simplified demo ~ eval.in
And of course, here's the obligatory "don't use the deprecated mysql extension, etc" addendum.
Run this code and check if it is still coming. I could not reproduce the error.
<html>
<head>
<script>
var name = [
<?php
$row=array("Volvo", "BMW", "Toyota");
for($i=0;$i<count($row);$i++) {
echo "\"". $row[$i]."\", ";
}
?>
];
</script>
</head>
<body>
</body>
</html>
Can someone help me with this? My sql code only works if I match only integers like 2=2 but if I change it to like this orange=orange it wont work...can anyone help me figure whats wrong with my code.
index.php:
<script type="text/javascript" src="jquery/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="jquery.jCombo.min.js"></script>
<form>
Caraga Region: <select name="region" id="region"></select>
Municipalities: <select name="town" id="town"></select>
Unique ID: <select name="uniq_id" id="uniq_id"></select> <br />
</form>
<script type="text/javascript">
$( document ).ready(function() {
$("#region").jCombo({ url: "getRegion.php" } );
$("#town").jCombo({ url: "getTown.php?townid=", parent: "#region", selected_value : '510' } );
$("#uniq_id").jCombo({ url: "getID.php?unqid=", parent: "#town", data: String, selected_value : '150' } );
});
</script>
getRegion.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Execute Query in the right order
//(value,text)
$query = "SELECT id, municipalities FROM regions";
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row[0], "value" => htmlentities($row[1]));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
// convert into JSON format and print
$response = isset($_GET['callback'])?$_GET['callback']."(".$data.")":$data;
echo $data;
?>
getTown.php:
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$townid = !empty($_GET['townid'])
?intval($_GET['townid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT town FROM towns WHERE tcode = $townid";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['town'], "value" => htmlentities($row['town']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
getID.php: The problem is in this code. It wont work if I match character to character it only works if its integer=integer.
<?php
// Connect Database
mysql_connect("localhost","root","");
mysql_select_db("klayton");
// Get parameters from Array
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
// if there is no city selected by GET, fetch all rows
$query = "SELECT uid, unq_pos_id FROM tb_uniqid WHERE tb_uniqid.uid = '$unqid'";
// fetch the results
$result = mysql_query($query);
$items = array();
if($result && mysql_num_rows($result)>0) {
while($row = mysql_fetch_array($result)) {
$option = array("id" => $row['uid'], "value" => htmlentities($row['unq_pos_id']));
$items[] = $option;
}
}
mysql_close();
$data = json_encode($items);
echo $data;
?>
(uid)field is stored with character values just like in the (town)field. I want to match it but it won't work.
Try to in getID.php replace:
$unqid = !empty($_GET['unqid'])
?intval($_GET['unqid']):0;
with:
$unqid = !empty($_GET['unqid'])
?$_GET['unqid']:0;
if you want to be able to match strings as well as integers. You see, intval() returns only the integer value of the variable, thus you strip of the other characters when you send a string to that page, and therefore you can't match anything with the code you had before.