I am looking for a live search solution or jquery autocomplete using ajax to take data from a file (later from db)
Let's say i have this php file with data:
[
{ID: "1", "Name": "User 1"},
{ID: "2", "Name": "User 2"},
{ID: "3", "Name": "User 3"},
{ID: "4", "Name": "User 4"}
]
I found on the web this code it works but it scanns only wikipedia, how can i make is to scann my php file? http://jsfiddle.net/TzQJP/
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>Comperio Super Simple Instant Search</title>
</head>
<body>
<h1>Search Wikipedia!</h1>
<br />
<input id="searchterm" />
<button id="search">search</button>
<div id="results"></div>
<script>
$("#searchterm").keyup(function(e){
var q = $("#searchterm").val();
$.getJSON("http://en.wikipedia.org/w/api.php?callback=?",
{
srsearch: q,
action: "query",
list: "search",
format: "json"
},
function(data) {
$("#results").empty();
$("#results").append("<p>Results for <b>" + q + "</b></p>");
$.each(data.query.search, function(i,item){
$("#results").append("<div><a href='http://en.wikipedia.org/wiki/" + encodeURIComponent(item.title) + "'>" + item.title + "</a><br>" + item.snippet + "<br><br></div>");
});
});
});
</script>
<div style="position:absolute;bottom:0;right:0;text-align:right">
Fergus McDowall 2012<br>
<br>
</div>
</body>
</html>
By change "http://en.wikipedia.org/w/api.php?callback=?" path to your PHP file path you can accomplish it. Make sure that your JSON result it correctly formatted and a valid one.
Don't just take code snippets from the internet and use it. At least get an idea what it does. It may help you to extend the code as you want.
Why not use: http://jqueryui.com/autocomplete/
example from the same website:
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C"
];
$( "#tags" ).autocomplete({
source: availableTags //OR path to your PHP script
});
});
and you can have path to your PHP script instead of availableTags in source that returns
echo json_encode($array_of_items);
If you still want to use the code you provided, make sure you do echo json_encode($array); on your PHP script since response ajax is expecting should be type of json
Related
i am trying to parse json data from remote URL using Jquery. My data is in below format:
[
{
"UserId": "5",
"Name": "Syed",
"Lat": "23.193458922305805",
"Long": "77.43331186580654",
"EmailId": "syedrizwan#ats.in",
"LocationUpdatedAt": ""
},
{
"UserId": "98",
"Name": "Michael Catholic",
"Lat": "23.221318",
"Long": "77.42625",
"EmailId": "michaelcatholic#gmail.com",
"LocationUpdatedAt": ""
}
]
i have checked the data in json lint and it says it is correct data format. when i try to run it on my HTML page , it returns a blank page. My HTML code is a below:
<html>
<head>
<title>Jquery Json</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results.Name);
});
});
</script>
</head>
<body>
</body>
</html>
I am trying to retrieve names from the json string
results is an array of items, so you have to consider which item you want.
Normally, you'd go over the array in a loop, in a fashion similar to that:
$.getJSON('http://localhost/fbJson/json.php', function(results){
for(var i = 0; i < results.length; i++) {
console.log(results[i].Name);
}
});
There is an array of objects, you can reach them directly by using the index
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results[0].Name);
});
If you wish to iterate over the array you can use $.each and pass the results into it
$.each(results, function(key, val) {
document.write(val.Name);
});
Your json format is correct.
Use this code to access name in first row array:
document.write(results[0].Name);
I'm trying to use autocomplete in jquery, and it works with the demo data, but I haven't been able to make it work with my own data source. I'm trying to write a mailer where the user just enters a few letters of a person's name, and the contacts database helps autocomplete so that the corresponding emails show up in the "To" field.
I've included the following files:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
My jQuery code in document.load is below:
$(function() {
function log( message ) {
$('#to').append(message);
console.log(message);
}
$( "#search" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item? ui.item.email : "NO" );
}
});
});
And my HTML is:
<div class='ui-widget'><input type='text' class='medium' id='search' /></div> <br />
To:<br />
<div class='ui-widget'> <textarea type='text' style='width:80%; height:24px;' id='to' class='ui-widget-content'></textarea></div>
The result of search.php is fine as far as json is considered, here's a sample of the output when the letters "Ahmed" are pressed:
[{"email":"saddi#yahoo.com","name":"Ahmed Qasim"},{"email":"aaaab#alangari.com.sa","name":"Ahmed Abbas"},{"email":"mokhlef#yahoo.com","name":"Ahmed Sahdi"}]
I know I'm getting this response from search.php because I check Firebug and see it, but it doesn't show up below the search input field... Instead, what does show up is just a stump of a list... as in the image below.
But this exact same thing worked as expected when I used the demo code here: demo Why doesn't the list show up properly? Is there a limit on how much data can be displayed? I've pasted only 3 entries from the JSON output I got, but there were tens.
I think keune has the correct diagnosis. If you don't want to change the output of search.php, you could do something like this:
$( "#search" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "search.php",
type: "POST",
dataType: "json",
data: { searchText: myQuery, maxResults: 10 },
success: function(data) {
var mappedData = $.map(data,
function(item) {
return {
label: item.name,
value: item.email,
id: item.email
};
});
response(mappedData);
}
});
}, ....
What you are returning from server contains email and name fields, jquery ui needs an value and label field.
[{"label":"Ahmed Abbas", value: "Ahmed Abbas"}]
label is what you see on autocomplete list, and value is the value you will get when you select an item.
I am trying to dynamically fetch the data from a PhP module, load it as JSON data into javascript and use this data to generate a Pie chart using HighCharts. The Pie chart is generating properly when I am using some static data but not loading when I am parsing JSON data and feeding that as input to the Highchart series object. I am sure this is something to do with the formatting of data while inputting to Highcharts but I am not able to figure that out for sometime now :( So thought would just reach out to you guys . I have attached the code here and the sample json output generated by the php module for your reference.
Sample JSON input generated from PhP module : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]. Need to parse this JSON input and feed as input to my HighCharts series object to generate a pie-chart showing "html" and "css" as pie-slices.
Any guidance would be appreciated.
Thanks.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Top Skills Analytics</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="highcharts.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2" align="center"><u><b><font size="4">Top Skills Analysis</font></b></u>
</td>
</tr>
<tr>
<td>
<div id="container" style="height: 500px; width: 500px; margin-bottom: 1em;"></div>
</td>
</tr>
</table>
<script type="text/javascript">
// Creates the HighChart using the dynamically generated data from PhP module
function loadCharts() {
// Parses the JSON data and returns an array of an array
var result = [];
// json from php is like : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]
$.getJSON('test.php', function (json) {
$.each(json, function (i, entry) {
result.push(entry.skill, entry.count);
});
});
//result = [["html",158],["css",134]]; --> this works
var options1 = {
"series": [{
"name": "Jobs",
"type": "pie",
"sliced": true,
"data": result, // works when populated with static value like [["html",158],["css",134]]
"pointWidth": 15,
"color": "#C6D9E7",
"borderColor": "#8BB6D9",
"shadow": true,
}],
"title": {
"text": "Top Skills Analytics"
},
"legend": {
"layout": "vertical",
"style": {
"left": "auto",
"bottom": "auto",
"right": "auto",
"top": "auto"
}
},
"chart": {
"renderTo": "container"
},
"credits": {
"enabled": false
}
};
var chart1 = new Highcharts.Chart(options1);
}
// Load the charts when the webpage loads for the first time
$(document).ready(function () {
loadCharts();
});
</script>
</body>
It works with static data because the count is an int
["html",158]
And it doesn't work with dynamic data because it returns a string count
{"skill":"html","count":"158"}
Notice the double quotes around the second code line?
You need to either cast your string to an int in php or in javascript before passing it to highcharts
And another thing, if you run the code highcharts should complain with an error
Uncaught Highcharts error #14: www.highcharts.com/errors/14
If you visit the link it basically says the same thing about strings.
There is another thing wrong with the code
[["html",158],["css",134]]
As you can see here we have an array of arrays and when we run your code with string to int parsing we get
["html", 158, "css", 134]
Notice the problem? We have an array of four elements.
What you need to do is:
result.push([entry.skill, entry.count]);
Push an array of two elements to the result variable and don't forget that count must be an int
Try this,
result.push([entry.skill, parseInt(entry.count)]);
I am using jquery autocomplete on a form and trying to do a simple echo of what is selected upon submitting a form entry to verify my data is being read correctly. I am receiving the following message:
Notice: Array to string conversion in C:\xampp\htdocs\New\search.php on line 4
Array
Search.php Contents:
<?php
$dest_name = $_GET["dest_name"];
echo ["dest_name"];
?>
Html contnts:
<body>
<form method="GET" action="search.php">
<div>
<input type="text" id ="destination" name="dest_name"/>
</div>
</form
</body>
autocomplete script
var destinations = [
{value: "49 Degrees North Ski Area",label: "49 Degrees North Ski Area",id: "1"},
{value: "Afton Alps",label: "Afton Alps",id: "2"},
{value: "Al Quaal Recreation Ski Area",label: "Al Quaal Recreation Ski Area",id: "3"},
{value: "Alpental",label: "Alpental",id: "4"},
{value: "Alpine Meadows",label: "Alpine Meadows",id: "5"},
];
$(document).ready(function() {
$("#destination").autocomplete({
source: destinations,
focus: function(event, ui) {
$("#destination").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#destination").val(ui.item.label);
$("#dest_id").val(ui.item.id);
return false;
}
});
$('#button').click(function() {
alert($("#dest_id").val());
});
});
In line 4 use have displayed the array index instead of that you have to echo the variable which you have declared in line 3.i.e.,
echo $dest_name;
On line 4 of your PHP file you are echoing an array (the square brackets can be used to create an array):
echo ["dest_name"];
If you want to echo the brackets, you need to wrap the entire line in quotes.
echo '["dest_name"]';
I have a simple web application in which I have created a wizard, each wizard page contains different form fields which are populated from database, as user presses next the page data is retrieved from server using Ajax call. Here is the code of the page which is retrieved from server against an Ajax call. I am making it simple to understand..
function printAdAlertWizardStep($step)
{
switch($step)
{
case 1: //step of wizard, first step
print "Welcome to alert wizard,...";
break;
case 2: //second step of wizard which contains the text field to which I want to attach autocomplete list.
?>
<table>
<tr>
<td>Keywords</td>
<td><!-- This is text field to which I want to attach autocomplete -->
<input id="nalertkw" name="nalertkw" size="10" type="text">
</td>
</tr>
</table>
<?php
break;
}
}
}
And the Java script code for attaching Autocomplete to keywords text field is
//Script will be executed when the page is ready for scripting
$(document).ready(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#nalertkw" ).autocomplete({
source: availableTags
});
});
Now the problem is that the form is loaded after the user presses next and the $(document).ready() function has fired already when the #nalertkw text field doesn't exists. So the autocomplete is not working. I am using Jquery-UI Autocomplete, How can I attach the autocomplete to a textfield which is loaded through Ajax call?
edit: Moreover I have tested my setup on a simple page (without Ajax call) with textfield and attaching the autocomplete to that text field the same way. It works absolutely fine. It confirms that autocomplete setup is correct, but it don't works when attached to a textfield which is retrieved through Ajax call.
Try hooking the event in Ajax call's :success handler, like this,
$.ajax({
url: "page.aspx/FetchEmailList",
data: "{ 'mail': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
$( "#nalertkw" ).autocomplete({
source: availableTags
});
}
}))
}
});
best solution I have found
$("#nalertkw").live("keydown.autocomplete", function(){ $(this).autocomplete({
source: availableTags
});
});
as soon as the text filed is clicked the autocomplete is attached to it... some one replyed this solution to my question, but has deleted his answer.. I only make little changes to his code and it starts working, so I decided to add an answer to help others. Thanks to you all for your suggestions. #Raghav, solution also looks good, and I think it will work also.. so upvote for you #Raghav. Thanks.
After the new page is loaded: run your autocomplete call. Something like:
jQuery.post('[url]', '[arguments]', function(data, status){
jQuery("[pageframe]").html(data);
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#nalertkw" ).autocomplete({
source: availableTags
});
}, "html");
This might be the same required action and it states that 'Ummar' solution is right as well.
Bind jQuery UI autocomplete using .live()