Sorting jQuery's Autocomplete Results - javascript

I have a working autocomplete script that links to my database but I'm sure how to sort the results.
My table has 4 columns: ID, location, slug, population. The table itself has about 1,000 entries.
Currently, my autocomplete takes in user search for slug, and it will search for slugs but I would like the autocomplete list results to be sorted by population order, the higher population being highest on list.
Index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete using PHP/MySQL and jQuery</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<div class="header">
</div><!-- header -->
<h1 class="main_title">Autocomplete using PHP/MySQL and jQuery</h1>
<div class="content">
<form>
<div class="label_div">Type a keyword : </div>
<div class="input_container">
<input type="text" id="slug" onkeyup="autocomplet2()">
<ul id="list_id"></ul>
</div>
</form>
</div><!-- content -->
<div class="footer">
Powered by Jason's Fingers</a>
</div><!-- footer -->
</div><!-- container -->
</body>
</html>
script.js:
// autocomplete : this function will be executed every time we change the text
function autocomplet2() {
var min_length = 3; // min caracters to display the autocomplete
var keyword = $('#slug').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#list_id').show();
$('#list_id').html(data);
}
});
} else {
$('#list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// Changes input to the full name on selecting
$('#slug').val(item);
// Hides list after selection from list
$('#list_id').hide();
}
ajax_refresh.php:
<?php
// PDO connect *********
function connect() {
return new PDO('mysql:host=localhost;dbname=wallettest', 'root', 'butthead', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM population WHERE slug LIKE (:keyword) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$slug = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['slug']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['slug']).'\')">'.$slug.'</li>';
}
?>

You could set the "ORDER BY" part of $sql to be:
...ORDER BY population DESC LIMIT 0, 10"

Figured it out, in this line:
$sql = "SELECT * FROM country WHERE country_name LIKE (:keyword) ORDER BY country_id ASC LIMIT 0, 10";
Change Order by country_id to population

Related

jquery add 1 to variable on click then insert to database

I want to have 2 buttons on a page. If u click button "addMe", then I want to add 1 to a variable? (theCount). The other button (InsertDB) I want to add "theCount" into my db.
Im able to add data to my db, but not "theCount", probly because its a "div id" and I dont know how to do it. I have 3 files: index.php, addscript.js and insert.php
Here is my script:
index.php:
<?php
include "insert.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add 1 on click, then add sum to db</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<button id="addMe">Add 1</button>
<div id="theCount"></div>
<form method="post">
<button id="InsertDB">Add to DB</button>
</form>
</body>
</html>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"></script>
<script src="addscript.js"></script>
addscript.js:
var counter = 0;
$(document).ready(function() {
$("#InsertDB").click(function(){
var theCount= $("#theCount").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "theCount=" + theCount,
success: function(data) {
alert("Added to DB");
}
});
});
$("#addMe").click(function(){
counter++;
$("#theCount").text(counter);
});
});
insert.php:
<?php
include "db.php";
$theCount=$_POST['theCount'];
$sql = "INSERT INTO `mat`( `polse`)
VALUES ('$theCount')";
if (mysqli_query($conn, $sql)) {
echo "Craig is Satoshi";
}
else {
echo "Error";
}
mysqli_close($conn);
?>
#theCount is a <div>:
<div id="theCount"></div>
And a <div> doesn't have a value, so this won't work:
var theCount= $("#theCount").val();
Instead, get the text of the element:
var theCount= $("#theCount").text();
Much in the same way that you already set the text of the element:
$("#theCount").text(counter);

using ajax call to empty the div

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

Feed PHP parsed JSON data from MySQL to Morris.js Chart

