appendChild not working and showing error - javascript

I have a js which is showing error in javascript console Cannot call method 'appendChild' of null in this file:
(function(d) {
if( typeof jQuery === 'undefined' ) {
var srsr = d.createElement('script');
srsr.src = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js';
d.body.appendChild(srsr);
setTimeout(function(){ doThat(); }, 5000);
} else {
doThat();
}
function getHost( url ) {
var a = document.createElement('a');
a.href = url;
var host = a.hostname;
var t = host.split(".");
if( t.length == 2 ) {
var host = "www."+host;
}
return host;
}
function doThat() {
$.ajax({
url: 'http://mobilesplashpro.com/app/assets/php/tRaCk_loAdInG_PoPUp.php',
type: 'GET',
data: 'adrs='+getHost( document.domain ),
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'methodCallback',
success: function( data ) {
if( data.message == "yes" ) {
$.getScript("http://mobilesplashpro.com/app/assets/js/popup/PoPUp_txt_CoDE.js",function() { iPhoneAlert(); });
} else {
}
},
error: function( error ) {
console.log( error );
}
});
}
})( document );
have used Appendchild code in another file which is working perfectly but not in it..
Thanks

First of all, place this code in the end of your body (if this is in your head, the body doest not exists), if you must place it in the head, you should make some sort of interval untill you simulated a DomReady event (That garantees you have a document.body to traverse).
Example:
var intervalDomReady = setInterval(function() {
if (document.body) {
clearInterval(intervalDomReady);
intervalDomReady =null;
DomReady();
}
},500);
function DomReady() { /*you code*/ }
You only have the reference to jquery from google CDN once it is loaded. So you will not have sure that It will happen in 5 secs, must first bind to the onload event of the script an then try to use jquery functions.
Example of solution:
var d = document;
var srsr = d.createElement('script');
srsr.src = '//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js';
srsr.src.onload = function() { doThat(); }

Because this is running when the document loads, it's a valid use-case for document.write.
It'll also simplify things if you use document.write to load the script, since it'll load the script synchronously.
As a result, you would eliminate the need for the doThat() function, and the setTimeout.
So first put your jQuery check and script loading code in a separate script at the top...
<script type="text/javascript">
if( typeof jQuery === 'undefined' ) {
document.write('<scr' + 'ipt src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"><\/scr' + 'ipt>');
}
</script>
Then put your main script in a separate script below the one above...
<script>
(function(d) {
function getHost( url ) {
var a = document.createElement('a');
a.href = url;
var host = a.hostname;
var t = host.split(".");
if( t.length == 2 ) {
var host = "www."+host;
}
return host;
}
$.ajax({
url: 'http://mobilesplashpro.com/app/assets/php/tRaCk_loAdInG_PoPUp.php',
type: 'GET',
data: 'adrs='+getHost( document.domain ),
dataType: 'jsonp',
jsonp: false,
jsonpCallback: 'methodCallback',
success: function( data ) {
if( data.message == "yes" ) {
$.getScript("http://mobilesplashpro.com/app/assets/js/popup/PoPUp_txt_CoDE.js",function() { iPhoneAlert(); });
} else {
}
},
error: function( error ) {
console.log( error );
}
});
})( document );
</script>
Now if jQuery isn't loaded, the new script will be written and loaded below the first, and above the second, and we never had to perform any sort of DOM selection.

Related

How to add second link to script in JqueryWidget code

