I need to use a switch statement to build the markups based on the retrieved feed. Although I'm able to retrieve the data, I wonder if it's correct to use two $(data.value.items).each(function (index, item) { to append the feed's titles to a select box as well as an unorder list. Any better way of doing the same thing?
$.ajax({
url: "http://www.zzz.com/text.json",
dataType: 'json',
success: function (data) {
item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail'); }
});
function parseData(type, data) {
var item_html ='';
switch(type) {
case 'thisfeed':
item_html +='<select>';
$(data.value.items).each(function (index, item) {
item_html += '<option>'+item.title+'</option>';
});
item_html += '</select>';
item_html += '<ul>';
$(data.value.items).each(function (index, item) {
item_html += '<li>'+item.title+'</li>
});
item_html += '</ul>';
break;
}
return item_html;
}
You could just do both in the same loop, something like this
$.ajax({
url : 'http://www.zzz.com/text.json',
dataType : 'json',
success : function (data) {
var item_html = parseData(feedformat, data)
var nextarea = $this.next('.area');
nextarea.append(item_html).slideDown();
},
error: function () {
area.html('fail');
}
});
function parseData(type, data) {
switch(type) {
case 'thisfeed':
var select = $('<select />'),
ul = $('<ul />');
$(data.value.items).each(function (index, item) {
var option = $('<option />', {text : item.title}),
li = $('<li />', {text : '.......'});
select.append(option);
ul.append(li);
});
}
}
return select.add(ul);
}
Related
I want to create paginate system. I have this code:
(function (name) {
var container = $('#pagination-' + name);
container.pagination({
dataSource: '/ajax/allads',
locator: 'items',
totalNumber: 3,
pageSize: 2,
ajax: {
beforeSend: function () {
container.prev().html('Loading...');
}
},
callback: function (response, pagination) {
window.console && console.log(22, response, pagination);
var dataHtml = '<ul>';
$.each(response, function (index, item) {
dataHtml += '<li>' + item.title+ '</li>';
});
dataHtml += '</ul>';
container.prev().html(dataHtml);
}
})
})('demo2');
It display 2 page but everytime it displayall result. Why?
This has to do with your backend system. The result is basically from your response. Or you have to make your question more clear.
I'm learning Ajax and jQuery and trying to use json file as data source. I'm using jQuery UI autocomplete widget to help user select one option. I know I'm terribly off the track.
My json file:
[
{"iata":"AAC", "name":"El Arish"},
{"iata":"AAE", "name":"Annabah"},
{"iata":"AAF", "name":"Apalachicola"},
{"iata":"AAG", "name":"Arapoti"},
{"iata":"AAH", "name":"Aachen"},
{"iata":"AAI", "name":"Arraias"},
{"iata":"AAJ", "name":"Awaradam"},
{"iata":"AAK", "name":"Buariki"},
{"iata":"AAL", "name":"Aalborg"},
{"iata":"AAM", "name":"Malamala"},
{"iata":"AAN", "name":"Al Ain"}
]
My JavaScript:
$(document).ready(function () {
$('#search').autocomplete({
source: function (request, response) {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON("beta.json", function (data) {
var output = '<ul class="searchresults">';
$.each(data, function (key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
output += '<li>';
output += '<h2>' + val.iata + '</h2>';
output += '<p>' + val.name + '</p>';
output += '</li>';
}
});
output += '</ul>';
$('#update').html(output);
});
)
});
}
});
});
I fixed some syntax errors and then wrote up this example to really get you jump started.
$( function() {
$.getJSON("http://neil.computer/stack/beta.json", function(data) {
autoComplete = [];
for (var i = 0, len = data.length; i < len; i++) {
autoComplete.push(data[i].name + ", " + data[i].iata);
}
$( "#tags" ).autocomplete({
source: autoComplete
});
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
You can push html to an array at request, pass array to response, at .autocomplete("instance")._renderItem create an <li> element with html set to second argument item, .value property, which should be html set within request and passed to response; append <li> to first argument ul, return ul from ._renderItem
var elem = $("#search");
$.ajaxSetup({
context: elem
});
elem.autocomplete({
minLength: 1,
source: function(request, response) {
$.getJSON("beta.json")
.then(function success(data) {
var searchField = elem.val();
var myExp = new RegExp(searchField, "i");
var res = [];
$.each(data, function(key, val) {
if ((val.iata.search(myExp) !== -1) ||
(val.name.search(myExp) !== -1)) {
res.push("<h2>" + val.iata + "</h2>" + "<p>" + val.name + "</p>")
}
});
response(res);
}, function error(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown) // log `$.ajax` errors
})
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>", {
html: item.value
}).appendTo(ul)
};
jsfiddle http://jsfiddle.net/wr1wg5df/11/
I don't want to parse all title from the list. I only want the first title to be parsed. Any suggestion?
function parseRSS(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
$.each(data.responseData.feed.entries, function(key, value){
var thehtml = '<h3>'+capitaliseFeed(value.title)+'</h3>';
$(container).append(thehtml);
});
}
});
}
function capitaliseFeed(string) {
return string.toUpperCase();
}
Instead of $.each you could loop the data and keep only the first entry
for (var i = 0; i < data.responseData.feed.entries.length; i++) {
var entry = data.responseData.feed.entries[i];
var thehtml = '<h3>'+capitaliseFeed(entry.title)+'</h3>';
$(container).append(thehtml);
break;
}
Hi I have the problem of filtering the second drop down that depends on the first drop down,It is like the second drop down options they are static they does not do change based on what i have chosen here is my code to get secon drop down data.
$.ajax({
dataType: "json",
url: "{{action('CampaignController#getAdvertiser')}}/"+$("#advertiserId").val()
}).done(function(results){
$("#brandId").empty();
$(results).each(function(index,value){
newOption = $("<option value=\""+value.id+"\">"+value.brandName+"</option>");
$("#brandId").append(newOption);
});
please check my entire script maybe somewhere is refreshing that drop down
$(document).ready(function () {
$(function () {
$("#multiselect").multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#multiselect option:selected");
var message = "";
selected.each(function () {
message += $(this).text() + " " + "\n";
});
alert(message);
});
});
function loadBrands() {
$.ajax({
dataType: "json",
url: "{{action('CampaignController#getAdvertiser')}}/" + $("#advertiserId").val()
}).done(function (results) {
$("#brandId").empty();
$.each(results, function (index, value) {
var newOption = $("<option value=\"" + value.id + "\">" + value.brandName + "</option>");
$("#brandId").append(newOption);
// $("#brandId").trigger("chosen:updated");
});
//$("#brandId").empty();
// hardcode 1 it must be remove asap
$.ajax({
dataType: "json",
url: "{{action('ReportingController#getCamp')}}/" + 1
}).done(function (results) {
$("#campaignId").empty();
console.debug(get);
$(results).each(function (index, value) {
$("#campaignId").append("<option value=\"" + value.campaignId + "\">" + value.campaignName + "</option>");
$('#campaignId').trigger('change');
});
});
//loading city
$.ajax({
dataType: "json",
url: "{{action('CampaignLocationController#getLocations')}}/" + 1
}).done(function (results) {
$("#city").empty();
$(results).each(function (index, value) {
getCityDetails = value.data[0];
$("#city").append("<option value=\"" + getCityDetails.brandId + "\">" + getCityDetails.city + "</option>");
$('#city').trigger('change');
});
});
}).fail(function (results) {
alert("Failed to load brands.");
});
}
loadBrands();
$("#advertiserId").change(loadBrands);
$("#brandId").change(loadBrands);
});
$(results).each(
Is used to iterate the Nodelist in jQuery.
For data manipulation, you must use $.each(results) instead.
$.each(results, function(index,value){
var newOption = $("<option value=\""+value.id+"\">"+value.brandName+"</option>");
$("#brandId").append(newOption);
// $("#brandId").trigger("chosen:updated");
});
Instead of appending in each iteration, you can push to an array and then append it at last.
var options = [];
$.each(results, function(index,value){
options.push('<option value="'+value.id+'">'+value.brandName+'</option>');
});
$("#brandId").html(options.join());
Also You've missed var keyword while defining newOption so it will be global
$(document).ready(function() {
$(function () {
$("#multiselect").multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#multiselect option:selected");
var message = "";
selected.each(function () {
message += $(this).text() + " " + "\n";
});
alert(message);
});
});
function loadBrands(){
$.ajax({
dataType: "json",
url: "{{action('CampaignController#getAdvertiser')}}/"+$("#advertiserId").val()
}).done(function(results){
$("#brandId").empty();
$.each(results, function(index,value){
var newOption = $("<option value=\""+value.id+"\">"+value.brandName+"</option>");
$("#brandId").append(newOption);
// $("#brandId").trigger("chosen:updated");
});
//$("#brandId").empty();
// hardcode 1 it must be remove asap
$.ajax({
dataType: "json",
url: "{{action('ReportingController#getCamp')}}/"+1
}).done(function(results){
$("#campaignId").empty();
console.debug(get);
$(results).each(function(index,value){
$("#campaignId").append("<option value=\""+value.campaignId+"\">"+value.campaignName+"</option>");
$('#campaignId').trigger('change');
});
});
//loading city
$.ajax({
dataType: "json",
url: "{{action('CampaignLocationController#getLocations')}}/"+1
}).done(function(results){
$("#city").empty();
$(results).each(function(index,value){
getCityDetails = value.data[0];
$("#city").append("<option value=\""+getCityDetails.brandId+"\">"+getCityDetails.city+"</option>");
$('#city').trigger('change');
});
});
}).fail(function(results){
alert("Failed to load brands.");
});
}
loadBrands();
$("#advertiserId").change(loadBrands);
$("#brandId").change(loadBrands); removed this line now it is working
Fiddle Example
I'm working on a chained selectbox that populates options via Ajax and uses localStorage to save the returned data. The code is working but I want to simplify the code a little bit.
I want to know if it's possible to define the two $.each functions as a function outside the ajax code and call it back in the success function, like this example,but the tricky part is that the returned data is defined as data in the ajax success function while it's defined as key from the localStorage.
Failed Code:
function loop(){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
$('select').each(function(loop){
$(this).one("mouseenter",function(){
var name = $(this).data('name'),
key = JSON.parse(localStorage.getItem(name)),
$select = $('select');var $option="";
$(this).addClass('yellow');
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data);
}
});
}
else{
loop(key);
}
});
});
Original Working Code:
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
$(this).addClass('yellow')
if (!key) {
$.ajax({
url: url,
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
$.each(key.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
$select.dynamicDropdown({"delimiter":"#"});
}
}); // end one function
});
Like this?
function loop(data, $select){
$.each(data.query.results.json.json, function (index, i) {
smallchoice = i.choice.split('|');
$.each(smallchoice,function(j,smallchoice){
$option = $("<option/>").attr("value", smallchoice).text(i.bigcat + "#" +( i.cat || "") +"#" + smallchoice);
$select.append($option);
});
});
}
$('select').each(function(){
$(this).one("mouseenter",function(){
var name = $(this).data('name');
var key = JSON.parse(localStorage.getItem(name));
var $select = $('select');var $option="";
if (!key) {
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fcheapgamessales.com%2F133.json%22&format=json&diagnostics=true&callback=",
success: function(data){
localStorage.setItem(name, JSON.stringify(data));
loop(data, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
}
else{
loop(key, $select);
$select.dynamicDropdown({"delimiter":"#"});
}
});
});