I have created a simple page the displays random quotes from QuotesOnDesign API. However, my "New Quote" element when clicked doesn't trigger the getQuote function. Here is a link to my code:
CodePen Random Quote
I suspect this is related to jQuery as the Chrome console displays an error mentioned that it refused to load script (referring to jQuery). The strange thing is that when I click on "New Quote" while I have the Developer Tools open in Chrome, it works!
The browser is caching the response the first time you call the API, and reusing that response on future calls. You can resolve this by adding a cachebuster to the URL.
The reason it works when you open the console is because you presumably have the Disable cache (while DevTools is open) option set.
function getQuote() {
var cb = Math.round(new Date().getTime() / 1000);
$.getJSON("http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=" + cb, function(a) {
$(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>");
});
}
Working CodePen
You can get rid of the funciton call altogether and give $.ajax a try like so:
$(".button").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1',
success: function(a) {
$(".quote-text").html(a[0].content + "<p>— " + a[0].title + "</p>")
},
cache: false
});
});
With cache: false you are preventing caching on a per call basis so the content changes each time the button is clicked as expected.
Related
This is a very specific problem and one that makes me particularly confused. The project in short: I'm working on a counseling website that gets data from an API and is loaded with AJAX. I'm now trying to get old, archived chats to be be preloaded and displayed with css on click in a menu.
Here's the problem: It works... but only about 1 in 3 times or after reload of the page. I don't understand how that can be, either it should work or it doesn't.
I checked and the data is always loaded (it has to because the current chat is opened first and always works)
So how can that be?
$.ajax({
type: 'POST',
url: '/vsbt/counselling/archive/',
data: {},
}).done(function(data) {
console.log('ajax /vsbt/counselling/archive/');
console.log(data);
//menu is created
$('#counselling_status').append('<ul class="archivedCounsellings"></ul>');
$('.archivedCounsellings').append('<h2>Archivierte Chats</h2>')
for (var i = 0; i < data.length; i++) {
//menu items are added
var that = data[i].messages[0].title;
$('.archivedCounsellings').append('<li class="' + that + '"><a>' + that + '</a></li>')
$('#vbst_communication_container').prepend($('<div class="counselling inactive ' + that + '" />')
.append($('<h2>' + that + '<h2>')));
//the messages are added with to classes for styling
data[i].messages.forEach(function(message) {
$("div." + that)
.append($('<div />')
.addClass(message.type)
.append($('<p />')
.text(message.message)))
});
//this doesn't work either, you can maybe tell me why, but that's not the issue
$('.counselling').data("status", [i]);
}
$(".archivedCounsellings").append('<li class="aktuell"><a><br>Zur aktuellen Beratung</a></li>');
//click event to toggle the displayed counseling
$('.archivedCounsellings li').click(function() {
$('.counselling').addClass('inactive');
$('div .' + $(this).attr('class')).removeClass('inactive');
//workaround which works, but isn't really acceptable
// no load workaround
// if($('.openCounselling').siblings().length == 0){
// window.location.reload();
// }
// $('.statusDisplay').text($('#job_status_' + $(this).attr('class')).data("status"));
// console.log($('div .' + $(this).attr('data-status')));
});
PS. I'm aware of the typo in 'counselling'
PPS. if you find a mistake that obviously makes it fail that probably happend while copying since, remember, it does work sometimes.
Ok so if anyone ever encounters this problem: I was just explained AJAX a little bit closer and basically AJAX sends out all the requests more or less simultaneously. Whatever happens in the done function happens after that, hence the successful data request.
What I did, was initiate the container for said elements in a different function. So occasionally that one was a little bit slower and there was no place to append my elements to --> no error, just nothing happened.
It's unlikely that anyone will see this, since it's very specific, but maybe this'll help someone, at least i know better now
Let me state initially that the code below works fine when I open a new browser page and enter my web server's URL, and it works also when I reload a page (F5 or Ctrl-R).
It only works partially however if I reopen a closed browser window and the browser restores my old tabs: then, the today's date is updated and displayed (see the code below, very simple), but the getJSON() call doesn't seem to be executed. The browser keeps displaying the data from the previous session. Only if I update the page (F5), the data in the browser window is updated.
I'm sure it's not the server. What else could it be?
Browsers: Firefox, Chrome, latest versions.
Using this code in index.html
<script>
$(document).ready(onReady());
</script>
and this code in helper.js
var onReady = function() {
// Display current date
var dateText = moment().format("dddd, Do MMMM YYYY");
var dateHTML = "<h2>" + dateText + "</h2>";
$("#date-col").append(dateHTML);
:
:
// Retrieve data from server and display it
var statText = "Statistics:";
$.getJSON("courses/starter", function(data) {
statText = statText.concat(" " + data.count + " starter");
$.getJSON("courses/dessert", function(data) {
statText = statText.concat(", " + data.count + " dessert");
$("#statistics").text(statText);
});
});
}
You have to pass a callback instead of executing the function immediately.
Try:
<script>
$(document).ready(onReady);
</script>
$( document ).ready(handler) expects argument to be a function expression which will be executed later when DOM is ready
In your example, you are invoking onReady() function and that function is not returning anything(undefined) hence exection will be like: $(document).ready(undefined);
Either use function expression like $(document).ready(onReady); or onReady() should return a function to be executed later.
Shorthand would be $(onReady)
I am new to jQuery, please help.
After window.location.href other functions are not getting called/ aborted.
I am using Spring to catch that url("downloadPack?Name=" + Name + "&ID="+ID) and generating excel file , till this point it is working fine.
below code works perfectly on Firefox and IE , but having issues with Google Chrome only.
var href_red = "downloadPack?Name=" + Name + "&ID="+ID ;
jQuery
.post(
'checkPack',
{
Name :Name,
ID : ID,
Date :Date,
},
function(data) {
if (data == 1) {
window.location.href = href_red;
dialog_load('Download Workbook','downloadOptions', '675px', '630px', 2);
} else {
dialog_error('Error','workbook has not yet been created, please create it first');
}
});
Changing the window.location will kill all scripts currently running in the browser.
So you need to add that code before you are redirecting.
Or other solution is getting a page via AJAX and run a callback function to execute when the content is loaded.
I have a JSON file that is approx 500 lines long. The script that reads in the file is the first thing to happen when the page is loaded. The script works perfectly. It updates a drop down box automatically depending on a users choice.
A moment ago I added an additional 50 lines or so to the JSON file, maintained correct syntax etc etc. When I reloaded the page there was nothing but a white screen, no error logs etc. I removed what I had added to the JSON and received the same white screen, I'd also reloaded the page after clearing cache and on different browsers, same thing.
I then commented out the script that calls the JSON, reloaded and voila, it's fine. I un-comment the script again so it is as it was and magic, it now works.
Can anyone explain what could be happening and how I might solve it please? I can't force it to happen again but that doesn't mean it won't.
Many thanks.
Simplified sample of JSON:
"angle" : [
{
"value":"degree",
"name":"Degree (deg)"
},
{
"value":"grad",
"name":"Grad (grad)"
}]
The script that calls it:
<script>
$.getJSON('JSON/conversionJSON.json', function(data){
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
}
});
});
});
</script>
Thanks
...or Why $(this).dialog() fails in Firefox when using dynamic HTML?
I have a a click event that opens a jQuery modal dialog box on a web page, and it is working fine in Chrome and IE, but not in Firefox.
Here is the pertinent code:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
dialogDiv.load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
In Firefox 11, $(this).dialog({ autoOpen: false }) fails with the following error message:
$(this).dialog is not a function
But in IE 9 an Chrome 17 everything is working fine. Any clue why that is?
UPDATE:
Here is my document.ready function where the code above was. I removed it to simplify things. ALERT A is occuring before ALERT B. ALERT A says [object Object]. ALERT B occurs when I click on a link and it says 'undefined'.
$(function () {
alert($.ui); // ALERT A
// Wire up the click event of any dialog links
$('.dialogLink').live('click', function () {
alert($.ui); // ALERT B
return false;
});
});
UPDATE 2:
Now that I pin pointed where the problem was coming from I rephrased my question and posted the minimal code to reproduce the original problem here: Why is FF on OS X losing jQuery-UI in click event handler?
You've got a bit of a syntax/chaining issue if I'm not mistaken:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
//var dialogDiv = $(document.createElement('div')).attr("id", dialogId);
//dialogDiv equals the attribute 'id'
//try and console.log(dialogDiv) right here. what I think you want is:
var dialogDiv = $("<div />");
dialogDiv.attr("id", dialogId).load(this.href, function () {
var dialog = $(this).dialog({ autoOpen: false });
...
});
I also don't think this is the correct way to initialize what you're trying to do... can you describe what's going on, on your page?
you may think about doing something like this:
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000);
//Build some HTML here in the dialog div, or in a string.
theHTML = $('#'+dialogId).html() || "<p>This is a string of HTML</p>";
$('body').on('click', ".button" function () {
console.log($.ui);
$.dialog({autoOpen:true, html: theHTML})
});
The problem was with a Firefox Add-On. I started Firefox in safe mode, and now everything is working fine. I tried to identify which Add-On caused the problem, and I restarted Firefox with various Add-Ons turned on or off, but I can't seem to be able to reproduce the problem now.