I have written a widget and it works great, but right now I am giving my users a link to a remote script, a link to my script and a div to place on their page. I would like to reduce this to just a link to my script and the div. The remote link I want to include in my code below is
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
Can anyone please educate me on how to add a second link in my code? I already link to a remote jquery and a remote stylesheet, but I am not sure how/where to include another remote link. I have tried a number of places and ways, but I keep breaking my page, haha. Thanks for any help offered.
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "//code.jquery.com/jquery-1.12.4.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonURL = "//www.myurl.com/mssql.php/ws_nfy";
jQuery(document).ready(function() {
jQuery.ajax({
url: jsonURL,
success: searchCallback
});
});
function searchCallback(data) {
var ws_nfy = data.ws_nfy.records;
jQuery.each(ws_nfy, function(index, nfy) {
jQuery("#tabs ul").append('<li>' + nfy[2] + '</li>');
jQuery("#tabs ul").after("<div id='tabs-" + nfy[0] + "'>" + nfy[1] + "</div>");
});
$("#tabs").tabs();
};
});
}
})(); // We call our anonymous function immediately
You're checking if jQuery is already loaded before injecting it... Which is good. Now you should do the same for jQuery-UI.
So that's the same procedure...
Try this:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.12.4') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src", "//code.jquery.com/jquery-1.12.4.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function() {
// For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
//main(); // Not now! Check for UI first.
checkUI();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
//main(); // Not now! Check for UI first.
checkUI();
}
// ========================== Check if jQuery-UI is already loaded
function checkUI(){
if(typeof(jQuery.ui) != "undefined"){
// UI is loaded already.
console.log("UI is defined");
console.log( typeof(jQuery.ui) );
main();
}else{
// UI is not loaded. Got to load it.
console.log("UI is NOT defined");
//console.log( typeof(jQuery.ui) );
var ui = document.createElement('script');
ui.setAttribute("type", "text/javascript");
// For UI
window.$ = jQuery;
ui.setAttribute("src", "https://code.jquery.com/ui/1.12.1/jquery-ui.js");
console.log(ui);
document.getElementsByTagName("head")[0].appendChild(ui);
if (ui.readyState) {
console.log( "READYSTATE" );
ui.onreadystatechange = function() { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
console.log( "STATELOADED" );
main();
}
};
} else {
console.log( "ELSE" );
jQuery(ui).on("load", function(){
console.log("UI loaded...");
main();
});
}
}
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
console.log("jQuery: "+jQuery.fn.jquery+"\njQuery-UI: "+jQuery.ui);
console.log("Tabs element: "+jQuery("#tabs").length);
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonURL = "//www.myurl.com/api.php/ws_nfy";
jQuery.ajax({
url: jsonURL,
success: searchCallback
});
function searchCallback(data) {
var ws_nfy = data.ws_nfy.records;
jQuery.each(ws_nfy, function(index, nfy) {
jQuery("#tabs ul").append('<li>' + nfy[2] + '</li>');
jQuery("#tabs ul").after("<div id='tabs-" + nfy[0] + "'>" + nfy[1] + "</div>");
});
jQuery("#tabs").tabs();
};
});
}
})(); // We call our anonymous function immediately

Two instances of Widget Only One Instance Working

I have a widget that only works with one instance.
The problem I have is that if I have one instance of the widget on a page it works fine. If I have more than one instance on the page, only one instance works. The second instance does not work...
you can check this page for an example http://fullylinked.com/advert.php
From my troubleshooting, I have noticed the following
1. The placement ID of the second instance is not passed to the script.
2. Even if the default placement ID is used, I get an error saying
"Uncaught ReferenceError: jsonpCallback is not defined".
Unfortunately the jsonpCalback is defined because the first script works..
Please here are my code..
The Widget...
<script placementID = "37" src="placement.js" type="text/javascript"> </script>
<div id="widget-container_37"></div>
---- Second instance below this line -------
<script placementID = "36" src="placement.js" type="text/javascript"></script><div id="widget-container_36"></div>
NOW HERE IS THE .JS file
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
/** var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/**** get host name ***/
var site_name = window.location.hostname;
/****** get user ID******/
var this_js_script = $('script[src*=placement]'); // get file name..*/
var placementID = this_js_script.attr('placementID');
/**var placementID = document.getElementById("adblabla_2").getAttribute("placementID");**/
if (typeof placementID === "undefined" ) {
var placementID = '23';
}
/******* Load HTML *******/
$.ajax({
url: 'processors/processor.php?placementID='+placementID,
data: {name: 'Chad', site: site_name},
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
success: function(data){
//alert(placementID);
$('#widget-container_'+placementID).html(data.message);
}
});
});
function jsonpCallback(data){
$('#widget-container_2').text(data.message);
}
}
})();
The reason is another then I thought, your code is already encapsulated, so its not calling twice the same main function, but it finds twice the same script tag, and thus gets the wrong parameter I think.
http://www.2ality.com/2014/05/current-script.html
Well you can try this code:
(function () {
// Localize jQuery variable
var jQuery,
//get current script
currentScript = document.currentScript || (function () {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function ($) {
/******* Load CSS *******/
/** var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/**** get host name ***/
var site_name = window.location.hostname;
/****** get user ID******/
var this_js_script = $(currentScript); // get file name..*/
var placementID = this_js_script.attr('placementID');
/**var placementID = document.getElementById("adblabla_2").getAttribute("placementID");**/
if (typeof placementID === "undefined") {
var placementID = '23';
}
/******* Load HTML *******/
$.ajax({
url: 'processors/processor.php?placementID=' + placementID,
data: {name: 'Chad', site: site_name},
dataType: 'jsonp',
jsonp: 'callback',
success: function (data) {
//alert(placementID);
$('#widget-container_' + placementID).html(data.message);
}
});
});
function jsonpCallback(data) {
$('#widget-container_2').text(data.message);
}
}
})();
PS: its always very useful when you build up a testcase on http://jsfiddle.net/

