Jquery autocomplete images in the returned data - javascript

I've gotten jquery autocomplete working on my site, and now I'm trying to get it to display an image from the data that I am pulling from my database.
However I've run into a problem as while it is pulling through my image data and product name, it's displaying the html as text in the autocomplete drop down.
Hopefully someone can see where I'm going wrong and point me in the right direction!
$(document).ready(function() {
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('homepage_products/suggestions'); ?>",
data: { term: $("#autocomplete").val()},
dataType: "json",
type: "POST",
success: function(data){
var data_to_return = new Array();
for (var i = 0; i < data.length; ++i) {
data_to_return.push("<li><a>" + "<img src='" + data[i].image + "' />" + data[i].prodid+ " - " + data[i].product_name+ "</a></li>");
}
response(data_to_return);
}
});
},
minLength: 4
});
});
});
Thanks!
-------------EDIT-------------
Ok after the suggestion of Spokey I've now altered my code as follows and I've managed to get my results to display in html rather than just text:
$(function() {
$( "#autocomplete" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('homepage_products/suggestions'); ?>",
data: { term: $("#autocomplete").val()},
dataType: "json",
type: "POST",
success: function(data){
var data_to_return = new Array();
for (var i = 0; i < data.length; ++i) {
data_to_return.push("<li><a href = '/shop/products/id/" + (data[i].image).toLowerCase() + ".htm'>" + "<img src='/shop/images/product_thumbs/" + (data[i].image).toLowerCase() + ".jpg' />" + data[i].id + " - " + data[i].name+ "</a></li>");
}
response(data_to_return);
}
});
},
select: function( event, ui ) {
alert(ui.item.value);
window.location.href = ui.item.value;
},
minLength: 2
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.image + "</a>")
.appendTo(ul);
};
});
However now I'm not getting any specific javascript errors, but the images aren't appearing. I've tried absolute paths, and I've checked that they do exist on the server - but all I get is a grey box when I roll my mouse over where the image should be appearing on the drop down list.
Hopefully someone can spot my mistake!
I also found this for links which I found quite useful and thought I'd recommend for anyone else trying to achieve something similar:
JQuery Autocomplete Where the Results are Links
-------------FINAL FIX-------------
Oops - it was me being an idiot in the end - I was calling
item.image
When I should have been calling
item.label
Thanks for the help!

Related

How to manually select an item using AJAX, Select2 and the "val" function

Trying to figure out how to change the selected item of a select2 box after the page loads for the first time (and after it has loaded data from a ajax api call)
I tried using the below, but I cant get them to call after the ajax data has loaded?
$series2.val('2');
$series2.trigger('change');
The documentation says that it cannot be done using the val function (see here https://select2.org/programmatic-control/add-select-clear-items) and I do not want to do this with a custom API call that provides a "selected" value - as this does not work with templating.
This is NOT a duplicate of Select2 auto trigger event change
var $make2 = $(".make2");
var $series2 = $(".series2");
$make2.select2().on('change', function() {
$series2.empty();
if ($make2.val() !== null) {
$.ajax({
url: "{{ url('/') }}" + "/api/series/" + $make2.val(),
type: 'GET',
dataType: 'json',
async: true,
success: function(data) {
$series2.select2({
data: data,
templateSelection: function(result) {
return result['text'];
},
templateResult: function(result) {
if (!result['id']) {
return result['text'];
};
var final =
'<div>' +
'<strong>' + result['text'] + '</strong>' +
'<ul class="list-unstyled">' +
'<li><em>' + result['make'] + '</em></li>' +
'<li><em>' + result['category'] + '</em></li>' +
'</ul>' +
'</div>';
return final;
},
escapeMarkup: function(result) {
return result;
},
});
}
});
}
}).trigger('change');
});

How to extract and add the JSON data received as a AJAX response to the HTML select drop down using jQuery?