Diving into a new project and trying to teach myself JSON,PHP,MySQL and Morris.js.
Some background into what I am trying to achieve.
I have a PHP file that goes out to a webpage and grabs JSON data. (Right now I just have it set to grab everything). Then with the data that it grabs it puts it into a mysql database. I have set a Cron job up right now to run this file every 1 minute, so that I can get some data flowing into this database.
<?php
//connect to mysql db
$con = mysql_connect('localhost','user','password',"") or die('Could not connect: ' . mysql_error());
//connect to the database
mysql_select_db('database', $con);
//read the json file contents
$jsondata = file_get_contents('http://192.168.10.243/j');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the device details
$id = $data['data']['id'];
$type = $data['data']['type'];
$detector = $data['data']['detector'];
$cpm = $data['data']['cpm'];
$temperature = $data['data']['temperature'];
$uptime = $data['data']['uptime'];
//insert into mysql table
$sql = "INSERT INTO database_table_1(id, type, detector, cpm, temperature, uptime)
VALUES('$id', '$type', '$detector', '$cpm', '$temperature', '$uptime')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
After this, I then use PHP again to parse the information out of MySQL into a JSON array. Right now it will parse all the MySQL data it has (which I'm not sure if this is a good thing right now or if I should figure out a way to just parse the most recent data from MySQL.) Let me know what you think.
<?php
//open connection to mysql db
$connection = mysqli_connect('localhost','user','password','database_table_1') or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from database_table_1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
array_push(
$emparray,
array(
'a' => $row['timestamp'],
'w' => $row['id'],
'x' => $row['cpm'],
'y' => $row['temperature'],
'Z' => $row['uptime']
)
);
}
// $emparray[] = $row;
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
Now if I was to run this PHP file by itself manually I would receive a lot of JSON data formatted just like this.
[{"a":"2015-08-17 21:34:01","w":"110000","x":"16","y":"28","Z":"112094"}]
Now my plan is to have this information update a chart or charts on a webpage using the morris.js charts. Here is my current index.html page with the PHP script and morris.js sections being near the bottom.
<!DOCTYPE html>
<html lang="en">
<!-- morris.js dependencies -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>Chart V0.1</title>
<!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul class="sidebar-nav">
<li class="sidebar-brand">
<a href="#">
Start Bootstrap
</a>
</li>
<li>
Dashboard
</li>
</ul>
</div>
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<div id="myfirstchart" style="height: 300px;"></div>
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<h1>Simple Sidebar</h1>
<p> This template has a responsive menu toggling system.</p>
Toggle Menu
</div>
</div>
</div>
</div>
<!-- /#page-content-wrapper -->
</div>
<!-- /#wrapper -->
<!-- PHP from Mysql to Json array -->
<?php
//open connection to mysql db
$connection = mysqli_connect('localhost','user','password','database_table_1') or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from database_table_1";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray[] = array();
while($row =mysqli_fetch_assoc($result))
{
array_push(
$emparray,
array(
'a' => $row['timestamp'],
'w' => $row['id'],
'x' => $row['cpm'],
'y' => $row['temperature'],
'Z' => $row['uptime']
)
);
}
// $emparray[] = $row;
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
<!-- Json Pull -->
<script>
Morris.Area({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on the chart.
data: <?php echo json_encode($emparray);?>,
// The name of the data record attribute that contains x-values.
xkey: 'a',
// A list of names of data record attributes that contain y-values.
ykeys: ['x'],
// Labels for the ykeys -- will be displayed when you hover over the chart.
labels: ['x-test']
});
</script>
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>
<!-- Menu Toggle Script -->
<script>
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
</script>
So far I have figure most of this new project, though I am currently stumped on how to take the data that I can parse from my PHP script and feed it to a morris.js chart or charts. I would like to have it so the chart or charts will update themselves every 1 minute for now and that the morris.js charts will get their data from my PHP script.
Any help, ideas, links, or best practices would help out a lot. My coding experience is little to none so I do apologize in advance.
Thank you
UPDATE:
I migrated the PHP script out of the HTML page and tried calling the PHP results via $.getJSON in the HTML page. Though I still am not able to get morris.js to use the parsed data. I dont even get a chart Any ideas?
<!-- Ajax -->
<script>
$.getJSON('export_php_test_1.php', function( data ){
Morris.Area({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on the chart.
data: data,
// The name of the data record attribute that contains x-values.
xkey: 'a',
// A list of names of data record attributes that contain y-values.
ykeys: 'x',
// Labels for the ykeys -- will be displayed when you hover over the chart.
labels: 'x-test'
});
});
</script>
You can use meta refresh. Following code will refresh the full html page automatically after 60 seconds.
<meta http-equiv="refresh" content="60">
If you want to refresh only the chart section, then you have to remove the inline php codes to a separate source, and use Ajax to fetch the data for morris. If you do so, then you can use JS function setInterval to run the Ajax in regular interval.

jQuery autocomplete Redirection upon enter

