Jquery ui autocomplete php retrieve names - php

I'm trying to use the jquery UI autocomplete widget to retrieve names out of a mysql table in a php file (nameSearch.php)
It's not retrieving the results properly. Is there anything wrong with the Jquery I have here? Should it return results to the input with id 'tags'?
I'm getting the '$_GET['term']' variable in the php file which I understand is sent from the autocomplete request to the php file?
This is the Jquery code I have:
<script>
$("#tags").autocomplete({
source: "nameSearch.php",
minLength: 2
});
</script>
php
<?php
$namePart=$_GET['term'];
$names = array();
// Create connection
$con=mysqli_connect('localhost','root','admin','filmdatabase');
// Query Database
$result = mysqli_query($con,"SELECT name FROM actor WHERE name like '%".$namePart."%'");
$arr = '';
while($row = mysqli_fetch_array($result)){
array_push($names,$row['name']);
}
echo json_encode($names);
?>
Thanks for your help

Adding $(document).ready(function(){....});? as a wrapper solved the Problem

Related

Fetch data from database and display to a textbox using php and ajax

I'm creating a small project using php and jax, when I fetch data to database and display to a textbox using specific variable declared in may query it is working but when I try to use declared variable it is not working.
For example:
SELECT remaining FROM sys_stocks WHERE particulars='MONITOR' - Working Fine.
$particularslogs = $_POST['particularslogs'];
SELECT remaining FROM sys_stocks WHERE particulars='$particularslogs' - Not Working
What should be the problem?
Thank you in advance.
Here's what I tried so far.
PHP Code.
<?php
include_once('../connection/pdo_db_connection.php');
$particularslogs = $_POST['particularslogs'];
$database = new Connection();
$db = $database->open();
$query = $db->prepare("SELECT remaining FROM sys_stocks WHERE
particulars='$particularslogs'");
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $query->fetch()) {
echo $row['remaining'];
}
//close connection
$database->close();
?>
AJAX Code.
<script type="text/javascript">
$('#stocksdatelogs').on('blur', function(){
$.ajax({
type : "get",
url : 'function/remaining_stocks_fetch.php',
success : function(remaining)
{
$('#remaininglogs').val(remaining);
}
});
});
</script>
I expect the output will display the MONITOR remaining count into my database table which is 5 to a remaining textbox field using WHERE particulars='$particularslogs' and not WHERE particulars='MONITOR'.
You are not sending the data.
1 - send the data from ajax method to php file something like this.
url : 'function/remaining_stocks_fetch.php',
data: {particularslogs: your data field name},
2- You are using GET method so you need to change the method POST to GET, something like this.
$particularslogs = $_GET['particularslogs'];
OR
Change the type var in the ajax method, like this.
type : "POST",

Loading mysql rows from PHP into autocomplete jquery

<?php
$cuvant = (isset($_GET['cuvant']) ? $_GET['cuvant'] : '');
// the word I want to get from the search box
$sql = "SELECT cuvant FROM cautare where cuvant like'".$cuvant."%'ORDER BY nr_cautari DESC limit 0,6";
// I search for that word in a table from database
?>
<script>
$(function() {
var cuvinte=['<?php
$resursa = mysql_query($sql);
?>'];
$( "#cautare" ).autocomplete({
// #cautare is the id of the search box
source: cuvinte
});
});
</script>
I'm trying to make an auto-completer with jQuery, and I have this code in the index.php page. I don't know how to fix this issue: When I try to search something on the page, nothing happens.
Assuming that you are using jQuery Autocomplete: https://jqueryui.com/autocomplete/
I believe the variable that contains the values has to be valid JSON. Even doing an mysql_fetch_assoc() is going to return a php array that looks something like this for each row:
array(
'cuvinte' => "something"
);
So, assuming that there are multiple rows returned from your query, I think you would need to do something like this:
<script>
$(function() {
var cuvinte=
<?php
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$resursa[] = $row['cuvant'];
}
echo json_encode($resursa);
?>;
$( "#cautare" ).autocomplete({// #cautare is the id of the search box
source: cuvinte
});
});
</script>
Basically, this takes the result of your query, loops through all the rows, and builds a temporary array. The last step is to take that array and let PHP turn it into json for you.

