Replacing broken images in Jquery Auto-complete - javascript

I'm using the following auto-complete plugin that uses Jquery Auto Complete. It works well and does exactly what I need but my problem is that my JSON file has thousands of products with description, and images. Many of the images are down and don't work.
Does any one know how I can replace those broken image links with a general local image? I can't manually go into the JSON file and replace those images as it would take weeks.
I looked at this but no help: "http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images"
Any help is very much appreciated.
Here's FoxyComplete's JS and a link to the full script (Sorry couldn't get JsFiddle to work -- http://www.bcreatives.com.au/wp-content/uploads/dev/foxycomplete-local/):
(function($) {
$(document).ready(function() {
$( '#s' ).each( function(){
$(this).attr( 'title', $(this).val() )
.focus( function(){
if ( $(this).val() == $(this).attr('title') ) {
$(this).val( '' );
}
} ).blur( function(){
if ( $(this).val() == '' || $(this).val() == ' ' ) {
$(this).val( $(this).attr('title') );
}
} );
} );
$('input#s').result(function(event, data, formatted) {
$('#result').html( !data ? "No match!" : "Selected: " + formatted);
}).blur(function(){
});
$(function() {
function format(mail) {
return "<a href='"+mail.permalink+"'><img src='" + mail.image + "' /><span class='title'>" + mail.title +"</span></a>";
}
function link(mail) {
return mail.permalink
}
function title(mail) {
return mail.title
}
$("#s").autocomplete(completeResults, {
width: $("#s").outerWidth()-2,
max: 5,
scroll: false,
dataType: "json",
matchContains: "word",
parse: function(data) {
return $.map(data, function(row) {
return {
data: row,
value: row.title,
result: $("#s").val()
}
});
},
formatItem: function(item) {
return format(item);
}
}).result(function(e, item) {
$("#s").val(title(item));
//location.href = link(item);
});
});
});
})(jQuery);

I believe the accepted answer to the SO question you linked should work. Just replace your format function with the following:
function format(mail) {
return "<a href='"+mail.permalink+"'>" +
"<img src='" + mail.image + "' onerror='this.src=\'/img/error.jpg\'' />" +
"<span class='title'>" + mail.title +"</span></a>";
}
And make sure you have an image called /img/error.jpg, natch.

Related

Not able to understand how tag value is included from jsp page to js file

I am facing a problem where I have button in jsp page if i click it then it opens the dialogue and for the first time I am opening it , it shows the title of the dialogue box but from the second time onwards it doesnt show the title of dialogue.. I just started working on javascript and jsp , here I need a little help to understand where this value is coming from ,
**if($('#add-meeting-time').size() == 0)
$('body').append('<div id="add-meeting-time" />');**
How #add-meeting-time tag value is coming from jsp and why it is fetching the tag value add-meeting-time from jsp first time and not from the second time. I have added the code below.
please have a look and help
thanks in advance.
function addMeetingTime(caseId, passedds) {
showOverlay();
$.ajax({
url : 'case/RepairPro_addInputAgreeMeetingEvent?passedds='+passedds,
type : 'get',
data : 'cid=' + caseId + "&t=" + Math.random(),
success : function(data) {
if($('#add-meeting-time').size() == 0)
$('body').append('<div id="add-meeting-time" />');
$('#add-meeting-time').html(data);
$( "#add-meeting-time" ).dialog({
autoOpen: false,
modal: true,
width:650,
buttons: {
action: {
text: getText('save'),
click: function() {
disableDialogButton();
$('#add-meeting-time form').submit();
}
},
cancel: {
text: getText('cancel'),
click: function() {
$( this ).dialog( "close" );
}
}
},
create: function() {
var datepickerSettings = {minDate: 0};
if (getConfig('isDisplayTimezone')) {
datepickerSettings = {}
}
if(getConfig('isCalendarModularEnabled')) {
if(localMember.myrole > parseInt(getGlobal('AUTH2'))) {
$(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addMeetingTimeCalendar(\"" + passedds + "\", " + caseId + ");' title=\"" + getText('calendar_view') + "\" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
.button({icons:{primary: "ui-icon-calendar"},text: false}));
}
else {
$(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addPersonalMeetingTimeCalendar(\"" + passedds + "\", " + caseId + ");' title=\"" + getText('calendar_view') + "\" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
.button({icons:{primary: "ui-icon-calendar"},text: false}));
}
}
$(this).find('.datepicker').datetimepicker(datepickerSettings);
showTaskError(this, 'refreshCaseMessagesPage()');
initTeamMemberSelect();
},
open: function() {
$('select[id=add-meeting-member] option:eq(1)').attr('selected', 'selected');
$('select[id=add-meeting-member] option:eq(0)').attr('selected', 'selected');
},
close: function() {
$( this ).dialog( "destroy" ).remove();
}
});
$( '#add-meeting-time' ).dialog( 'open' );
}
});
}

Check if Jquery .get() JSON Function Worked

If have the following code that brings back a JSON array to be used in a banner delivery system. This works fine although there is some data in the system that populates the JSON array that is causing problems. It's an HTML and Javascript string. Is there any way to check if the below function has executed correctly and if not perform a secondary action?
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', function( data ) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, "json" );
From the jquery help page, as of jquery 1.5 you should be able to do this
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', function(data) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, "json").fail(function() {
// fail code goes here
});
similar to #dfsq answer, but less rewrite
You can use error callback:
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', "json").then(function(data) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, function(xhr, textStatus, errorThrown) {
console.log('Error', errorThrown);
});

