I can incorporate jquery ui autocomplete with source from database. How, I am trying to get the source from a prepared json file, the content is like this:-
{"data":[{"id":"1","country_name_en":"USA","country_name_hk":"\u7f8e\u570b"},{"id":"2","country_name_en":"China","country_name_hk":"\u4e2d\u570b"},{"id":"3","country_name_en":"British","country_name_hk":"\u82f1\u570b"}]}
I tried to modify the jquery codes as follow:-
<script>
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
alert(data);
})
}
});
</script>
but I think I do not written the format correctly. How shall I improve the way to extract the data from the json file?
The autocomplete won't show anything until you tell it to do so by calling the response function passed to your source method with the allowed autocomplete values. So you should do something like this:
$( "#country" ).autocomplete({
source: function(request,response) {
$.getJSON('../../database/country.json',{id: data.id},function(data){
var choices = [];
for(var i=0;i<data.data.length;i++) {
choices.push(data.data[i].country_name_en);
}
response(choices);
})
}
});
Also just a tip, you're going to confuse yourself by naming everything "data".
Ajax can be used for this refer this article which list countries from geonames.org(contains huge list country,state,regions). This will help you in some way.
To get data from json try this..
$("#country").autocomplete({
source: function(request, response) {
$.getJSON('../../database/country.json', { id: data.id }, function(data) {
$.each(data, function(key, value) {
alert(value.country_name_en); // json data
});
});
}
});
The problem is, you need to call the autocomplete callback from the ajax success handler.
$(function() {
$("#country").autocomplete({
source : function(request, response) {
$.getJSON('country.json', {
id : 1
}, function(data) {
var list = $.map(data.data, function(item, index) {
return {
id : item.id,
label : item.country_name_en
};
});
response(list);
})
}
});
})
Demo: Plunker
Related
I am trying to get JSON data from API on Laravel 5 , The route gives me correct
Data in the browser but when trying to access this route in JQuery it failed.
the route is:
http://localhost:8000/search/student/all
worked finally in the browser and the data is displayed in json format
but this script failed:
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
I replaced localhost:8000 with 127.0.0.1:8000 but nothing changed.
Note: I generated the json response using Laravel
$students=App\Student::all();
return response()->json($students);
In jquery you can do like something below
$.get( "http://localhost:8000/search/student/all", function(data ) {
var obj = jQuery.parseJSON(data);
console.log(obj);
});
Another possibility use jsonp
JSONP is really a simply trick to overcome XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)
$.ajax({
url:"http://localhost:8000/search/student/all",
dataType: 'jsonp',
success:function(data){
var obj = jQuery.parseJSON(data);
console.log(obj)
},
error:function(){
}
});
Basic example of using .ajax() with JSONP?
Try like this...
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://localhost:8000/search/student/all", function(result){
$.each(result.students, function(i, field){
$("div").append(field.name + " ");//name is database field name such as id,name,address etc
});
});
});
</script>
PHP
$students=App\Student::all();
echo json_encode($students);//or return $students->toJson();
I retrireve data from my MySQL database into a simple table. Above this table I should have a text-input. On entering a keyword into this input, I want to cancel all showing data in the table and display data, found by %LIKE% operator, matching the keyword entered.Something similar does jQueryUi Autcomplete, FooTable and a couple of Yii extensions, but I wanna do it all from scratch. Any ideas on how to do it? Links?
My knowledge:
$.ajax({
url: 'ajax/test.html',
success: function(){
alert('Load was performed.');
}
});
What I am going to give you is not the complete code.
You want to do it yourself so here is only the logic.
In you index.php file
<input type="text" name="autocoplete" id="autocomplete"/>
<div id="result"></div>
<script type="text/javascript">
$(document).on('keyup', '#autocompelte', function(){
var text = $('#autocomplete').val();
$.post('process.php', {text:text}, function(resultData){
//Treat your resultData and convert into HTML for example
$('#result').html(myHTMLResult);
}, 'json'); //I want my result as JSON
});
</script>
process.php
if(true === isset($_GET['text']) && false === empty($_GET['text']))
{
//Do your query where you field is like %$_GET['text']% : example : SELECT * FROM mytable WHERE myfield like %$_GET['text']%
//Store all your result in an array
//Format this array into json to be easy to treat with json
//Send this json back to your index.php file.
echo json_encode($listResult);
}
#ThinkTank thank you very much for the help. It works just fine. Here is my final code:
$(document).ready(function() {
$('#input').keyup(function(eventObject){
//cancel all displaying data in the table if keyword exists
if($(this).val()) {
//$("td").hide();
$("td").remove();
//data hid, now send data to server
var orgValue = $(this).val();
$.ajax({
url: '/products/RetrieveData',
data: 'term='+orgValue,
success: function(data) {
var jsondata=$.parseJSON(data);
$.each(jsondata, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
}
});
} else {
$("td").show();
}
});
} );
Just some ideas:
1. Once I find (filter out) what I need, I clear the input with backspace. How do I set the table to the initial state with the data?
I have a json response in the form of data with format like this. It is part of the whole data released
JSON Data Here
I have made a script to read the data :
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
for(var i=0; i<data[0].actionDetails.length;i++){
document.write('Judul Halaman : '+ data[1].actionDetails[i].pageTitle+"<br>");
document.write('URL : '+ data[1].actionDetails[i].url+"<hr>");
}
});
});
But the data generated using getJSON only 1, 2 or 5 data. While there are actually a lot of results generated process.
How do I capture all of the data generated??
I just wanted to take the pageTitle and url data from the data.
At first glance, you are mixing data[0] and data[1] (it will display all action details from the first item in the data array)
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
for(var i=0; i<data[0].actionDetails.length;i++){
document.write('Judul Halaman : '+ data[0].actionDetails[i].pageTitle+"<br>");
document.write('URL : '+ data[0].actionDetails[i].url+"<hr>");
}
});
});
If you want to display all action items in data
$(document).ready(function() {
$.getJSON('http://services.berthojoris.com/json/baca2.php', function(data) {
$.each(data, function(idx, item){
$.each(item.actionDetails, function(idx, actionDetail){
document.write('Judul Halaman : '+ actionDetail.pageTitle+"<br>");
document.write('URL : '+ actionDetail.url+"<hr>");
})
})
});
});
Also note, you may have to use $('body').append(string) instead of document.write(string)
So I have a problem with the following code. I have an array that is formatted:
{label:movie, value:location}
The following code will only show the label in the search box and when clicked uses that information to make the url. I need it to pass the value field from the array instead of the label. I've tried changing suggestions.push(val.label) to suggestions.push(val.value) at which point the clicking url works but the url shows in the searchbox instead of the label. I'm new to Jquery and Json so am really flying blind.
$(function(){
//attach autocomplete
$("#to").autocomplete({
minLength: 2,
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("/movie.php?callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.label);
});
//pass array to callback
add(suggestions);
});
},
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
},
});
});
You are close. You don't need the post-processing that you're doing in the success callback:
source: function(req, add){
//pass request to server
$.getJSON("/movie.php?callback=?", req, add);
},
The autocomplete widget can take an array of objects, as long as those objects have a label and/or value property.
Since you've supplied both in the result of your AJAX call, you should get the behavior you want by calling the add function directly as the success method of your AJAX callback.
i need some code for the next step..this my first step:
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
});
</script>
after matches..i want the result can connect to data base then show data from table inside <div id="value">...how to do that?
you can start here. $.ajax();
You should have some server side scripting knowledge also.
You will need to do it using an ajax call (matches will be a parameter for the call). The php script called through ajax will have to fetch the data and give it back to the calling page.
There you will need to parse the ajax response and display what you want.
A helpfull tutorial can be found here.
<script>
$("#mod").change(function() {
var barcode;
barCode=$("#mod").val();
var data=barCode.split(" ");
$("#mod").val(data[0]);
$("#seri").val(data[1]);
var str=data[0];
var matches=str.matches(/EE|[EJU]).*(D)/i);
$.ajax({
type:"post",
url:"process.php",
data:params,
cache :false,
async :false,
success : function() {
alert("Data have been input");
$("#value").html(matches);
return this;
},
error : function() {
alert("Data failed to input.");
}
});
return false;
});
</script>
and i change my process.php become:
select itemdata as version from settingdata where version = "tunerrange";