I have JS file hosted at https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js
When I run the following script on the browser console
jQuery.getScript("https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js")
.done(function() {
alert("done");
})
.fail(function() {
alert("fail");
});
I get a popup that says "done", but when I run
version.number()
the following error message is returned
ReferenceError: version is not define
Why is "version" not defined if the script is supposedly loaded properly?
Your script at has a syntax error, so it cannot be parsed. Correct your script, and version.number() will come:
var version = {
number: function() { return "1.1"; }; <==Syntax error here
}
Of course you must call version.number() from inside .done(function () {...})
EDIT
Ok i solved it for you, you need to change that uploaded file to this:
var version = {
number: function() { return "1.1"; }
}
you have a ; to much in that code.
And this is your new javscript/jquery code:
$.getScript( "https://cdn.rawgit.com/DarkPotatoKing/darkpotatoking.github.io/master/latest_version.js" )
.done(function( script, textStatus ) {
console.log(version.number);
})
.fail(function( jqxhr, settings, exception ) {
console.log("nope");
});
OLD
This is because your code is not in sync.
if you run version.number() inside the .done it must work.
Related
I'm trying to lazy-load images using the following script (lazy-load.js):
function lazyLoadImage(imgContainers) {
var img = $('<img src="">');
imgContainers.each(function (i, elm) {
img.attr('src', $(elm).data("large"));
img.on('load', function () {
$(this).addClass('loaded');
});
img.addClass('picture');
$(elm).append(img.clone(true));
});
}
$(window).on('load',function () {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
});
The problem is, everything goes well if I load the script using <script></script> tag but when the script is loaded dynamically using jquery $.getscript() the script is not working consistently (i.e. sometimes the onload event is not triggering).
Loading script dynamically:
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
});
So, why the script is not working consistently??
window.load fires when the window finished loading. It doesn't fire a second time when you load more content via ajax because there is no way to tell for the browser when you will be finished loading additional content. So for all stuff you do via ajax you have to execute all functionality again.
In your case I guess you want these things to happen:
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
So I would say put this in a function and just call it when you finish loading the script:
function lazyloadimages() {
var imgContainers = $(document).find(".img-container:not(:has(.loaded))"); // images not loaded yet
lazyLoadImage(imgContainers);
}
$(window).on('load',function () {
lazyloadimages(); // notice this change, put the stuff in an extra function so you can reuse it!
});
$.getScript( "path/to/lazy-load.js" )
.done(function( script, textStatus ) {
console.log( "script loaded' );
lazyloadimages();
})
.fail(function( jqxhr, settings, exception ) {
console.log( "script not loaded' );
// oh no something went wrong, no need to lazyload something here!
});
On my Polymer-Page I try to login to my google-plus page and retrieve my name and cover-photo url.
For that purpose I use a google-signin element that runs the following function when login finishes:
loginSuccess: function(e){
console.log("Success!");
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(function(retr){
console.log("Data Loaded");
console.log(retr);
this.myFunction(retr);
});
});
}
Up to "Data Loaded" everything works great, also the console prints out the whole result object from google plus. But I am not able to execute functions (this.myFunction) or access data from polymer there. How do I store the result data from the gapi-request into my polymer variables???
Thanks, Malte
Inside the Ajax result, the this context is different. You need to setup a variable before your ajax request, or before your function to access it, like so :
self: this,
loginSuccess: function(e){
console.log("Success!");
gapi.client.load('plus', 'v1', function() {
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute(function(retr){
console.log("Data Loaded");
console.log(retr);
self.myFunction(retr);
});
});
}
I just found out, that i chose the wrong way to get my profile-data.
There is a polymer element to get data from the google-api called google-api-loader (http://googlewebcomponents.github.io/google-apis/components/google-apis/#google-api-loader). I use that element the following way additionally to the google-signin element:
<google-api-loader id="plus" name="plus" version="v1"
on-google-api-load="{{displayProfile}}">
</google-api-loader>
Here the function displayProfile
displayProfile: function(){
if (this.signedIn && this.$.plus.api) {
var request = this.$.plus.api.people.get({"userId": "me"});
request.execute(function (resp) {
this.userData = resp;
}.bind(this));
}
}
It works awesome and I get access to the data via this.userData. Here it another example: https://github.com/Scarygami/google-signin-samples/blob/master/elements/google-signin-status.html
The following code gives me an error like this when I request a page and it comes back 404. Instead it should bring up an alert. What is strange is it only does this on links that have been ajaxed in, on links that don't update/change it works fine.
('.page-wrap').append('<img src="img/graphics/ajax-loader.gif" class="ajax-loader" />');
var target = $('section.content'),
siteURL = 'http://' + top.location.host.toString(),
internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']"),
links = $('a'),
URL,
el,
mainContent,
headContent,
headClasses,
pageName,
ajaxSpinner = $('.ajax-loader');
internalLinks.click(function(e) {
el = $(this);
URL = el.attr('href');
$('.current_page_item').removeClass('current_page_item');
el.addClass("current_link").parent().addClass("current_page_item");
ajaxLoader(URL, false);
e.preventDefault();
});
function ajaxLoader(location, isHistory) {
$("html, body").animate({ scrollTop: "0px" });
ajaxSpinner.show();
$('.page-wrap').css('opacity', '0.5}');
// Load New Page
$.get(location, function(data) {
mainContent = $('section.content', data).html();
headContent = $('.feature-content', data).html();
pageName = $('.page-name', data).html();
headClasses = $('header', data).attr('class');
$('section.content').html(mainContent);
$('.page-name').html(pageName);
$('.feature-content').html(headContent);
if (headClasses) {
$('header').attr('class', headClasses);
} else {
$('header').removeClass();
}
if (!isHistory) {
history.pushState(location, '', location);
}
$(resizeHeader);
ajaxSpinner.fadeOut();
}).error(function() {
alert('woops'); // or whatever
});
}
w.bind('popstate', function(event) {
if (event.originalEvent.state !== null ) {
ajaxLoader(event.originalEvent.state, true);
}
});
First thoughts
Is it perhaps the case that something in your success handler code is causing an error of some kind? Like maybe the injection of whatever html that comes back the first successful time is causing the script to fail a second time?
What do you see playing out in your your Fiddler/Firebug/F12 developer tool of choice - you are using one of these, right? :) Keep an eye on any console errors...
Second thought
What jQuery version are you using?
I have tested this with jq 1.8.2 and the error handler works just fine for me, but if this is a JSONP request it won't trigger the error() function. I took the gist of your code:
$.get(
"404MeBaby.html", function (data) {
$(".result").html(data);
console.log(data);
}
).error(
function (x) {
console.log("well that didn't go so well...");
});
From the API:
As of jQuery 1.5, the success callback function is also passed a
"jqXHR" object (in jQuery 1.4, it was passed the XMLHttpRequest
object). However, since JSONP and cross-domain GET requests do not use
XHR, in those cases the jqXHR and textStatus parameters passed to the
success callback are undefined.
You could try using $.ajax instead as it gives a lot more control. Or, you can set the jQuery global ajax options as shown here that will affect all $.get calls, but remember the curse of JSONP, if relevant!
After last update of firefox (I asssume) I have problem with firebug console. In my app when I combine app.refresh() with setting observable on get "too much recursion" is thrown and firefox is not responding. When I close firebug console everything works well.
In my viewmodel I have:
self.firstStep = ko.observable();
var app = Sammy(function () {
this.before({ only: { verb: 'get', path: URL.FirstStep } }, function (context) {
console.log("before");
});
this.get(URL.FirstStep, function () {
self.firstStep(new firstWindow());
console.log("get");
});
});
self.LoadData = function () {
$.ajax({
//...
success: function (data) {
//here is commented out because of debuging the problem
},
complete: function () {
app.refresh();
}
});
};
app.run();
self.LoadData();
Get in console is logged once, before is logged twice. When I comment out self.firstStep(new firstWindow()) get is fired twice too.
In chrome everything works fine. Help really appreciated.
EDIT: #Mörre
When I modify code like:
this.get(URL.FirstStep, function() {
self.firstStep = ko.observable();
self.firtStep(new firstWindow());
console.log("get");
});
it is working.
Disable the "Script" panel fix the issue for me, if you don't need to debug JavaScript using the "Script" panel.
Here is the script. It works fine in all other browsers, so I thought it was a cache problem but not really. I have been banging my head for hours and nothing is working.
$.ajaxSetup({
cache: false
});
$("#send").live('click', function () {
console.log("AAAAA");
$("#loader").show();
$form = $('#reservationForm');
$inputs = $form.find('input[name^="entry"]'),
serializedData = $('#reservationForm :input[name^="entry"]').serialize();
console.log(serializedData);
serializedData += "&pageNumber=0&backupCache=1&submit=Submit";
// fire off the request to /form.php
$.ajax({
url: "https://docs.google.com/spreadsheet/formResponse?formkey=d",
// url: "https://docs.google.com/spreadsheet/formResponse?formkey=d;ifq",
type: "post",
data: serializedData,
// callback handler that will be called on success
success: function (response, textStatus, jqXHR) {
// log a message to the console
console.log("Hooray, it worked!");
$("#loader").hide();
document.getElementById('error<?php echo"$uname";?>').innerHTML = error;
$("#success").fadeIn();
setTimeout(function () {
$("#success").fadeOut();
}, 5000);
},
// callback handler that will be called on error
error: function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.log("The following error occured: " + textStatus, errorThrown);
alert('Due to an unknown error, your form was not submitted, please resubmit it or try later.');
},
// callback handler that will be called on completion
// which means, either on success or error
complete: function () {
// enable the inputs
$inputs.removeAttr("disabled");
}
});
// prevent default posting of form
event.preventDefault();
});
console.log is available after you open Developer Tools (F12 to open) in IE. Try turning it on or use an alert instead in your code.
or use a try catch;
try{
console.log('worked')
}
catch(err){
}
And You might want to check if your event variable is undefined:
event= event || window.event;
event.preventDefault();
At the beginning of the script you are not adding the "event" declaration in the handler:
$("#send").live('click', function () {
should be:
$("#send").live('click', function (e) {
And at the end of the script there is a reference for the variable event:
// prevent default posting of form
event.preventDefault();
I think that IE doesn't have a 'preventDefualt' function in the global event object (which you are referencing): this function is added to the "e" event object passed by jQuery. Any way, it should fail too in all other browsers with a "event is not defined". Try this too:
// prevent default posting of form
e.preventDefault();
An additional note: jQuery team currently discourage the use of the "live" event binding function, instead you should use the equivalent form of the "on" function.
IE doesn't understand the content type of response in ajax. So put your dataType value in the request and it should work.
for e.g. -
dataType: ($.browser.msie) ? "text" : "xml"