jQuery autocomplete Conflict -

http://jsfiddle.net/Share_Knowledge/dgtqptr7/
I am trying to use autocomplete functionality of jquery ui into my project But i have no idea why THE SECOND $('.search').autocomplete() is
not working.
maybe i have to use $.noConflict()
if yes how i can use it $.noConflict()
would any body tell me how to use it to solve this problem out
any help please i would be thankful
using firebug i get these errors
POST http://localhost/autoservice/public_html/tickets/load_spareparts/11/instance
First
i don't what is the word instance coming from..???
here is the order of the js files
-js/jquery-ui.min.js
-jquery.autocomplete.js
jQuery(document).ready(function($) {
$.ajaxSetup( { type: "post" } );
// THIS IS WORKING PERFECTLY
$("#item").autocomplete(url+'/item_search', {
minChars:0,
selectFirst: false,
width: 749,
multiple: false,
matchContains: true,
formatItem: formatItem,
formatResult: formatResult
});
// THIS SHOW THE ERROR WHICH MENTIONED UP THERE
// IT'S NOT WORKING
$('#search').autocomplete({
minLength: 0,
source: path3+'/get_spareparts',
focus: function( event, ui) {
$('#search').val( ui.item.item_id );
return false;
},
select: function(event, ui) {
output = '';
output += '<tr>';
output += '<td>'+ui.item.item_id+'</td>';
output += '<input type="hidden" value="'+ui.item.id+'" name="item_id"></td>';
output += '<td>'+ui.item.item_name+'</td>';
output += '<td>'+ui.item.price+'</td>';
output += '<td><input type="text" name="qty" value="" size="1" class="qty"></td>';
output += '<td>'+ui.item.desc+'</td>';
output += '<td>Delete</td>';
output += '</tr>';
$('.inject').append(output);
$(this).val('');
deleteItem(); // DELETE ITEM
return false;
}
}) .autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.desc + "<br>" + item.item_id + "</a>" )
.appendTo( ul );
};
function deleteItem () {
$('.spareTrash').on('click', function(event) {
event.preventDefault();
$(this).parent().parent().fadeOut(900, function(){ $(this).remove();});
});
}
}); // END READY JQUERY

jQuery Autocomplete Nested Ajax Calls

