I have the following jquery code, that pulls json data from a url; however, it is giving me the same quote over and over, instead of random. If I use url directly on browser it does randomize the quote. What am I missing? Thanks
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
console.log(a[0].content + " " + a[0].title)
$("#quote-content").html(a[0].content)
$("#quote-title").html(a[0].title)
});
});
You can either turn off AJAX cache for jQuery, like this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
//...
});
Or you could change the url for every request (so it doesn't get cached), something like this could work:
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&"+new Date().getTime(), function(a) {
//...
});
});
});
Also, I don't think you need the callback= parameter
Related
I'm trying to use the ajaxStop function in jquery but can't get it to fire, any ideas?
What I'm trying to do is loop through each anchor tag and then update some content inside it, from there I want to use the ajaxstop event to fire a script to reorganize the anchors based on the updates
Thanks for any help
jQuery(document).ready(function($) {
function updateUsers() {
$(".twitch_user").each(function(index, user) {
$.ajax({ url: "https://api.twitch.tv/kraken/streams/" + $(user).attr("id") + "?callback=?", success: function(d) {
if(d.stream) {
$(user).addClass("online");
$(user).removeClass("offline");
$(user).children(".viewers").text(d.stream.viewers + " viewers");
} else {
$(user).addClass("offline");
$(user).removeClass("online");
$(user).children(".viewers").text("0 viewers");
}
console.log(d);
}, dataType: "json"});
});
}
//$(document).ajaxStart(function() {
// console.log("Event fired!");
// updateUsers().delay(2000);
//})
$(document).ajaxStop(function() {
console.log("Event fired!");
// updateUsers().delay(2000);
});
updateUsers();
});
Apparently the global handlers are turned off when doing JSONP requests, as explained in this ticket:
JSONP requests are not guaranteed to complete (because errors are not caught). jQuery 1.5 forces the global option to false in that case so that the internal ajax request counter is guaranteed to get back to zero at one point or another.
I'm not sure if JSONP is your intention or not, but the ?callback=? on the end of the URL makes jQuery handle it as such.
The solution was to set the following:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
I have 2 different set of codes, the only difference is the location of $(this).closest('.organizer_listing').slideUp('fast');. In the first set of code, it works, but I prefer for that line of code to be as in the 2nd set of code inside the callback function, which no longer works - slideUp does not seem to be executed.
Why is this so? How should I fix it?
Variation 1
$("input[type=checkbox]:checked").each(function() {
$(this).closest('.organizer_listing').slideUp('fast'); // Remove listings visually from list
// Send AJAX request to delete from database
var listing_id = $(this).closest('.organizer_listing').data('listing_id');
$.ajaxSetup({ cache: false });
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
});
});
Variation 2
$("input[type=checkbox]:checked").each(function() {
// Send AJAX request to delete from database
var listing_id = $(this).closest('.organizer_listing').data('listing_id');
$.ajaxSetup({ cache: false });
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
$(this).closest('.organizer_listing').slideUp('fast'); // Remove listings visually from list
});
});
Variation two doesn't work because in your $.getJSON callback, this is no longer the current element in your each loop, but rather the jqXHR object.
You can easily work around this by saving the value of this to a new variable, which your callback will "close over" (have access to):
var self = this;
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
$(self).closest('.organizer_listing').slideUp('fast'); // Remove listings visually from list
});
It does not work anymore because this in the callback of the $.getJSON is not anymore your checkbox !
Do this:
$("input[type=checkbox]:checked").each(function() {
var $cb = $(this); // save your ref to the checkbox
var listing_id = $cb.closest('.organizer_listing').data('listing_id');
$.ajaxSetup({ cache: false });
$.getJSON(base_url + 'organizer/delete_favorite',
{listing_id: listing_id},
function(json) {
$.modal.close();
// use $cb
$cb.closest('.organizer_listing').slideUp('fast');
});
});
When you want to use it, you should always ask yourself what is the value of this in the current context.
I'm stuck in a rut. I hope some one can help.
Basically, I am building an AJAX mobile web app with jQuery. I am able to parse a specific XML file just fine, but I want the option to parse other XML files based on the link they were clicked on and load them on the fly into the same DIV or UL.
So:
click on Link1, loads XML1
click on Link2, loads XML2
I would like to be able to do this all client side, so no PHP (or is that a bad idea?). This the jquery code I've been using:
$(document).ready(function() {
$("a.load_ajax").click(loadAjax());
function loadAjax() {
var fileID = get('?lineID=');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
}
});
Its just not working at all. I have been passing the variable using GET in the url. So the link in the HTML goes to /?lineID=SBD_to_Union and it should load the XML file called SBD_to_Union.xml
Making sense to anyone? I'd appreciate some help.
What you seem to be struggling with is obtaining the line from the url in the anchor. Use $(this) to get the href attribute of the clicked link. You could then use a regex, if the url is as described, to remove all but the line id to use in constructing the link for the XML. I presume that the XML is server side and relative to the current url. If not, then you'll need to adjust the path. I've taken the liberty to compress things a bit by putting the functions inline. Edit: and the click handler should return false to prevent the link from actually performing its default action.
$(function() {
$("a.load_ajax").click( function() {
var fileID = $(this).attr('href').replace(/.*?lineID=/,'');
var dataID = "xml/" + fileID + ".xml"
$.ajax({
type: "GET",
url: dataID,
dataType: "xml",
success: function(xml) {
$(xml).find("train").each(function() {
$("ul#ajax-output").append('<li>' + $(this).find("time").text() + '</li>');
});
}
});
return false;
});
});
Have you checked if the get function returns the correct data ?
add an alert(fileID); right after the get(..); line..
But why don't you create the urls to point directly to the xml files instead of parsing and creating urls on the fly ?
just make the link in the html to point to xml/SBD_to_Union.xml
On first glance, I think your ajax() syntax is a little off.
Are you using query strings for a particular reason? If no, I'd try giving the HTML links the absolute URL to the XML file you are trying to fetch:
Then try this:
$("a.load_ajax").click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
type: 'GET',
url: url,
dataType: 'xml',
success: function(response) {
$(response).find('train').each(function() {
$('ul#ajax-output').append('<li>' + $(this).find('time').text() + '</li>');
}
});
});
I haven't tested this, but it should do what you want.
Link1
Link2
You can do things depending on the id of the href (or another of its attributes or its href value).
$(function() {
$("a.load_ajax").click(loadAjax);
});
function loadAjax()
{
if ($(this).attr("id") == "link1")
{
alert("link1"); //load xml1
}
else
{
alert("link2"); //load xml2
};
}
Why does the return false stop the alert() from working and how do I get around this? If I remove it, the alert will show up, and then it will load the page that the <a> tag pointed to.
<script type="text/javascript">
$("document").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.getJSON(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
My guess is that badly formed JSON is being sent to the client, which will prevent the callback from firing. The manual says:
If there is a syntax error in the JSON
file, the request will usually fail
silently. Avoid frequent hand-editing
of JSON data for this reason.
Can you show us a snapshot of the JSON that the server is generating?
Answer Update!
I have tested this thoroughly using the $.ajax functions, which is what actually gets called by $.getJSON.
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
}
});
}
return false;
});
});
With a correctly formatted JSON object, this works as expected. Here is the contents of my json.html test file:
{ "firstName" : "John",
"lastName" : "Doe",
"age" : 23 }
However, if the file contains HTML, or a badly formatted JSON object, the alert never gets called - in fact, by adding an error handler to the above example, you'll spot that it errors:
$("document").ready(function(){
$("a").click(function(event){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.ajax({
url: href,
dataType: 'text',
success: function(data) {
alert("hi");
},
error: function() {
alert("NO!!!!");
}
});
}
return false;
});
});
As you are replacing hyperlinks in your code with this request, I'm guessing that you maybe want to use a $.get, rather than a $.getJSON. So to return to your original example:
<script type="text/javascript">
$("document").ready(function(){
$("a").click(function(){
if(!$(this).is('static')){
var href = $(this).attr('href');
$.get(href, function(data) {
alert('hi');
});
}
return false;
});
});
</script>
This seems to work in Firefox 3 and in Chrome, with both get and getJSON.
IE8 is another story (I presume the same goes for IE7). There, only get works; getJSON fails. Is the JSON being returned by the server not IE-friendly?
After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.