How to set an Array in Javascript dynamically?

I am working on an e-commerce website. There is an array "products" in javascript defined by the following code
<script type="text/javascript">
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
/*some other javascript code*/
</script>
I want this array to be updated dynamically according to the number of rows returned by querying the database.
For example, suppose I query the database and 5 rows are returned. I want this array to be updated with those 5 rows. Please help me getting this done. I am using PHP, MySQL, Apache on Windows machine.
You want the push function: http://www.w3schools.com/jsref/jsref_push.asp
var products =
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"}
];
// Let's add a new phone:
products.push({"id":"3","title":"HTC Evo"});
/*
products now equals:
[
{"id":"1","title":"Apple iPhone 4"},
{"id":"2","title":"BlackBerry 9780 Bold"},
{"id":"3","title":"HTC Evo"}
];
*/
To account for the possibility you may have an existing array and you'd like to update it via ajax, you can do this dynamically with PHP:
<script type="text/javascript">
<?php foreach($phones as $phone): ?>
products.push({"id":"<?=$phone['id']?>","title":"<?=$phone['name']?>"});
<?php endforeach; ?>
</script>
The top answer to the question JSON encode MySQL results could achive this for you:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
In your case, replacing the last line with
?>
var products = <?php echo json_encode($rows); ?>;
<?php
would initialize the JavaScript object with your query results. This would need to be done before the page is loaded, because the PHP runs on the server producing the JavaScript for the client. If you need to get the results after the client page is loaded you would need a more complicated solution, probably using AJAX.
I would make a server side script that makes the connection to the database, get's the products, and constructs the JSON for you, so that way all you have to do is make an AJAX request to the script from the client side and it will return everything for you for use on your webpage.
You can use PHP to output json directly into the page.
Assuming that $data is an array that contains the products you want to output.
In the template you would do something like this:
<script type="text/javascript">
var products = <?php echo json_encode($data) ?>;
</script>
products[products.length] = {..some data..};
products.push({..some data..});
Or you need something else?

How do I use php to feed data to jQuery autocomplete?

I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...

Load Javascript array with MYSQL database data

suppose i have an javascript array "userName".I want to load it from a database table named "user".
Can anyone help with idea or sample code?
Thanks
You'll have to use the mysql_connect(), mysql_select_db() functions in PHP to connect to your db. After that use mysql_query() to SELECT the fields in your user table (if your user table has the fields name and id, SELECT name, id FROM user). Then you can fetch all infos from the db with mysql_fetch_assoc() or any other mysql fetch function. Now you need to echo your data into the javascript on your website, formatted as an array. This is complicated to get right, but you can get help from json_encode.
To fill your array with the user names, you'd do something like this.
<html>
<head>
<script type="text/javascript">
var userName = <?php
// Connect to MySQL
//mysql_connect();
//mysql_select_db();
$d = mysql_query( "SELECT name, id FROM user" ) or die( mysql_error() );
$usernames = array();
while( $r = mysql_fetch_assoc($d) ) {
$usernames[] = $r['name'];
}
echo json_encode( $usernames );
?>;
// Do something with the userName array here
</script>
</head>
Use ajax and php as an intermediate :
Define an empty JS array :
var myarray = new Array();
use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):
new Ajax.Request('myfile.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
Write your PHP code to grab data and print JS code (it must be valid javscript !) :
$i=0; $q=mysql_query('select ..');
while($row=mysql_fetch_array($q)){
echo "myarray[".$i."]='".$row['data']."';";
$i++;
}
You can check that your Js array contains data :
alert(myarray.length);
hope this helps.
This creates a global user variable in your page.
<?php
$user = /* get information from database the way you usually do */;
// $user == array('id' => 1, 'name' => 'foo', ...);
?>
<script type="text/javascript" charset="utf-8">
var user = <?php echo json_encode($user); ?>;
</script>
If you're looking for a dynamic AJAXy solution, follow some tutorials about AJAX.
The best way to do that simply is to get your data in your php code, and then "write" the javascript code to generate the array in php.
A short example would be :
echo "a = new Array();";
foreach($row in $results)
{
echo "a[$row[0]] = $row[1];";
}
My code could be quite incorrect, it's juste to give you a quick example.
You could also do that in a more elegant way, using json.

Categories