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);
});
Related
So, in my code, when I press my #jsonclick button, it activates my script which populates a table with information from a JSON page. The problem I am having is that I am getting a TypeError: a is undefined, and I have no idea why.
Here is my code:
jQuery function
$("#clickjson").click(function () {
$.getJSON("gmessagegroup.php?gid=" + $('#gbox').val(), function (data) {
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
console.log(data.messages[key].clientmessageid + ":" + data.messages[key].from + " - " + data.messages[key].content);
$("#messages tbody tr:last").after('<tr><td>' + data.messages[key].clientmessageid + '</td><td>' + escapeHtml(data.messages[key].from).replace("https://bn1-client-s.gateway.messenger.live.com/v1/users/ME/contacts/8:", "") + '</td><td id=' + data.messages[key].clientmessageid + ' contenteditable="true">' + escapeHtml(data.messages[key].content) + '</td></tr>');
}
});
});
setTimeout(function () {
var message_status = $("#status");
$("td[contenteditable=true]").blur(function () {
var field_userid = $(this).attr("id");
var value = $(this).text();
$.post('groupedit.php', field_userid + "=" + value, function (data) {});
});
}, 1000);
});
The code is getting the value of the selected item in a dropdown select. I tried putting and alert in and it is putting out the correct value that is being pushed out to the PHP. I am unsure of where the TypeError comes into play, all I know is that when I remove ?gid=" + $('#gbox').val() from the end of the php, the error goes away. Problem is, I need that for the php to work. Can somebody please tell me why this is happening?
Thanks.
Actually in your json response messages is not found thats why it is responding as a is undefined check if you json data has messages or not like,
if(data && data.messages.length) // check for messages
$.each(data.messages, function (key, val) {
if (data.messages[key].clientmessageid != undefined) {
...
}
});
}
Snapshop
I'm using the Google Feed API to parse a feed into HTML. I'm trying to access the first image from the content body of the JSON. Here's my script right now:
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) {
console.log(data.responseData.feed);
// $(container).html('<h2>'+capitaliseFirstLetter(data.responseData.feed.title)+'</h2>');
$.each(data.responseData.feed.entries, function(key, value) {
var images = $(value.content).find('img').map(function(){
return $(this).attr('src')
}).get();
$(container).append('<article><h3> '+ value.title +' </h3>'+ ( images.length == 0 ? '' : '<img src="'+ images[0] + '"/>' )+'<p>'+ value.contentSnippet +'</p></article>');
});
}
});
}
function capitaliseFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
It fetches the second image just fine, but not the first. Any suggestions?
How can I get data response after uploading image and insert that response into a tag as data-id attribute (after successful post I am getting id of inserted image ). Where in the function is happening this? The function:
function img_upload(url) {
{
var fileTemplate = "<div id=\"{{id}}\">";
fileTemplate += "<div class=\"preview\"></div>";
fileTemplate += "<div class=\"filename\">{{filename}}</div>";
fileTemplate += "ObriĊĦi Sliku";
fileTemplate += "</div>";
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
$("#dropbox").html5Uploader({
postUrl: url,
onClientLoadStart: function (e, file, data) {
var upload = $("#upload");
if (upload.is(":hidden")) {
upload.show();
}
upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name));
console.log(data);
},
onClientLoad: function (e, file) {
$("#" + slugify(file.name))
.find(".preview")
.append("<img class=img_upload title=\"" + file.name + "\" src=\"" + e.target.result + "\" alt=\"\">")
.on('click', function () {
img_name = $(this).find('.img_upload').attr('title'),
url = '<?php echo base_url() ?>admin/galerija_naslovna_slika/' + img_name.replace(/\s/g, "_") + '/' + id;
$.post(url);
});
var img_delete = $('.image_delete');
delete_image(img_delete);
},
onServerLoad: function (e, file) {
}
});
}
}
I know this is old, But what I do is pass the id in the postURL.
So something like: /image_upload/212/
You need to use apache's mod_rewrite though to get to your php file. And then you can simply look at the request path to get the ID.
Or the other way to do it is pass the ID as a POST var.
You could have a hidden "input" with the id as the value.
docid = $('#docid').val();
$.ajax({
url: '/upload.php',
type: "POST",
data: {'docid': docid},
success: function(data, status, jqXHR) {
set_status('info', 'Success!');
},
error: function(jqXHR, status, err) {
set_status('danger', 'Error: ' + err + ' - ' + status);
},
complete: function(jqXHR, status) {
}
});
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.
When I click the button on the page I am getting a "Function Expected" error message.
The error is on the first if statement.
I have the following code:
Response_Error: function (xhr, textStatus, errorThrown) {
if (textStatus && (textStatus == 'error' || textStatus == 'parsererror')) textStatus = '';
if (errorThrown && errorThrown == 'error') errorThrown = '';
var html = '';
try {
html = (textStatus ? 'textStatus: ' + textStatus + '<br/>' : '') +
(errorThrown ? 'errorThrown: ' + errorThrown + '<br/>' + '<br/>' : '') +
(textStatus || errorThrown ? '' : '<hr/>') + xhr.responseText;
}
catch (err) {
document.write(err.description + '<br/>' + xhr.responseText);
}
if (Page._lastModalDialog) {
try {
if (false) { // HACK: change this to true to put contents on a textarea
html = html.replace('<', '<').replace('>', '>');
html = "<form><textarea rows='40' cols='120'>" + html + "</textarea></form>";
}
$(Page._lastModalDialog).html(html).fadeIn("slow");
}
catch (err) {
document.write(err.description + '<br/>' + html);
}
Page._lastModalDialog = null;
}
else {
document.write(html);
}
},
You can determine the line that have the error from the chrome inspector console or from fire bug and i think it hase something to do with providing a variable while a function is expected.
This is usually the case when a callback function is expected. Check the code and see if there is place where one of the parameters should be a callback function. You could also do a console.log xhr.onreadystatechange, to see if there is a callback assigned to the xhr object.