Repopulating Image Picker select control with new data after ajax call - javascript

I am using this Image Picker jQuery plugin (http://rvera.github.io/image-picker/) and I'm facing a problem with the following:
Repopulating the select control with new data after ajax call.
$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result)
{
$.each(result, function(i, obj) {
console.log(obj.description);
$('#cake-filling-types-select')
.append($("<option data-img-src='" + obj.image + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
$("#cake-filling-types-select").data("picker").sync_picker_with_select();
}});
For more details please find the issue here: https://github.com/rvera/image-picker/issues/79
Thanks.

The issue is solved. With the help of #ArmindoMaurits # GitHub, so using the ' $("#cake-filling-types-select").empty();' is fine for clearing this plugin select.
Also, for the other issue where some items are not getting into the select control, I found that these the ones that is missing the img src.
Updated working code:
`$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result){
$("#cake-filling-types-select").empty();
$.each(result, function(i, obj) {
if(obj.image != null)
{
var imgSrc = obj.image;
}else{
imgSrc = '';
}
$('#cake-filling-types-select')
.append($("<option data-img-src='" + imgSrc + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
}});`

Related

How to strip a string from unwanted parts?

Given an url like this:
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg
How do i get it to be like
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,44_AL_.jpg
The issue I am having is with retrieving IMDB poster images, using this:
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
crossDomain: true,
dataType: "jsonp",
success: function(data) {
window.console.log(data);
}
});
});
I get a json response like:
"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_UX32_CR0,0,32,44_AL_.jpg"
I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:
function imdbLoad() {
var form = $("#usp-title").val();
var encodedTerm = encodeURIComponent(form);
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
q: encodedTerm
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
$.each(data.data.results, function(i, items) {
$("#imdb").append('<h2>'+i+'</h2>');
$.each(items, function(k, item) {
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
});
});
}
});
}
Unless anyone has any other way to grab the poster url
You can either use regex to replace string part that is not required
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var regex = /,.*(?=,)/g;
console.log(url.replace(regex, ''))
or split using comma(,) and join first and last part.
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var parts = url.split(',');
console.log(parts[0] + ',' + parts.pop())
This is a bit of a longer code as I have included few bits such as limiting the number of results but basically what I noticed is that after the ## the whole string is about image size. So instead of using a regex (that would be the answer for this specific question), I could simply add the dimension to the url as a string like:
<img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'>
Full code
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
api_key: "...",
q: form.find('input[name="q"]').val()
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
var thumbnailMod, limiteRes = 1;
if (data.data.results.titles !== undefined) {
$("#imdb").append('<h2>Titles</h2>');
$.each(data.data.results.titles, function(i, item) {
thumbnailMod = item.thumbnail.split('#.');
if (thumbnailMod.length > 1) {
if (limiteRes > 3) {
return;
}
limiteRes++;
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
}
});
} else {
console.log('No titles found for this search.');
}
}
});
});

How can i load data from ajax to Chosen jquery?

