Odd Javascript behavior - porting to WordPress - javascript

I'm currently making my first effort into porting a webpage to Wordpress, so forgive my inexperience on the subject.
In my page, I have the following code:
function workLoad() {
$.ajaxSetup({ cache: false });
$('.thumb-unit').click(function() {
var $this = $(this),
newTitle = $this.find('strong').text(),
newFolder = $this.data('folder'),
spinner = 'Loading...',
newHTML = 'work/'+ newFolder +'.html';
$('.project-load').html(spinner).load(newHTML);
$('.project-title').text(newTitle);
});
}
In the past, this has worked fine hosted both locally and on Github. However, running my wordpress build locally through MAMP gives me the following error:
jquery-2.1.1.min.js:4 GET http://localhost/work/proj-1.html?_=1485348127113 404 (Not Found)
The URL should be fine, except for the part where it adds the ?_=(number). I'm not familiar with this behavior or what causes it. I tried changing work/ to /work/, since the dir is in the root folder, but that didn't solve it. I also have tried changing the variable to
newHTML = '< ?php bloginfo('template_directory')' + '/work/'+ newFolder +'.html';without the space after the opening bracket but to no avail. I also tried putting that bit in its own var, but it keeps adding ?_=1485348127113 to the URL of the html file I want to load, resulting in a 404 error.
What causes this? Thanks in advance for any advice you could share.

This timestamp is added for You to obtain the latest version of the file using ajax load.
If You want to disable this behaviour, You should set
$.ajaxSetup({
cache: true
});
This will enable caching and Your request would not contain the ?_=1485348127113 part anymore. This parameter should not cause the 404 not found error. Please check your path.

Related

Handsontable not scrolling properly on Chrome