I have an Autocomplete that works perfectly but I'm having trouble figuring out how to re-direct the user to a separate web page containing info about his selection upon pressing ENTER on keyboard. The website itself doesn't have to exist, I just want to know the code for it assuming the website already exists.
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Autocomplete using PHP/MySQL and jQuery</title>
<link rel="stylesheet" href="css/style.css" />
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container">
<div class="header">
</div><!-- header -->
<h1 class="main_title">Autocomplete using PHP/MySQL and jQuery</h1>
<div class="content">
<form>
<p>Table consists of : ID, Location, Slug, Population </p>
<br><br>
<div class="label_div">Search for a Slug : </div>
<div class="input_container">
<input type="text" id="slug" onkeyup="autocomplet2()">
<ul id="list_id"></ul>
</div>
</form>
<br><br><br><br>
<p>List will be ordered from Highest population to lowest population (Top to bottom)</p>
<br><br>
</div><!-- content -->
<div class="footer">
Powered by Jason's Fingers</a>
</div><!-- footer -->
</div><!-- container -->
</body>
</html>
script.js:
// autocomplete : this function will be executed every time we change the text
function autocomplet2() {
var min_length = 3; // min caracters to display the autocomplete
var keyword = $('#slug').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#list_id').show();
$('#list_id').html(data);
}
});
} else {
$('#list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item) {
// Changes input to the full name on selecting
$('#slug').val(item);
// Hides list after selection from list
$('#list_id').hide();
}
function change()
ajax_refresh.php:
<?php
// PDO connect *********
function connect() {
return new PDO('mysql:host=localhost;dbname=wallettest', 'root', 'butthead', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = connect();
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM population WHERE slug LIKE (:keyword) ORDER BY population DESC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$slug = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['slug']);
// add new option
echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['slug']).'\')">'.$slug.'</li>';
}
?>
Listen for the keydown event, and check if the key pressed was the enter key, by checking the keycode.
input.on('keydown', function (ev) {
if (ev.keyCode === 13) { //enter's keycode is 13
//redirect code
}
});
You might also have to do ev.preventDefault() if the enter key would normally do something unwanted.

ajax form not finding javascript function

I can't seem to figure out what I'm doing wrong with this no matter how many things I try. I've looked through Google for a related issue but found nothing specific. Hopefully someone can help me.
The script runs through a external .js file calling a list of music albums, then listing the song of the album chosen via ajax. The user can then edit of delete the songs. Everything works fine until I submit the edited information through a form. When I click the submit button I get a web developer error "updateSong is not a function"
Here's the form:
<?php
include("database.php");
$song = $_GET['song'];
$query = "SELECT * FROM song INNER JOIN genre ON song.gID = genre.gID INNER JOIN album ON song.alID = album.alID WHERE sID = '$song'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("
<form action='#' method='POST' name='updateSong' onSubmit='updateSong(\"$song\")'>
<input name='songName' type='text' value='$row[songName]' />
<input type='text' id='genreSearch' name='genre' alt='Genre Search' onkeyup='searchSuggest();' autocomplete='off' value='$row[genreName]'/>
<div id='genre_search_suggest'></div>
<input name='songURL' type='text' value='$row[songUrl]' />
<input name='sID' type='hidden' value='$row[sID]' />
<input name='Submit' type='Submit' value='Update Song' />
</form>
");
}
?>
Here's the javascript:
function updateSong(sID) {
if(ajax) {
var song = sID;
alert("2");
ajax.open('get', './song_update.php' + encodeURIComponent(sID));
alert("3");
ajax.onreadystatechange = function() {
handleResponse(ajax);
}
ajax.send(null);
return false;
}
}
//EDIT//
Here's the page it's loaded into. I removed the unnecessary stuff around what this question is dealing with.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="artistPageStyle.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="javascripts/artistAjax.js"></script>
</head>
<body>
<div id="mediaPlayerBox">
<div id="artistAlbumList">
<?php
$query = "SELECT * FROM `album` INNER JOIN artist ON album.aID = artist.aID WHERE artist.LoginKey = '$token'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
echo ("<div id='artistAlbumBox'><div id='artistAlbum'><a href='#' onclick='loadAlbum($row[alID])'><img src='$row[albumCover]' width='75px' height='75px' border='0px' ></a></div><div id='artistAlbumLabel'>$row[albumName]</div></div>");
}
?>
</div>
</div>
</body>
</html>
Shouldn't it be: onSubmit='updateSong("$song")'?
try doing onSubmit='return updateSong($song)'
It's saying it is not a function because it isn't loaded, are you loading the external script in the display page at all?

Categories

Resources