how to populate the json data in select dropdown using ajax? - javascript

Actually i need to display the list of school in a dropdown using select tag so far i am getting the response through hard coded values now here is the problem not able to generate through a link i am getting the data from rest full service how to do that , any on please help
<html>
<head>
<meta http-equiv="content-type" content="application/json; charset=UTF-8">
</head>
<body>
<select id="sel"></select>
<script>
$(function() {
var data = [
{
"id": "1",
"name": "test1"},
{
"id": "2",
"name": "test2"}
];
$.each(data, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
});
})
</script>
</body>
</html>

You can use the getJSON method of jQuery
$('#brand').change(function(){
$.getJSON(
'your url to get json string',
'get parameters to send if any',
function(result){
//result would have your json string
//Empty the dropdown if it is having some items
$('#item').empty();
//Looping through all the json items
$.each(result.result, function(){
//Appending the json items to the dropdown (select tag)
//item is the id of your select tag
$('#item').append('<option>'+this['item']+'</option>');
});
});
});

Try this,
$(document).ready(function(){
getschool(val);
});
function getschool(val) {
$.ajax({
type: "GET",
url: 'http://localhost:8080/SMWS/Rest/parentService/parent/getSchoolDetails',
contentType: "application/json;charset=utf-8",
dataType: "json",
data:'school_id='+val,
success: function(data){
var html = '';
$.each(data, function(index,value){
html+= '<option value="'+value['item_value']+'">'+value['item']+'</option>';
});
$('#country-list').html(html);
}
});
}

Related

Jquery - Bootstrap DataTable Refresh issue DATA

Could you please assist me with this issue related to Bootstrap - Jquery Table?
I would like to retrieve data from a database server In JSON Format (through an ajax call) into a bootstrap DataTable and then reload the DataTable only.
Here you are the code, this will be run once pressed the click button (search):
var prova = null;
$(document).ready(function(){
prova = $('#prova_table').DataTable({
paging: true,
searching: false
});
prendivalori();
});
function prendivalori() {
$("#bottone").click(function() {
$("#prova_table").empty();
var sopravvissuti = $('#sopravvissuti').val();
var vita = $('#vita').val();
var provincia = $('#provincia').val();
var campi = $('#campi').val();
var table = $('#prova_table');
$.ajax({
type: 'GET',
url: './php/select.php',
data: {'sopravvissuti': sopravvissuti, 'vita': vita, 'provincia':provincia, 'campi':campi},
dataType: 'json',
success: function(data) {
table.append("<thead><tr><th class='th-sm'>Cognome</th><th class='th-sm'>Nome</th><th class='th-sm'>Sesso</th></tr></thead>");
console.log(data);
len=data[0].length;
table.append("<tbody>");
for(i=0; i< len; i++){
temp=data[0][i]
table.append("<tr><td>" + temp[1] + "</td><td>" + temp[0] + "</td><td>"
+ temp[2] +"</td></tr>");
}
table.append("</tbody>");
$('#prova_table').DataTable().ajax.reload();
}
,
error: function(data) {
alert('Assicurarsi di aver selezionato tutte le caselle');
}
});
});
};
Here you are the error message received once clicked button data...
DataTables warning: table id=prova_table - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The json data received from the server are correct because we can see them properly into the table but we are unable to use all the functions Bootstrap DataTable provides like Pagination search and number of entries....
I'm using all the updated links for running the website ..
ETC ECT
Here you are a JSON response:
Many thanks in advance for all you kind support
Have a nice day
Andrea
You should not do table.append() and any other direct dom changes on table.
Jquery data table will do this for you if you pass options to it in right way.
Do it this way.
First initialize the datatable like below with column names if available
var table = $("#myTable").DataTable({
data:[],
columns: [
{ "data": "Cognome" },
{ "data": "Nome" },
{ "data": "Sesso" },
{ "data": "data di nascita" }
],
});
in on click of button, do a get ajax call and in done callback clear the table table.clear().draw(); and table.rows.add(result).draw() to render data to the table.
$.ajax({
url: "https://www.mocky.io/v2/5e89289e3100005600d39c17",
type: "get",
}).done(function (result) {
table.clear().draw();
table.rows.add(result).draw();
})
JSFiddle : https://jsfiddle.net/k0d1mzgL/
var table = $("#myTable").DataTable({
data:[],
columns: [
{ "data": "Cognome" ,"title": "Cognome"},
{ "data": "Nome" ,"title": "Nome"},
{ "data": "Sesso" ,"title": "Sesso"},
{ "data": "data di nascita","title": "data di nascita" }
],
});
$("#getDataBtn").click(function(){
$.ajax({
url: "https://www.mocky.io/v2/5e89289e3100005600d39c17",
type: "get",
}).done(function (result) {
table.clear().draw();
table.rows.add(result).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
//if failed
console.log("Due to https issue,this request cant be made, go check jsfiddle link provided in answer");
});
});
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" >
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="myTable">
</table>
<button id="getDataBtn">Get data</button>