I have use chosen at http://harvesthq.github.io/chosen/ . Ok, i testing it load data from ajax . I founding anywhere, maybe no someone success with them.
<script src="theme/js/jQuery-2.1.3.min.js"></script>
<link href="theme/chosen_v1.4.2/chosen.css" rel="stylesheet" />
<script src="theme/chosen_v1.4.2/chosen.jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(".cb_bu_info").chosen({
width: "95%",
source: function (data) {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
//$.each($.parseJSON(data.d), function (idx, obj) {
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
//$("#cb_info").trigger("liszt:updated");
},
error: function (data) {
console.log(data.d);
}
});
}
});
$("#cb_info").trigger("liszt:updated");
});
</script>
<select id="cb_info" class="cb_bu_info"></select>
The data form ajax as
[{"BU_ID":"B01","BU_NAME":"Agro Feed","BU_DES":"Agro Feed","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false},{"BU_ID":"B02","BU_NAME":"Agro Farm","BU_DES":"Agro Farm","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false}]
Well , it's look ok , but when i run it , result not show in select option, see browser dev tool , I've not seen error. Anything is ok.What's the problem happen in here? Notes: only use Chosen Jquery
After checking out the Chosen docs, there seems to not be a "source" option. What you need to do is first run your Ajax call, then fill your select options. Once the select is all filled, then run Chosen on that select element.
I would use the following JS code:
var url = "../BUS/WebService.asmx/LIST_BU";
$.getJSON(url, function(json){
var $select_elem = $("#cb_info");
$select_elem.empty();
$.each(json, function (idx, obj) {
$select_elem.append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$select_elem.chosen({ width: "95%" });
})
Ok, After some time with the help of suggestions from everybody, I have done
function load_cb_info() {
$.ajax({
type: "POST",
url: "../BUS/WebService.asmx/LIST_BU",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#cb_info").html('');
$.each($.parseJSON(data.d), function (idx, obj) {
//$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen({ width: "95%" });
},
error: function (data) {
console.log(data.d);
}
});
}
And , I think this is an answer and everyone else can find it .Thank you.
I have changed your jsfiddle. Try this out http://jsfiddle.net/GaganJaura/by4d528c/2/
I have moved the chosen() to bottom.
$("#cb_info").empty();
$.each(data, function (idx, obj) {
$("#cb_info").append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
});
$("#cb_info").trigger("liszt:updated");
$("#cb_info").chosen();
You can try as follows it works for me
$.ajax({
type: "POST",
url: url,
data: formData,
processData: false,
contentType: false,
success:function(data){
if($.trim(data) != "no"){
$("#PROGRAM_ID").html(data);
$("#PROGRAM_ID").trigger("chosen:updated");
}
}
});
try this. it works for me. please pay attention to the bold text
Ext.Ajax.request({
url:'<?php echo base_url()."index.php/";?>ttemuan31a/cari_divisi',
method:'post',
params:{
divisi:vdivisi
},
success:function(data)
{
$("#divisi").chosen();
//document.getElementById('detail_divisi').innerHTML=response.responseText;
$('#divisi').empty();
$.each(JSON.parse(**data.responseText**), function(i, item) {
$('#divisi').append('<option value="'+item.id+'">'+item.namadivisi+'</option>');
$("#divisi").trigger("chosen:updated");
});
}
});
}

What's the error in following function code of jQuery?

I've written one jQuery function to get the city and state code based upon the zip code value but facing some issue with some errors. Can someone please help me in correcting the mistakes I'm making here.
Following is my code :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {'request_type':'ajax', 'op':'get_test_category_list','zip_code =' + el.val()},
success: function(result, success) {
$("#city").val(result.city);
$("#state_code").val(result.state);
}
});
}
});
});
Thanks in advance.
The issue is in your data object, you have invalid syntax. Change this:
'zip_code =' + el.val()
To this:
'zip_code': el.val()
The full object should look something like this:
data: {
'request_type': 'ajax',
'op': 'get_test_category_list',
'zip_code': el.val()
},
I think the problem is with data part of the ajax
Change it like this
data: {request_type:"ajax", op:"get_test_category_list",zip_code : el.val()},

Display data in dynamically created div using jquery

I want to display data function name and function description from database and display it in div which will be created dynamically using jquery. How can I display data with dynamic div using jquery...
code for dynamically created div is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'FunctionListing.aspx/CountFunction',
data: "{}",
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
//alert(result.d);
for (var i = 1; i <= result.d; i++) {
$('body').append("<div id='div" + i + "' />");
}
},
error: function (result) {
alert(result);
}
});
});
dataType :"json"
Not datatype :"json"
Hope, it'll helps you.

Json data from Guardian API

I have a guardian json data feed that I want to pull into my page online.
http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz
I have used this javascript but nothing seems to be working to grab the right content from the json;
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < 12; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='" + webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});
This is not throwing anything in terms of errors.
Am I better using a js service like backbone or underscore?
Any help would be amazing on this.
Use
data.response.results[i].webTitle
instead of
webTitle
error was
Uncaught ReferenceError: webTitle is not defined
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < data.response.results.length; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='"
+ data.response.results[i].webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});​
JSFiddle

Categories

Resources