I am following a tutorial online (http://mycodde.blogspot.co.uk/2013/12/typeaheadjs-autocomplete-tutorial-ajax.html#comment-form) which invloves typeahead.js and a simple MySQL DB and I cannot get it to work.
Using typeahead.js v10.2 jQuery v1.9.1 and Bootstrap v3.2.0
I have included the necessary css and js files, I have also created a connection.php file, which successfully connects to my localhost db.
The problem is that the auto-suggest box doesn't auto-suggest anything. I am possibly doing something silly as I am new to js and programming.
I have included my files below if anybody would be kind enough to point me in the right direction I would appreciate it.
index.php
<!DOCTYPE>
<html lang="en">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<title>Typeahead.js Tutorial with Mysql Database</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
</head>
<body>
<input type="text" name="search" id="search"></div>
</body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/bloodhound.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/typeahead.bundle.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/typeahead.jquery.js"></script>
<script>
$("document").ready(function(){
$("#search").typeahead({
name : 'sear',
remote: {
url : '/connection.php?query=%QUERY'
}
});
});
</script>
</html>
connection.php
<?php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT first_name,last_name FROM actor");
while($row = $result->fetch_object()){
$user_arr[] = $row->first_name;
$user_arr2[] = $row->last_name;
}
mysqli_close($con);
?>
When I check the firebug console I get an Uncaught TypeError: undefined is not a function appears at line 22 which is;
$("#search").typeahead({
Can anybody lend some assistance?
Thanks
You need to add the following code in your .js file:
var search = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('sear'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: {
url: '/connection.php?query=%QUERY',
filter: function(list) {
return $.map(list, function(search) {
return {
name: sear
};
});
}
}
});
The json file contains an array of strings, but the Bloodhound
suggestion engine expects JavaScript objects so this converts all of those strings.
Check you jquery DOM Ready bind handler syntax here:
$("document").ready(...
It must be
$( document ).ready(...
Read more:
http://learn.jquery.com/using-jquery-core/document-ready/
Related
I wanted to perform jquery post to php and get the data and post to the console log. But however i cant find data on the console.log after performing post the data. my code is found below...........please help me...
student html page
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post("student.php",
{
PostLastName: "Abdullah",
PostLastReligion: "Muslim"
},
function(data)
{
console.log(data);
});
});
</script>
</body>
</html>
student.php script
<?php
if ((empty($_POST["PostLastName"])) && (empty($_POST["PostLastReligion"])))
{
//Return "Posted Values are empty" if the values is empty
$post_string = 'Posted Values Are Empty';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
else
{
//Return the Post Data
$post_string= 'Post Last Name = '.$_POST["PostLastName"]."\n".' Post Last Religion = '.$_POST["PostLastReligion"].'';
//echo "<script>console.log(".$post_string.");</script>";
echo $post_string;
}
?>
I have test your code. i think check first check your loaded jquery included in header.
After change some code like below mention and test your browser console.
<html>
<head>
<title>NEW AJAX GET</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script type="text/javascript">
showData();
function showData()
{
$.post( "student.php", { PostLastName: "Abdullah", PostLastReligion: "Muslim" })
.done(function( data ) {
console.log(data);
});
};
</script>
</body>
</html>
I hope u resolve u r issue.
The following code should add 100 to an existing number in a mysql table if the button gets clicked. If I click the button nothing happens, but if I reload the page the function adds 100 to the number. What is wrong with my code?
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
<?php
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
?>
});
</script>
</html>
You cant call PHP code from a jQuery function like that. All the php runs when the page loads and thats it. You can however use jQuery and Ajax to send a message to a php script that processes that message then returns a response. The script can even be in the same actual file like you have (or in a different file altogether) something like this would do:
<?php
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '123');
define('DBNAME', 'dbtest');
$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);
if(isset($_POST['updateTest']){
$val = $_POST['test'];
$id + $_POST['userId'];
// validate inputs and such....
mysql_query("UPDATE users SET test = (test + 100) WHERE userId=1");
// send success or error response...
echo json_encode(['success'=>true]);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.8/css/materialize.min.css">
</head>
<body>
<a id="button" class="waves-effect btn deep-orange darken-1">Button 1</a>
</body>
<script>
$("#button").click(function(){
var count = 100;
var userId = 1;
var dataObject= {updateTest: true, test: 100, userId: 1};
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataObject,
success: function(response) {
if(response.success){
alert('test worked');
}
else{
alert('there was an error')
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</html>
As mentioned by the previous poster PHP is server side and Javascript client side so what is actually happening is the following.
When the page is returned back to the user your piece of javascript just looks like the below..
Your MySQL statement here has executed already it can not interact with client side code in this way
<script>
$("#button").click(function(){
// nothing here.. But your MYSQL statement has executed anyway
});
</script>
I'm trying to scrape a web page, but getting some weird results in my browser's console (as seen below). Here's my code:
index.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Icefilms Searcher</title>
<script type="text/javascript" src="jquery-2.0.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="script.js"></script>
<div id="container" style="width:1100px;position:relative;"></div>
</body>
</html>
script.js
$(document).ready(function(){
var currNum = 168000;
var maxNum = 168005;
function generateNextUrl(){
currNum++;
return currNum-1;
}
scrapeThis(generateNextUrl());
function scrapeThis(theUrl){
$.ajax({
url:
"php.php",
data:
"icefilmsURL=" + theUrl,
success:
function(response){
var movieTitle = $(response).find("#videotitle").find("span:first").text();
$("#container").append("<a href='http://www.icefilms.info/ip.php?v="+theUrl+"' target='blank'>"+movieTitle+"</a><br>");
},
complete:
function(){
if(currNum < maxNum+1){
scrapeThis(generateNextUrl());
}
},
error:
function(xhr,err){
$("#container").append("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
$("#container").append("responseText: "+xhr.responseText);
}
});
};
});
php.php
<?php
echo file_get_contents("http://www.icefilms.info/ip.php?v=".$_GET["icefilmsURL"]);
?>
The code works fine, but this is what I see in my console:
Any ideas?
You are seeing those in the console because the page you are scraping contains references to relative paths.
That is to say rather than
<img src="http://www.icefilms.info/someimage.jpg">
The code is
<img src="someimage.jpg">
Therefore, when you grab and display their HTML on your own domain the browser is trying to load the image from your domain, localhost in this case. But you do not have the image on your server.
You can use a base href in the HTML to resolve this, or you could find and replace relative path images to include the domain.
<base href="http://www.icefilms.info/">
I am using the code below to graph data into flot, and when I print out dataOne, it returns properly formatted values for flot, however when I set it as the data for flot to graph, flot forms a graph but then has no data points?
<!DOCTYPE HTML>
<html>
<head>
<title>AJAX FLOT</title>
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<script language="javascript" type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
yaxis: {
min: "0",
max: "1023"
},
xaxis: {
mode: "time"
}
};
function update() {
$.ajax({
url: "http://localhost/data.php",
context: document.body
}).done(function(response) {
dataOne = response;
var d = "[" + dataOne + "]";
var plot = $.plot($('#placeholder'), [d], options);
setTimeout(update, 1000);
});
}
update();
</script>
</html>
Finally to the root of the problem. If it's valid JSON, dataOne must be an array of arrays:
[[1412393775000, 277], [1412393777000, 277], [1412393778000, 277]]
Note the extra brackets. Check your console.log carefully.
Doing this:
var d = "[" + dataOne + "]";
in JavaScript, automatically converts it to a string.
What you need is an array of array of array (the inner most is a point, the second is a series, the outer is a collection of series):
var d = [dataOne];
And then just
var plot = $.plot($('#placeholder'), d, options);
For those of you who may want to do something similar, here is the code I used to finally make it work. :)
First off, the page that produced the value the PHP file collected was incorrect. The Arduino was using AJAX to update the value every second, but I realised this was stupid as the page was called every second from the main AJAX call which called data.php which then called this page. So I removed the AJAX from the Arduino Web Server code.
Since the code was not working and I had spent hours trying I started to look around for alternatives. In highcharts.js I found some AJAX code, and decided to try it. Here is the code I ended up with:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>AJAX FLOT</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="javascript" type="text/javascript" src="../../jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="../../jquery.flot.time.js"></script>
</head>
<body>
<div id="placeholder" style="width: 100%;height: 600px;"></div>
<div id="div" style="width: 100%; height: 100px;"></div>
<script type="text/javascript">
var options = {
lines: {
show: true
},
points: {
show: true
},
xaxis: {
mode: "time"
}
};
window.setInterval(function(){
$.getJSON('http://localhost/data.php', function (csv) {
dataOne = csv;
var plot = $.plot($('#placeholder'), [dataOne], options);
});
}, 1000);
</script>
</html>
After that, I had to get the data.php working properly. I had a problem where
file_get_contents
Would not only get the output of the Arduino, but also many of the tags surrounding it. This stuffed up my data. So I gave up with the proper html tags and just printed out the plain value. So if you went to the page source of the Arduino's output, there are no tags surrounding the value, all you see is a number. So that stopped that issue.
Here is the php code I use to format the values:
<?php
$file = "data.txt";
$webpage = "http://192.168.1.177/";
$t = time() * 1000;
$current = file_get_contents($file);
$data = file_get_contents($webpage);
if ($current < "1") {
$current .= '[[' . $t . ', ' . $data . ']]';
file_put_contents($file, $current);
echo $current;
}
else {
$cut = substr($current, 0, -1);
$cut .= ', [' . $t . ', ' . $data . ']]';
file_put_contents($file, $cut);
echo $cut;
}
?>
To get the data into the appropriate brackets, you can see that when no data is present in the file, the if statement does not include a comma and space, because there is no other set of data to separate from. As soon as one value is in the file, I use substr to get rid of the last containing bracket, then append the comma, space and then values, with the containing bracket put again at the very end of the data where it should be.
Anyway, this ended up working like a dream. Thanks for everyones help :)
I am just new to XMPP, and I am making the first "HELLO" code. Please take your time look at the following code (the .zip is at the end of this topic):
<html>
<head>
<title>Hello - Chapter 3</title>
<style type="text/css">
body {
font-family: Helvetica;
}
h1 {
text-align: center;
}
.hidden {
display: none;
}
#log {
padding: 10px;
}
</style>
<script language="javascript" type="text/javascript" src="scripts/jQuery.js"></script>
<script language="javascript" type="text/javascript" src="scripts/jQueryUI.js"></script>
<script language="javascript" type="text/javascript" src="scripts/strophe.js"></script>
<script language="javascript" type="text/javascript" src="scripts/flXHR.js"></script>
<script language="javascript" type="text/javascript" src="scripts/strophe.flxhr.js"></script>
<link rel="stylesheet" href="hello.css"></link>
<script language="javascript" type="text/javascript">
var Hello = {
connection: null,
log: function(msg) {
$("#log").append("<p>" + msg + "</p>");
}
};
$(document).ready(function() {
$("#login_dialog").dialog({
autoOpen: true,
draggable: false,
modal: true,
title: "Connect to XMPP",
buttons: {
"Connect": function() {
$(document).trigger("connect", {
jid: $("#jid").val(),
password: $("#password").val()
});
$("#password").val("");
$(this).dialog("close");
}
}
});
$(document).bind("connect", function(ev, data) {
var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function(status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger("connected");
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger("disconnected");
}
});
Hello.connection = conn;
});
$(document).bind("connected", function() {
// Inform the user
Hello.log("Connection established");
});
$(document).bind("disconnected", function() {
Hello.log("Connection terminated.");
// Remove dead connection object
Hello.connection = null;
});
});
</script>
</head>
<body>
<h1>Hello</h1>
<div id="log"></div>
<!-- Login dialog -->
<div id="login_dialog" class="hidden">
<label>JID:</label><input type="text" id="jid">
<label>Pwd:</label><input type="password" id="password">
</div>
</body>
</html>
According to the document, and the code, it must either say "Connection establised" or "Connection terminated". But it doesn't. I tried to put alert("It runs to here!"); in every line of the code, and it still alert(). It doesn't alert anymore when I put it in bind("connected") and bind("disconnect"). So I guess the code can not run to there. I've never done it before, and there is rarely documents about this, so I don't know what to do now.
Question: Could you guys please take a look at it, and tell me what was wrong? I myself is still working on debugging it!
Extra information: These are what is in my web folder (I am afraid of missing javascript framework files). All js files are latest version.
index.html
scripts/
jQuery.js
jQueryUI.js
strophe.js
flensed.js
flXHR.js
flXHR.swf
flXHR.vbs
swfobject.js
updateplayer.swf
checkplayer.js
css/
Not important...
Here are my code, please take time to view it: http://xx3004.kodingen.com/XMPP
I would appreciate any view of help.
[x]
your code is alright,
the problem is in the URL provided to make the connection using Strophe.
var conn = new Strophe.Connection("http://bosh.metajack.im:5280/xmpp-httpbind");
Try to find the location of the server, otherwise install an xmpp server(vysper), locally on your machine, and change the URL as http://localhost:8080/bosh/
Also try to comment the flxhr inclusion.
If you are running Openfire on your localhost make sure
bosh_service_url = 'http://127.0.0.1:7070/http-bind/'
ie
var conn = new Strophe.Connection("http://127.0.0.1:7070/http-bind/");
And if you are running ejabberd on your localhost make sure
bosh_service_url = "http://127.0.0.1:5222/http-bind/"