I am currently having an issue with handsontable on Chrome. What appears is that the table is scrollable, but the values and row headings are not updating. The situation can be seen from the below pictures.
Not Scrolled
Scrolled to Right and Down
As you can see, the scrolling takes place, but the values do not update. I should note, that this behavior only happens on Chrome. On Firefox and Safari, the table works as expected.
So more information about my environment.
Using Handsontable 0.28.0
Also using AngularJS and Angular Material
The code that I used to create this example is as follows
var Handsontable = require('handsontable');
// This function finds a div I am using, removes its contents, and then creates the table.
$scope.setSheet = function() {
var elementID = "shreadsheet-" + $scope.tabData.id;
var element = document.getElementById(elementID);
element.innerHTML = '';
var readonlyArr = $scope.tabData.sheetHeaders.map(function() {
return {readOnly : true};
});
var hot = new Handsontable(element, {
data: Handsontable.helper.createSpreadsheetData(1000, 1000),
colWidths: 47,
rowHeaders: true,
colHeaders: true
});
};
I compiled this code using the following command I found in the docs at the Handsontable github page.
SheetController_work.js -o SheetController.js -r moment -r pikaday -r zeroclipboard -r numbro
Has anyone else experienced this problem on Google Chrome, or does anybody have any suggestions?
Thanks.
For me this problem magically went away. The things that happened in the time that I noticed that this problem exists and the time that it magically fixed itself are as follows. You may want to try some of these if you experience this problem.
Restarted Computer (didn't work by itself)
Turned off localhost server from terminal and navigated to different directory.
Quit terminal.
Quit Google Chrome
EDIT with proper solution
I removed the paramater variableRowHeights: false and everything works now.

SCRIPT5 : Access is denied on IE-10 after Security Update : jquery-1.4.4.min.js

There was an IE-10 security update on Sept-10. After that, in my application there seems to be an issue accessing a standard div using jquery.
Here is the quick scenario :
I have a jsp layout template where there is a div defined :
<div id="abc"></div>
In that I include a js file k1.js, the following function in that is triggered upon a click of a button
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
jQuery("#abc").html(data);
});
This was totally functioning across all browsers including ie-10 till Sept -10. After 10th, it still works fine on IE-9 and old IE-10 builds, but on new IE-10 build throws the error in console :
SCRIPT5 : Access is denied
The call stack pointed to internals of Jquery code which I couldn't decipher/understand the context.
The quick fix was to replace the jquery with Javascript, and it worked :
function sample() {
jQuery.get("/fetchmedata.do?a=true", function(data) {
document.getElementById('abc').innerHTML = data;
});
The jquery version was jquery-1.4.4.min.js.
Please advice on what could have been the issue, is it again probably related to not using XDomainRequest instead of XHR, so that we could take precautions in the code to avoid future issues.
Also what is the best practices around it ?
Please advice.

How to update user script in greasemonkey

I have an issue with Greasemonkey, it doesn't update my script automatically (probably because we don't want to add it to its UserScripts root, and it seems in this case it doesn't update it)...
anyway, I was adding a piece of code (main idea from here) to my script to check the script version inside the script and let user know if there is a new version available, and as if user wants to update it, if so it should open a new window/tab for script url (that it should trigger Greasemonkey to install it)... this is my senario, and it works perfect up to the point that it should open a new window/tab...
here you can see the function I'm using:
function checkForUpdate(in_vid){
var plugin_url = 'https://MyWebSiteURL/MonaTest.user.js?'+new Date().getTime();
if ((parseInt(GM_getValue('SUC_last_update', '0')) + 86400000 <= (new Date().getTime()))){
try {
GM_xmlhttpRequest( {
method: 'GET',
url: plugin_url,
headers: {'Cache-Control': 'no-cache'},
onload: function(resp){
var local_version, remote_version, rt, script_name;
rt=resp.responseText;
GM_setValue('SUC_last_update', new Date().getTime()+'');
remote_version = parseFloat(/#version\s*(.*?)\s*$/m.exec(rt)[1]);
local_version = parseFloat(GM_getValue('SUC_current_version', '-1'));
if(local_version!=-1){
script_name = (/#name\s*(.*?)\s*$/m.exec(rt))[1];
GM_setValue('SUC_target_script_name', script_name);
if (remote_version > local_version){
if(confirm('There is an update available for the Greasemonkey script "'+script_name+'."\nWould you like to install it now?')){
-------> GM_openInTab(plugin_url);
//window.open(plugin_url,'_blank')
//location.assign(plugin_url);
GM_setValue('SUC_current_version', remote_version);
}
}
else{
GM_log('No update is available for "'+script_name+'"');
}
}
else{
GM_setValue('SUC_current_version', remote_version+'');
}
}
});
}
catch (err){
GM_log('An error occurred while checking for updates:\n'+err);
}
}
}
I tried to use GM_openInTab, but it returns this error in the console:
Timestamp: 9/27/12 9:55:33 AM
Error: ReferenceError: GM_openInTab is not defined
Source File: file:///Users/Mona/Library/Application%20Support/Firefox/Profiles/tonwb5lg.default/gm_scripts/MonaTest/MonaTest.user.js
Line: 97
I couldn't find any reference to indicate that GM_openInTab doesn't support anymore!
I tried other solutions, using window.open and location.assign... both of them doesn't work because they shows the script source codes without triggering Greasemonkey to install it...
I don't know if there is a way to update script using this method...
I would appreciate if you share your knowledge and help me with my problem.
Thanks for your time!
P.S. My firefox version is 15.0.1, Greasemonkey version is 1.1
don't forget to #grant.
correct me if im wrong, but your script does not end with js.
var plugin_url = 'https://MyWebSiteURL/MonaTest.user.js?'+new Date().getTime();
try forcing the .js extension.
when i added the date to my script, GM stopped installing it.
remove the date at the end and give it a try.
one last thing: you're basing your script on a script from 2009. take a look at a new one, like this from 2011.

How do I load an external file and make sure that it runs first in JSFiddle?

I have a JsFiddle here, and added Microsoft AJAX to be loaded through external JS/resource section. How can I tell whether or not my JS code is run after the AJAX file has finished loading?
Seems that the AJAX does not load either. :(
Here is the code in the JSFiddle:
Type.registerNamespace("Tutorial.Chapter1");
Tutorial.Chapter1.Person = function(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
};
Tutorial.Chapter1.Person.prototype = {
set_firstName: function(value) {
this._firstName = value;
},
get_firstName: function() {
return this._firstName;
},
set_lastName: function(value) {
this._lastName = value;
},
get_lastName: function() {
return this._lastName;
},
_firstName: "",
_lastName: "",
displayName: function() {
alert("Hi! " + this._firstName + " " + this._lastName);
}
};
Tutorial.Chapter1.Person.registerClass("Tutorial.Chapter1.Person", null);
The External Resources tab of jsFiddle is currently somewhat tricky and unstable to use.
The resources defined here are often not correctly included into the code. There seems to be an issue with the automatic recognition of JS and CSS resources. If this happens, the external resource is simply not added to the head section of the resulting code. You can check that by reviewing the source code of the Result frame of your jsFiddle. You will find that your MS AJAX resource is simply NOT mentioned in the resulting HTML code.
The correct recognition can actually be forced by adding a dummy value to the resource's URL like this (see –>jsFiddle docs for more info):
...&dummy=.js
Here is an example that shows how to add the external Google Maps API resource to a jsFiddle (mind the dummy parameter at the very end!):
https://maps.googleapis.com/maps/api/js?sensor=false&dummy=.js
Unfortunately this won't work for you as the MS AJAX URL will fail when additional parameters are appended.
A solution (and currently the safest way to load external resources) is to avoid the External Resources tab altogether and load external code manually in the first line(s) of jsFiddle's HTML window like this:
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/3.5/MicrosoftAjax.js"></script>
Here is your jsFiddle modified to use that method: http://jsfiddle.net/rEzW5/12/
It actually does not do a lot (I did not check what is wrong with the rest of your code), but at least it does not throw JavaScript errors anymore.
Open "Add Resources" section and add the url of your external script...
#Jpsy's approach no longer seems to work (see my comment under his answer).
For me, adding the resource under External Resources also didn't work. (According to the Firefox Debugger, it couldn't find the resource).
The only way I was able to get an external bit of JavaScript code (in my case jquery.backstretch.js) to work, was to use Google to find a Fiddle which used this resource (and worked), then Fork this Fiddle and copy/paste all my code into the HTML, CSS and JavaScript panels. Ugh!
#clayRay, You absolutely went thru a code surgery. Just resolved that by mentioning external source in plain html which in my case is
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
Using External Resources tab didn't help a bit...

Jquery - how to load everything except the images?

I'm currently working on a WordPress addition which loads full post content (normally it shows exceprts) when asked to. I did my code like this:
$(".readMore").click(function() {
var url = $(this).attr("href");
$(this).parent("p").parent("div").children("div.text").slideUp("slow", function () {
$(this).load(url + " .text", function(){
$(this).slideDown("slow");
});
});
$(this).parent("p").fadeOut();
return false; });
And it works. But I don't want images to be loaded. I tried .text:not(img), but it didn't worked. How can I do this?
The trick, of course, is preventing the images from being downloaded unnecessarily by the user's browser; not displaying them is easy.
I only have two browsers were it's easy and convenient to tell what's downloading: Chrome and Firefox+Firebug. In my tests, Martin's solution using *:not(img) results in the images being downloaded (although not displayed) in both Chrome and Firefox+Firebug. (I emphasize "Firefox+Firebug" because Firebug can change the behavior of Firefox on occasion, and so it may well be changing its behavior here, although I don't think it is; more on that below.)
It took some tweaking, but this seems to do the trick (more on testing below):
$.ajax({
url: url,
success: function(data) {
var div = $("<div>").html(data);
if (stripImages) {
// Find the images, remove them, and explicitly
// clear the `src` property from each of them
div.find("img").remove().each(function() {
this.src = "";
});
}
$(targetSelector).append(div.children());
},
error: function(jxhr, status, err) {
display("ajax error, status = " + status + ", err = " + err);
}
});
Live example The "Include big image" checkbox includes a large file from NASA's Astronomy Picture of the Day (APOD).
The key there was setting the src of the img elements to "". On Chrome, just removing the elements was enough to prevent Chrome starting the download of the images, but on Firefox+Firebug it not only started downloading them, but continued even when the download took considerable time. Clearing the src causes Firefox to abort the download (I can see this in the Firebug Net console).
So what about IE? Or Firefox without Firebug? I only did unscientific testing of those, but it's promising: If I run my live example of Martin's solution on either IE or Firefox without Firebug in a VM, I see the VM's network interface working hard, suggesting that it's downloading that big APOD picture. In contrast, if I run my solution above in that same environment (with caches cleared, etc., etc.), I don't see the VM network interface doing that work, suggesting that the download is either not being started or is being aborted early on.
.text *:not(img) will select every descendant from .text that is not an image, so in theory it should work.

Categories

Resources