I've been working with JavaScript and i need to call a function from another .js file.
The code works most of the time, but sometimes it gives me the error "Object has no method odometer". I've even put the code inside a call to getScript() to make sure it's loaded before it tries to call the odometer() function, but I'm still getting random errors.
Heres the code:
var updateDisplay = function(){
console.log("refreshing Odometers");
$.getScript("/odometer.js", function(){
$.getJSON(
'/getData',
{
product: '',
unit: unitSelection(),
period: salesPeriod(),
reportBegin: $("#datepickerfrom").val(),
reportEnd: $("#datepickerto").val()
},
function(data){
$(".odometer").odometer({
odometerData:data
});
});
});
};
I am getting an error on this line:
$(".odometer").odometer({
odometerData:data
});
It says "object has no method odometer".
I am using the Play framework for development and I've already imported jQuery and my other JavaScript files in the HTML page.
Here's my JS import order:
jquery
odometer.js (even i use getScript, i've put it there just to make sure)
main.js (which the given code resides in..)
What am I doing wrong?
Thanks for helping....
I think
$(".odometer").odometer({...})
is called before odometer extends to jQuery, flow may be like this
$(".odometer").odometer({...}); // first called
$.fn.odometer = function(){...}; // later it was extended to jQuery
seems like its a problem with ajax caching settings.
i've found the answer from this question:
jquery ajax bug
after adding
$.ajaxSetup({ cache: true });
the getScript works fine. thanks for spnding your time guys :)
Related
I have had to use some js code in order to make a plugin work correctly with my word press website that uses ajax to load pages.
The code allows the search plugin to be used without reloading pages when clicking a result (the search uses ajax too), as before using this code ajax page loads would not happen.
The code:
let newContent = document.querySelector(".asl_r");
let pjax = new Pjax({
cacheBust: false,
elements: "a", // default is "a[href], form[action]"
selectors: ["title", "#header nav", "#aside", "#footer", "#content"]
});
pjax.refresh(newContent);
});
let container = document.documentElement || document.body,
config = { attributes: false, childList: true, subtree: true, characterData: false };
dom_observer.observe(container, config);
This does work and search results are loaded using ajax when clicking a result.
The only issue I seem to have now is when checking the chrome dev console I can see the following error many times:
(index):228 Uncaught ReferenceError: Pjax is not defined at MutationObserver.<anonymous> ((index):228:14)
My js knowledge is minimal, but I have tried to define the Pjax function to remove the error without success.
I am just looking for any help I can get to fix this code and remove the error it is creating.
Thank you to any that can offer some advice.
There's no object called Pjax provided in the core JavaScript API. So if you're trying to use a function defined in another script make sure that the script is loaded first before you try to invoke any function from it.
I have recently updated my Wordpress blog which appears to have broken all my jQuery on the page.
I include a core.js file which contains a .ready method that modifies page behaviour, however since the update its stopped working. I believe its because Wordpress injects its own version of the jQuery library which is somehow conflicting with my script.
Webpage
Core.js file
Snippet of file
console.log('loaded core.js');
jQuery(document).ready(function($) {
console.log('inside ready function');
// other stuff goes on here
}
The 'loaded core.js' debug line will fire, however the second debug line will not.
I'm not sure how to resolve, will greatly appreciate advise.
You need to deregister the default jquery library.
For more information, check Function Reference/wp deregister script.
wp_deregister_script( 'jquery' );
If you are going to deregister jquery, here's a way of removing it and adding a different version:
function my_jquery_lib() {
wp_deregister_script('jquery');
$lib_url = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"; // the library URL.
wp_register_script('new-jquery', $lib_url, false, null);
wp_enqueue_script('new-jquery');
}
add_action("wp_enqueue_scripts", "my_jquery_lib");
Your website has an error in the console.
TypeError: f.browser is undefined
This maybe be causing the issue.
I have tried multiple combination of usage of code to make the Prototype and jQuery to work, but no luck yet.
Here is what I have currently.
index.html:
<script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.2.0/prototype.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="MAIN_JS_FILE.js"></script>`
main_js_file.js:
jQuery(document).ready(function() {
var jsq = [];
jsq.push(AJAX_CALL_FOR_FETCHING_JS_FILE_1);
jsq.push(AJAX_CALL_FOR_FETCHING_JS_FILE_2);
jsq.push(AJAX_CALL_FOR_FETCHING_JS_FILE_3);
var deferredjs = jQuery.when.apply(jQuery, jsq);
deferredjs.done(function() {
//Various variable initialization
//Various function definition.
}
});
Now when page is loaded (page loads properly), chrome console shows an error message:
Uncaught TypeError: undefined is not a function.
When clicked on the error file link, it points to element.dispatchEvent(event); in the prototype.js file, line no 7066.
Any help is appreciated.
Thanks.
Edit: I have changed the MAIN_JS_FILE.js file to use only jQuery instead of $
So now there is not a single javascript code that uses $ and still the undefined error is displayed.
If I now use jQuery.noConflict(); before .ready() function, then the $.when.apply code does not even execute.
As #steven iseki mentioned in comment you, can use jQuery.noConflict. You can read on their website that:
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $.
And it's indeed a case with Prototype also using $ sign.
Also, remember to use jQuery instead of $ sign in your jQuery code, e.g.:
jQuery(selector).on('click', function(){...});
I don't think there's jQuery Conflict error here. Try changing your code from main.js. Try alternate method to get your task done here. I analyzed your code but prototype.js has a way of hiding real thing.
I am using JQuery's getScript function to load scripts depending on the device type, to hope fully save on unnecessary requests and load time for mobile devices. I have this code currently:
<script type="text/javascript">
$(document).ready(function(){
$.getScript('http://dev.imadeamerica.com/wp-content/themes/imadeamerica/js/mfc.js', function(){
alert('It WORKED!');
});
});
</script>
But it's not working, because I keep getting the error $(window)._scrollable is not a function. The only weird thing is that if you visit http://dev.imadeamerica.com/wp-content/themes/imadeamerica/js/mfc.js there is no call to that function. When I put a different script in the getScript function it works fine. But for some reason it thinks I am calling a function called $(window)._scrollable even though it's not present in that file.
I haven't found anything like this before and any help would be much appreciated.
The first line of setUp, line 27, has this:
$(window)._scrollable();
So, yes, you are calling that function.
open your script and # line no 27 you have a call $(window)._scrollable(); please define the function cz that functions is not defined
Have the same issue when update bootstrap v4.0 to v4.3.1
Code example:
`https://codepen.io/pasha-oleynik/pen/yWvjaQ?editors=1011`
To fix need to use jquery without slim postfix. (use jquery-3.3.1.min.js instead of jquery-3.3.1.slim.min.js)
I was wondering how I can get a function from an AJAX request, like this:
Let's say I have a file called myfunction.js, that looks like this:
function(bar){
alert(bar);
}
Can I retrieve it via Ajax as a function, like this?
var foo = $.ajax({url:'myfunction.js',async:false}).responseText;
And run it like this?
foo(bar);
The reason I ask is because I know responseText is a string,
so I'm not really sure if JavaScript will understand that it is a function.
Is there a way to convert a string into a function?
In your JS file, give the function a name.
function foo(bar){
alert(bar);
}
Then use $.getScript to load it.
$.getScript('myfunction.js', function(){
foo('test');
});
Absolutely:
foo = eval('(' + foo + ')');
foo(bar);
You could use new Function but in my testing it doesn't work on some versions of IE.
I ended up using new Function instead of eval, eval executes the code as soon as it's parsed, which is not what I was after.
This is what I ended up doing, and it works very nicely in firefox, chrome, and IE 7+ (no errors at all)
function createMyFunction(code){return new Function('params',code)};
var thecode = $.ajax({
url: 'myCode.js',
async: false,
dataType: 'html'
}).responseText
myFunction = createMyFunction(thecode);
I know the createMyFunction is pretty lazy in terms of not being able to define different arguments, but using a single params map works for my templating scenario quite well.
Note the dataType:'html' in the ajax request, if you don't specify a plain text mime type, jQuery will actually recognize that you are getting JS code and try to parse it, which generally ends up throwing a parse error or sometimes "Uncaught TypeError: params is not defined".
With this, I am able to have template files that specify template-specific events, and keep them organized in the same way as the markup and css files for that template.
Thanks for the help everyone, the reason I chose the answer that I did is because the link at the end pointed me in the right direction.
Cheers,
D
One thing to beware.
Chrome and IE don't allow you to eval an anonymous function directly (FF is fine). That is
// Throws Syntax Error in Chrome, Object expected in IE 8
var fun = eval('function(){return 5}'); fun();
A hackaround is to put it in an array, doesn't seem very reliable for the future:
var fun = eval('[function (){return 5}][0]'); fun();
The only safe way would be to make sure your functions are named, since the following works fine in all browsers:
eval('function a(){return 5}]'); a(0);
See Are eval() and new Function() the same thing? for further discussion