jQuery autocomplete Redirection upon enter - javascript

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.

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);

Sorting jQuery's Autocomplete Results

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

Display tweets retrieved from database after onclick function

I am using JavaScript, PHP and HTML for my application. I have a SQL database that contains tweets. I need to query from database and display tweets after the keyword (connecting to a hyper tree) is clicked. I have researched and tried to include an external php file (generatetweets.php) inside myFunction() at index.php. However it's not working. Anyone can enlighten me or any reference for me to guide?
Thank you in advance.
Extracted example2.js, where child.name refers to the keyword from hyper tree
onComplete: function(){
//Log.write("done");
//Make the relations list shown in the right column.
//ONCLICK FUNCTION FOR KEYWORDS TO LOAD RELATED TWEETS
var node = ht.graph.getClosestNodeToOrigin("current");
var html = "<div><b>Keyword: " + node.name + "</b></div>";
html += "<ul>";
node.eachAdjacency(function(adj){
var child = adj.nodeTo;
var childName=child.name;
html += '<a onClick="myFunction('+'''+child.name+'''+')"><li>'+child.name + '</li></a>';
});
html += "</ul><br />";
$jit.id('inner-details').innerHTML = html;
}
generatetweets.php
<?php
// connect to the database
include "mysqli.connect.php";
// create your SQL statment to retrieve everything from
// the users table
$sql = "SELECT * FROM post WHERE content LIKE '%school%' ORDER BY date DESC";
// run the query
$result = $mysqli->query($sql);
// check for error
if ($mysqli->errno)
{
error_log($mysqli->error);
echo "<br />Something's wrong";
exit();
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<head>
</head>
<body>
<?php
// Check if there are records in the first place
if ($result->num_rows < 1)
{
echo "<h3>No records found</h3>";
}
// Iterate through the records
$counter = 0;
// Use fetch_array to get rows returned one at a time
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
?>
<table>
<tr id="tweetlist">
<td style="width:50px">
<!-- name goes here -->
<!--<img id="img<?=$counter?>" style="padding-right:5px" src="<?=$row["displaypicture"]?>"></img>-->
</td>
<td>
<!-- email textfield goes here -->
<span id="date<?=$counter?>" style="color:#CCFF33">[<?=$row["date"]?>] </span>
<span id="name<?=$counter?>">#<?=$row["username"]?>: </span>
<span id="emailTxt<?=$counter?>"><?=$row["content"]?> <span/>
</td>
</tr>
</table>
<br/>
<?php
$counter++;
}
$result->free();
$mysqli->close();
?>
</body>
Extracted index.php, to display tweets in div "demo"
<body onload="init();">
<!-- Header -->
<div id="header" class="container">
<!-- Logo -->
<h1 id="logo">Mood</h1> <!-- logo from style-n1.css -->
<div id="center-container">
<div id="infovis"></div>
</div>
<div id="right-container">
<div id="inner-details"></div>
<div id="log"></div>
<div id="node_name"></div>
<div id="demo" style="padding-left: 50px">
<script type="text/javascript">
function myFunction() {
$("#demo").load("generatetweets.php");
}
</script>
</div>
</div>
</div>
</body>
Hypertree is referenced from http://philogb.github.io/jit/static/v20/Jit/Examples/Hypertree/example2.html
I obtained tweets using nodejs and append it to div. Here is my code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
#<input type="text" id="tag" class="hash"/>
<button>submit</button>
</form>
<div id="tweets"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="/socket.io/socket.io.js"> </script>
<script>
var socket = io.connect("link to nodejs");
var link;
var tag;
var a;
function debounce(func, wait, immediate){
var timeout;
return function(){
clearTimeout(timeout);
timeout = setTimeout(function() {
timeout = null;
if (!immediate) func.apply();
}, wait);
if (immediate && !timeout) func.apply();
};
};
var func = debounce(function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
},1000);
$('.hash').keypress(func);
$('.hash').on('change',function(){
$('#tweet').html("");
socket.emit('message', $('#tag').val());
tag=$('#tag').val();
link="http://twitter.com/hashtag/"+tag;
a="<a href="+'link'+" target='_blank'> #"+tag+"</a>";
});
socket.on('message', function(msg){
console.log(msg.length);
$('#tag').val('');
var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig ;
var hashregex= /(#[a-z0-9][a-z0-9\-_]*)/ig;
console.log(link);
for(var i = 0; i < msg.length; i++){
msg[i].tweettext=msg[i].tweettext.replace(hashregex,a);
msg[i].tweettext=msg[i].tweettext.replace(regex, "<a href='$1' target='_blank'>$1</a>");
$('#tweets').after('<div>UserName: ' + msg[i].username+ '</div>');
$('#tweets').after('<div>Text: ' + msg[i].tweettext+ '</div>');
$('#tweets').after('<div>Time: ' + msg[i].timedate+ '</div>');
$('#tweets').after('<br></br>');
}
});
</script>
</body>
<html>

Checkbox value insert into MySQL

Here is what my front end looks like. I have created checkbox for email on and off, and I would like to store this ON/OFF information in MySQL.
This is my PHP code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Better Check Boxes with jQuery and CSS </title>
<link rel="stylesheet" type="text/css" href="css123/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.tzCheckbox123/jquery.tzCheckbox.css" />
<script src="jquery123.js"></script>
<script src="jquery.tzCheckbox123/jquery.tzCheckbox.js"></script>
<script src="js123/script.js"></script>
</head>
<body>
<div id="page">
<form method="post" action="">
<br>
<ul>
<li><label for="ch_emails">Email notifications: </label><input type="checkbox" id="ch_emails" name="ch_emails" data-on="ON" data-off="OFF" value="1" CHECKED/></li>
</ul>
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_POST['ch_emails'])){
echo $check=$_POST['ch_emails'];
$sql=mysql_query("Update scott123.rahul_tbl_users set group=$check where Dingoid=$dingo");
if($sql==1){
echo "Checked";
}
else{
echo "Not Checked";
}}}
?>
</body>
</html>
### And here is my Javascript code
(function($){
$.fn.tzCheckbox = function(options){
// Default On / Off labels:
options = $.extend({
labels : ['ON','OFF']
},options);
return this.each(function(){
var originalCheckBox = $(this),
labels = [];
// Checking for the data-on / data-off HTML5 data attributes:
if(originalCheckBox.data('on')){
labels[0] = originalCheckBox.data('on');
labels[1] = originalCheckBox.data('off');
}
else labels = options.labels;
// Creating the new checkbox markup:
var checkBox = $('<span>',{
className : 'tzCheckBox '+(this.checked?'checked':''),
html: '<span class="tzCBContent">'+labels[this.checked?0:1]+
'</span><span class="tzCBPart"></span>'
});
// Inserting the new checkbox, and hiding the original:
checkBox.insertAfter(originalCheckBox.hide());
checkBox.click(function(){
checkBox.toggleClass('checked');
var isChecked = checkBox.hasClass('checked');
// Synchronizing the original checkbox:
originalCheckBox.attr('checked',isChecked);
checkBox.find('.tzCBContent').html(labels[isChecked?0:1]);
});
// Listening for changes on the original and affecting the new one:
originalCheckBox.bind('change',function(){
checkBox.click();
});
});
};
})(jQuery);
I tried to write a code like this but the information email ON/OFF is not storing in database. I have created checkbox for email on/off, and I would like to store this ON/OFF information in MySQL, but the value is not getting stored.

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