I am currently working on implementing an album search autocomplete using the Spotify Metadata API. I have most of the features complete, but I am having trouble when doing a nested call to retrieve the album cover art. Here I believe is the root of my problem. When I do the ajax call to retrieve the image it does work, and I get the right data, but the return statement is not getting executed. What I am trying to do is get the first four results, for each get an image and return the label, item and image.
$('#spotify-album-search').autocomplete({
source:
function (query, process) {
$.when(
$.ajax({
url: 'http://ws.spotify.com/search/1/album.json?q=' + query.term,
})
).then(function (data) {
process($.map(data.albums.slice(0, 4), function(item) {
$.when (
$.ajax({
url: 'https://embed.spotify.com/oembed/?url=' + item.href,
dataType: 'jsonp'
})
).then(function (image) {
// Input: The Rolling Stones
console.log(item.artists[0].name + ' - ' + item.name + ': ' + image.thumbnail_url);
// Console: The Rolling Stones - Let It Bleed: https://d3rt1990lpmkn.cloudfront.net/cover/91205a1c80960d7055f8ed1bbe022f195e1767a4
return { label: item.artists[0].name + ' - ' + item.name, album: item, image: image.thumbnail_url };
});
}));
});
},
select: function (e, ui) {
console.log("selected= " + ui.item.album);
},
messages: {
noResults: '',
results: function() {}
}
})
.data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data( "ui-autocomplete-item", item)
.append('<a>' + item.label + '<img src="' + item.image + '" alt="" />' + '</a>')
.appendTo(ul);
};
EDIT:
Here you can find a working fiddle, if you believe could help!
http://jsfiddle.net/9GbkL/
In asynchronous programming, return is only useful for forcing an exit. You can't actually return data....
The only way to use data in asynchronous programming is to send it to a function.
So, you need a function that can update the UI given the data...
Add this functionality where currently the console.log testing with the data is done.
Thanks to the help from Godsbest at the jQuery Forums, I was able to get this working. Paul was right, and I needed the function call instead of the return statement. If anyone ever runs into a problem like I did, here is a fiddle with Autocomplete working with Bootstrap 3 and the Spotify Metadata API:
JS:
$('#spotify-album-search').autocomplete({
source:
function (query, process) {
$.when(
$.ajax({
url: 'http://ws.spotify.com/search/1/album.json?q=' + query.term,
})
).then(function (data) {
var process_data = [];
$.each(data.albums.slice(0, 4), function(i,item) {
$.when (
$.ajax({
url: 'https://embed.spotify.com/oembed/?url=' + item.href,
dataType: 'jsonp'
})
).then(function (image) {
process_data.push( { artist: item.artists[0].name, album_name: item.name, label: item.artists[0].name + ' - ' + item.name, album: item, href: item.href, image: image.thumbnail_url.replace("cover", "60")} );
process( process_data );
});
});
});
},
open: function(event, ui) {
},
select: function (e, ui) {
e.preventDefault();
$('#spotify-id').val(ui.item.album.href);
$(this).val(ui.item.label);
},
messages: {
noResults: '',
results: function() {}
}
})
.data('ui-autocomplete')._renderItem = function(ul, item) {
return $('<li>')
.data( "ui-autocomplete-item", item)
.append('<a>' + '<img width="50" src="' + item.image + '" alt="" />' + '<span class="ui-autocomplete-artist">' + item.artist + '</span>' + '<span class="ui-autocomplete-divider"><i class="fa fa-minus"></i></span>' + '<span class="ui-autocomplete-album-name">' + item.album_name + '</span>' + '<span class="ui-autocomplete-icon pull-right"><i class="fa fa-plus-circle fa-2x"></i></span>' + '</a>')
.appendTo(ul);
};
http://jsfiddle.net/9GbkL/5/ . Happy coding!

Jquery autocomplete images in the returned data

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!

Categories

Resources