I've following HTML code :
<select id="student" name="student" class="form-control"></select>
The jQuery-AJAX function I've written for adding the options to the above HTML select control is as follows :
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$('#student').html(result);
},
error: function() {
alert("Error is occured");
}
});
From PHP file I've received a big array encoded into JSON format(i.e. the result variable from jQuery-AJAX function). For your reference I'm showing below only the first four records from that array. In HTML select control actually I want to show all the elements from this array.
[{"id":2,"stud_name":"John Dpalma","stud_address1":"277 Eisenhower Pkwy","stud_address2":"","stud_city":"Edison","stud_state":"New Jersey","stud_country":"USA","stud_zipcode":"07039","stud_email":"abc#gmail.com","created_at":1409739580,"updated_at":1410253832},
{"id":3,"stud_name":"Anthony Gonsalvis","stud_address1":"520 Division St","stud_address2":"","stud_city":"Piscataway","stud_state":"NJ","stud_country":"USA","stud_zipcode":"07201","stud_email":"pqr#gmail.com","created_at":1409740530,"updated_at":1410255590},
{"id":4,"stud_name":"James Bond","stud_address1":"6 Harrison Street, 6th Floor","stud_address2":"Ste-2324","stud_city":"New York","stud_state":"NY","stud_country":"USA","stud_zipcode":"10013","stud_email":"xyz#gmail.com","created_at":1409757637,"updated_at":1412263107},
{"id":9,"stud_name":"Mary Jane","stud_address1":"2112 Zeno Place","stud_address2":"CA","stud_city":"Venice","stud_state":"CA","stud_country":"","stud_zipcode":"90291","stud_email":"utp#gmail.com","created_at":1409908569,"updated_at":1410254282}]
In HTML select control I want to set the values in following manner(consider first two records from above array)
<select id="student" name="student" class="form-control">
<option value="">Select Store</option>
<option value="2">John Dpalma, 277 Eisenhower Pkwy, Edison</option>
<option value="3">Anthony Gonsalvis, 520 Division St, Piscataway</option>
</select>
You might have observed from the expected output above that I want to set the value of option as a id from array and the text that I want to display is comprising of stud_name+stud_address1+stud_city
How should I manage this for all the elements from the JSON data in my code?
Also please guide me in showing the loading option into the select control until the response from PHP comes.
Please provide me some help.
success: function(result, success) {
var $select = $('#student');
$.each(result, function (i, option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
$('<option>', {
value: option.id,
text: txt.join(', ')
}).appendTo($select);
});
},
or with $.map (slightly more efficient):
success: function(result, success) {
var options = $.map(result, function (option) {
var txt = [option.stud_name, option.stud_address1, option.stud_city];
if (option.stud_address2)
txt.splice(2, 0, option.stud_address2);
return $('<option>', {
value: option.id,
text: txt.join(', ')
});
});
$('#student').append(options);
},
In PHP file echo the following in a loop:
echo '<option value="">'.$stud_name.', '.$stud_address1.', '.$stud_address2.', '.$stud_city.', '.$stud_state.', '.$stud_country.'</option>';
Then attach this result to the select dropdown with jQuery through the ajax success.
Here is my solution. This checks address 2 and adds it to the options accordingly.
JS code:
for(var i=0;i<result.length;i++){
if(result[i]["stud_address2"]==""){
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', ' +result[i]["stud_city"] +'</option>');}
else{
$('#student').append('<option value="' + result[i]["id"] + '">' + result[i]["stud_name"] + ', ' + result[i]["stud_address1"]+ ', '+ result[i]["stud_address2"]+ ', ' +result[i]["stud_city"] +'</option>');
}
}
Here is a working DEMO
This is exactly what you need!
$(document).ready(function(){
var mod_url = $('#mod_url').val();
$.ajax({
url : mod_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
},
success: function(result, success) {
$.each(result,function(index,item){
$label = item.stud_name +', ' + item.stud_address1 +', ' + item.stud_city;
$('#student').append('<option value="'+ item.id +'">'+ $label +'</option>');
});
},
error: function() {
alert("Error is occured");
}
});
});
It's a matter of iterating over the JSON you receive from the server, creating option tags for each record, then appending them to the select element:
var response = [{"id":2,"stud_name":"John Dpalma" ... }]
$.each(response, function (index, record) {
if (!record.stud_address2){
var stud_address2 = "";
} else {
var stud_address2 = record.stud_address2;
}
$('<option>', {
value: record.id,
text: record.stud_name + ", " + record.stud_address1 + ", " + record.stud_city + ", " + stud_address2
}).appendTo("#student");
});
Demo
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script>
function __highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "ig");
return s.replace(matcher, "<strong>$1</strong>");
}
$(document).ready(
function() {
$("#suggest").autocomplete(
{
source : function(request, response)
{
$.ajax({
url : 'URL',
dataType : 'json',
data : { term : request.term },
success : function(data)
{
//alert(data[0].title);
response($.map(data, function(item) {
//alert(item);
return {
label : __highlight(item.title, request.term),
value : item.title
};
}));
}
});
},
minLength : 3,
select : function(event, ui)
{
if(ui.item){
$(event.target).val(ui.item.value);
}
//submit the form
$(event.target.form).submit();
}
}).keydown(function(e) {
if (e.keyCode === 13)
{
$("#search_form").trigger('submit');
}
}).data("autocomplete")._renderItem = function(ul, item)
{
return $("<li></li>").data("item.autocomplete", item).append(
$("<a></a>").html(item.label)).appendTo(ul);
};
});
</script>

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

