In line 10, I have insert getSuggestion(q); for me to get results from my database but it does not work.
What should I put there in order for me to retrieve results from database while other codes remain the same?
This is my current code:
<html>
<script type="text/javascript" src="javascript/hogan-2.0.0.js"></script>
<script type="text/javascript" src="javascript/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="javascript/typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
<script type="text/javascript">
//document.getElementById("suggestion")
function getSuggestion(q) {
var ajax;
if(window.XMLHttpRequest)//for ie7+, FF, Chrome
ajax = new XMLHttpRequest();//ajax object
else
ajax = new ActiveXObject("Microsoft.XMLHTTP");//for ie6 and previous
ajax.onreadystatechange = function() {
if(ajax.status === 200 && ajax.readyState === 4) {
//if result are not there then don't display them
if(ajax.responseText === "")
document.getElementById("suggestion").style.visibility = "hidden";
else {
document.getElementById("suggestion").style.visibility = "visible";
document.getElementById("suggestion").innerHTML = ajax.responseText;
}
}
};
ajax.open("GET", "suggestion.php?q=" + q, false);
ajax.send();
}
</script>
</html>
Thanks in advance.
Replace
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
getSuggestion(q);
});
});
</script>
with this:
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
And that's all you need. Typeahead does the rest.
Query is in $_GET['q']
You can find my example here
My index.php looks like this:
<html>
<head>
<link rel="stylesheet" href="http://twitter.github.io/typeahead.js/css/main.css">
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.9.3/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.q').typeahead({
name: 'q',
remote: '/typeahead/suggestion.php?q=%QUERY',
minLength: 3, // start searching if word is at least 3 letters long. Reduces database queries count
limit: 10 // show only first 10 results
});
});
</script>
</head>
<body>
<input type="text" class="q typeahead tt-query" />
</body>
You dont need css file or classes to input. Only class "q" is needed.
<input type="text" class="q" />
And suggestion.php source:
<?php
$q = $_GET['q'];
echo json_encode(array($q));
?>
As you can see, whetever you currently search, it answers with the same result as you typed. You have to make database query and echo array with json_encode
Remember to add correct url to remote parameter.
EDIT: My example now gets data from itunes and searches for music videos. Edited source available in example.
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.
I have this code in my header.php :
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("a")
.filter(function() {
var href = jQuery(this).attr('href');
// return true if href exists and matches the regular expression
return href && href.match(/mywebsite\.com\/(page)\//);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
</script>
How can I make this code only work for users that are not logged in? (I'm using wordpress self-hosted)
Right now the code opens every '/page/*' in a new tab and makes it go through /te3/out.php but I would like that not to happen to logged in users.
I'm pretty new to this so please make it easy to understand.
Thanks a lot!
Simply put condition that if user is not logged in then use script else not.For that you can use is_user_logged_in.
<script type="text/javascript" src="/js/jquery.js"></script>
<?php
if ( !is_user_logged_in() ) :
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("a")
.filter(function() {
var href = jQuery(this).attr('href');
// return true if href exists and matches the regular expression
return href && href.match(/mywebsite\.com\/(page)\//);
})
.click(function(){
jQuery("a").attr("target","_blank");
url = jQuery(this).attr('href');
jQuery(this).attr('href','/te3/out.php?l=click&u=' + escape(url));
});
});
</script>
<?php
endif;
?>
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 load pages into a div , my question is i cant execute javascript code in page1.php.. How can i execute code when i load page in to div.. thanks for your help..
here is my codes
index.php :
<script language="JavaScript" type="text/javascript">
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#content").html(data).show();
});
}
</script>
Button1
Button2
<div id="content"></div>
load.php :
<?php
if(isset($_GET['contentVar']))
{
$contentVar = $_GET['contentVar'];
}else{
$contentVar = $_POST['contentVar']; }
if ($contentVar == "page1") {
include("page1.php");
} else if ($contentVar == "page2") {
include("page2.php");
}
and example for page1.php
<script type="text/javascript" src="nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });
</script>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
Data returned from Ajax is treated like plain text, so any Javascript within it is not executed by default. See this article.
Try using .load() instead of $.post() :
function swapContent(cv) {
$("#content").html('<img class="loader" src="images/loader.gif"/>').show();
var url = "load.php";
$("#content").load(url, {contentVar: cv});
}
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/"