How To add another post name/variable inside ajax script

<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate="+$("#epdate").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
i have this code and i want to add another variable
inside ajax script adding another
data: "empname="+$("#empname").val(),
dopesnt work i hope someone would help me. thank you
and how can i call a postname or make a postname into session an call it into another php page?
Actually, there are multiple ways, either separate them using a & character.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate=" + $("#epdate").val() + "&empname="+$("#empname").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
Or alternatively, you can use an object which holds the name-value pair.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: { epdate : $("#epdate").val(), empname : $("#empname").val() },
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
UPDATE 1: You can also pass it as an array in the following format,
data : [{
name : 'epdate',
value : $("#epdate").val()
}, {
name : 'empname',
value : $("#empname").val()
}],
UPDATE 2: There is build in functions in jQuery to do the same, use [serialize()][] or serializeArray() method for that. You can apply it on a form element or input elements and which generates based on the input elements name attribute.
data : $('#epdate,#empname').serialize(),
// or
data : $('#epdate,#empname').serializeArray()
,

JSON data in array

I am absolut beginner level of web development. I would like to ask how to handle the json data from that link https://www.maxenergy.com.mm/api/max_price_list. I want to show the Diesel price in my page. But how to select the exact key form json data.
[
{
"Ayeyarwady":[
{
"price":{
"95 Ron Octane":660.00,
"Premium Diesel":620.00,
"Diesel":580.00,
"92 Ron Octane":580.00
},
"address":"Aungsan Road, Yay Kyi Township,Ayeyarwady.",
"station":"Max Energy (Yay Kyi)",
"longitude":null,
"latitude":null,
"telephone":"09977877901, 046-52020"
},
{ },
{ },
{ },
{ },
{ }
]
},
{ },
{ },
{ },
{ },
{ }
]
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="aya"></div>
<script>
$(document).ready(function() {
$.ajax({
url: 'https://www.maxenergy.com.mm/api/max_price_list',
dataType: 'jsonp',
type: 'GET',
}).done(function(data) {
$("#aya").html(data.Ayeyarwady.price.Diesel);
});
});
</script>
</body>
</html>
JSONArray json = new JSONArray(YOUR_RESPONSE);
for(int i=0;i<json.length();i++){
JSONObject dataJsonObject = new JSONObject(json.getJSONObject(i));
//FIRST JSONOBJECT
//NOW FROM THIS GET JSONARRAY Ayeyarwady
//AND MAKE IT FRO LOOP AGAIN AND get price and address like...
}
Hope this helps...
the array displayed in your page is part JSON part array (you can tell by the brackets type - [] is array, {} is JSON.
so you should use data[0].Ayeyarwady[0].price.Diesel (data and Ayeyarwady are arrays of objects with one child)
BUT this particular API isn't really supporting jsonp, and that's why it isn't working for you, if you add an error function callback you'll see that jQuery throws a parsererror on the data received.
you'll have to create a proxy server side request to the API, grab the data, parse as JSON and then get that data locally
Please change dataType like this,
dataType: 'json',

Parse JSON data from API

I am new to working with Jquery JSON and API's(this being my first Stack question, so please bear with me). So I am trying to figure out a way in which Im hitting a API and it will return data(city name) in JSON which I have to display on my page in list form. But the cities should be updated and the page should display the city names dynamically.
Here is the fiddle link:
Fiddle File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST2</title>
</head>
<body>
<button>Submit</button>
<select id="list"></select>
</body>
</html>
<script type="text/javscript" src="jquery-3.1.0.js"></script>
<script type="text/javscript">
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('list', {
text: element.detail
}));
});
}
});
</script>
JSON FILE
[
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]
Requesting for your help, thanks in advance for those who contributed
Provided you receive data from API you can do what you want.
//...
success: function (data) {
$.each(data, function(index, element) {
//$('body').append($('list', {//no comment
// text: element.detail
//}));
//add cities to select id="list"
$('<option/>') //create option
.val(element.id) //set its value
.text(element.detail) //set text
.appendTo('#list'); //and append to the list
});//each
}
this is not a JSON object, its an array, are you sure it comes back like this? try to log it then do one of the following:
if it comes as a string write this
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
accepts: "application/json; charset=utf-8"
/* ... */
the accepts tells the server to send back json, hence you can get it as json. if it is still a string, write JSON.parse(data)
if it comes as an array like youve written, then there should be no problem, except that its an array not a json object. json should be an object not an array.
{results: [
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]}
something like this will make it a json file.
if it comes like this, then you should write: data.results to access the array you need.
You don't need to parse. JSON is JavaScript Object Notation. you can just asign data to variable and use it in your code like
success: function(result) {
var data = result;
data.forEach(function(data){
$('body').append($('list', {
text: element.detail
}));
}
console.log(data);
//in console you can see tyour data
Object {type: "form-focus", element: "#run"}

Select2 - Ajax search - remember last results

I am using Select2 3.5.1. With this plugin I can successfully load remote data. However I am here today to ask a question to improve this search. Here is the step-by-step to understand what I would like to do:
Setup a Select2 with remote data loading (using ajax).
Click on the Select2 input and search for something.
The loading will appear and after some seconds you will see a list of results.
Click on one of the results listed - the box of results will then disappear.
If you click again on the search box, the list will be empty and you will need to type some new text again to have a list of results.
Is it possible that when we click again on the search box, that the list of results previously searched re-appear without any ajax call? Then if the user delete a character or change his search criteria it would then trigger the ajax search again.
If it is possible, how would we code that?
I hope my question is clear, please let me know if you have any questions. Thank you.
Here is a very simple code where we do a search that return a list of results. It doesn't really search, but it does return a list when you type something. I am not sure how to use the initSelection that is mentionned in one of the response.
<html>
<head>
<title>
Test page for ajax cache
</title>
<script type='text/javascript' src='../../resources/javascript/jquery/jquery-1.9.1.min.js'></script>
<link type='text/css' href='../../resources/javascript/select2/select2.css' rel='stylesheet' />
<script type='text/javascript' src='../../resources/javascript/select2/select2.js'></script>
<script>
$(document).ready(function(){
$('#select').select2({
ajax: {
type: 'POST',
url: 'ajax.php',
dataType: 'json',
data: function(term, page){
return {
autoc: 'country',
term: term
}
},
results: function(data, page){
console.log(data);
return( {results: data.results} );
}
},
placeholder: 'Search something',
minimumInputLength: 3,
width: '333'
});
});
</script>
</head>
<body>
<input type='text' name='inputdata' id='select' />
</body>
</html>
The very simple ajax.php called:
<?php
$results2['more'] = false;
$results2['results'][0] = array('id'=> "1", 'text'=> "California");
$results2['results'][1] = array('id'=> "2", 'text'=> "Canada");
$results2['results'][2] = array('id'=> "2", 'text'=> "Someword");
$results2['results'][3] = array('id'=> "2", 'text'=> "Alberta");
$results2['results'][4] = array('id'=> "2", 'text'=> "New York");
echo json_encode($results2);
I did read your post once again.
I misunderstood you last time.
The solution is here.
$(document).ready(function () {
$('#select').select2({
// this part is responsible for data caching
dataCache: [],
query: function (q) {
var obj = this,
key = q.term,
dataCache = obj.dataCache[key];
//checking is result in cache
if (dataCache) {
q.callback({results: dataCache.results});
} else {
$.ajax({
url: 'ajax.php',
data: {q: q.term},
dataType: 'json',
type: 'POST',
success: function (data) {
//copy data to 'cache'
obj.dataCache[key] = data;
q.callback({results: data.results});
}
})
}
},
placeholder: 'Search something',
width: '333',
minimumInputLength: 3,
});
// this part is responsible for setting last search when select2 is opening
var last_search = '';
$('#select').on('select2-open', function () {
if (last_search) {
$('.select2-search').find('input').val(last_search).trigger('paste');
}
});
$('#select').on('select2-loaded', function () {
last_search = $('.select2-search').find('input').val();
});
});
This will make another ajax call but with the same query string as before. Uses event select2:closing to save last query string and select2:open to insert the string into the search input and trigger input event.
var lastQueryString = '';
jQuery(".my-select2").select2({
minimumInputLength: 2,
placeholder: "Select an option",
ajax: {
url: "/example",
data: function (params) {
var query = {
search: params.term
}
return query;
},
processResults: function (data) {
return {
results: JSON.parse(data)
};
}
}
});
jQuery('.my-select2').on('select2:open', function () {
if (lastQueryString) {
jQuery('.select2-search').find('input').focus().val(lastQueryString).trigger('input');
}
});
jQuery('.my-select2').on('select2:closing', function () {
lastQueryString = jQuery('.select2-search').find('input').val();
});

Categories

Resources