jQuery - preventDefault() in .each function

I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/

Execute completeAjax only once

I need to fire a function on completion of an already running ajax on the page. The function I want to update will update wishlist item counter and the function which is previously running saves item in wishlist.
The problem is (what I've figured out) - after making (initializing) ajax request, while waiting for success msg, the function again executes itself.
Bottom line, I want ajaxComplete function part to run only once ever. Please point me in right direction
jQuery(document).ready( function() {
var token = false;
jQuery( '.add_to_wishlist' ).on( 'click', function() {
if( token == false ) {
jQuery(document).ajaxComplete(function() {
console.log('Entered Click!');
token = true;
jQuery.ajax({
url: wishajax.ajax_url,
data: {
action: 'vg_inject_wish',
},
success: function( response ) {
console.log('Entered Success!');
jQuery( '.wishlist-container' ).html( response );
console.log('After Success!');
token = true;
}
});
});
}
});
});
jQuery(document).ajaxComplete is an independent event. Why are you combining it inside click event and writing again jQuery.ajax inside it? Separate the concerns as below:
jQuery(document).ajaxComplete(function() {
token = true;//If you need this only in success then no need to put it here as this
//will get executed irrespective of ajax result
});
jQuery( '.add_to_wishlist' ).on( 'click', function() {
if( token == false ) {
jQuery.ajax({
url: wishajax.ajax_url,
data: {
action: 'vg_inject_wish',
},
success: function( response ) {
console.log('Entered Success!');
jQuery( '.wishlist-container' ).html( response );
console.log('After Success!');
token = true;
}
});
}
});
maybe this can help you to
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
taken from the blog of David Walsh.

Reinitialise JScrollPane after AJAX post loading

Im'm loading posts in a div #reviewspostscont, the AJAX code works and the posts are loaded when the scrollbar gets to the end but I can't reinitialise JScrollPane to show them.
I tried different codes but nothing works, this is what i have so far.
Thanks in advance, Matt
jQuery(document).ready(function($) {
$(function()
{
$('#reviewspostscont').each(
function()
{
$(this).jScrollPane(
{
horizontalDragMaxWidth : 100
}
);
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind(
'resize',
function()
{
if (!throttleTimeout) {
throttleTimeout = setTimeout(
function()
{
api.reinitialise();
throttleTimeout = null;
},
50
);
}
}
);
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight)
{
var count = 2;
if (isAtRight == true) {
loadArticle(count);
var api = $(this).data('jsp');
api.reinitialise();
count++;
}
}
);
}
)
});
function loadArticle(pageNumber){
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop-reviews',
success: function(html){
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});
You can use autoReinitialise. Here's a demo showing a similar example. And another one. And another.

Categories