Implement jQuery on dynamically created elements

I'm trying to integrate two jQuery scripts into one but because the elements of the first part are created dynamically using jQuery I can't get the second part of the project working.
The project:
1.Instagram pictures are parsed as JSON into li elements.
Here's a portion of the code:
<ul id="elasticstack" class="elasticstack">
</ul>
<script>
$("#elasticstack").append("<li><div class='peri-pic'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /><span class='name'>"+ data.data[i].caption.from.username +"</span> <span class='likes'><span class='glyphicon glyphicon-heart'></span><p>"+data.data[i].likes.count +"</p></span></div></li>"
);
</script>
Source: LINK
2.This works fine but when I try to add the slider none of the functions work. Even if I wrap the callout function in a $( document ).ready(function() { });
Here's the call out code:
<script>
new ElastiStack( document.getElementById( 'elasticstack' ) );
</script>
Source: LINK
Here's the JS Fiddle with all my code: LINK
Where am I going wrong?
You're looking for this. After the initial loadImages(start_url) call, you should be able to call loadImages(next_url) to load and display more. new ElastiStack had to be called after the images had been appended.
var access_token = "18360510.5b9e1e6.de870cc4d5344ffeaae178542029e98b",
user_id = "18360510", //userid
start_url = "https://api.instagram.com/v1/users/"+user_id+"/media/recent/?access_token="+access_token,
next_url;
function loadImages(url){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url,
success: function(data){
displayImages(data);
next_url = data.pagination.next_url;
}
})
}
function displayImages(images){
for(var i = 0; i < 20; i++){
if(images.data[i]){
$("#elasticstack").append("<li><img class='instagram-image' src='" + images.data[i].images.low_resolution.url + "'></li>");
}
}
// Call it after the images have been appended
new ElastiStack(document.getElementById('elasticstack'));
}
$(document).ready(function(){
loadImages(start_url);
});
Try to initialize the ElastiStack after data (HTML elements) has been appended into the DOM in your ajax, for example:
for (var i = 0; i < count; i++) {
// ...
$("#elasticstack").append(...);
}
new ElastiStack(...);
It should work.
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: url ,
success: function(data) {
next_url = data.pagination.next_url;
//count = data.data.length;
//three rows of four
count = 20;
//uncommment to see da codez
//console.log("count: " + count );
//console.log("next_url: " + next_url );
//console.log("data: " + JSON.stringify(data) );
for (var i = 0; i < count; i++) {
if (typeof data.data[i] !== 'undefined' ) {
//console.log("id: " + data.data[i].id);
$("#elasticstack").append("<li><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' /></li>"
);
}
}
new ElastiStack(document.getElementById('elasticstack'));
}
});
You have to move your new ElastiStack(document.getElementById('elasticstack')); inside the ajax success event. You don't have to change anything else in your. I also updated your JSFiddle.

how to show the loader dynamically until all the image load in jquery mobile phonegap listview

am having trouble to showing loader untill all the image is load in the listview.the following code is used in my app.it shows the loader untill all the image is load but the problem is , append the last src value to all the image attribute src.please help me.
$.ajax({
url: "http://www.some.com/",
type: 'POST',
data: param,
dataType: "jsonp",
success: function (result) {
$.each(result.results, function (k, v) {
var searchPic = "http://www.some.com" + $.trim(v.eventIcon);
var localarray = new Array();
var c = v.eventText;
strs = c.slice(0, 60);
$('[data-role="listview"]').append('<li> ' + '<img alt="img" class="pic1" src=" ">' + '<h4 >' + v.eventTitle + '</h4>' + '<p>' + strs + '...' + '</p></li>');
$('[data-role="listview"]').listview('refresh');
imgload(searchPic);
});
$('[data-role="listview"]').append('<li id="no-results">There is no record found based on your search criteria, please refine your search.</li>');
}
});
function imgload(tx) {
$('.pic1').load(function () {
$.mobile.loading('hide');
}).attr('src', tx);
}
});

Categories

Resources