I’m having problems trying to call a Javascript function from an enqueued javascript file used whilst editing WordPress pages. I have created a simple meta box with some AJAX hyperlinks that I want to be able to call functions from the Javascript file (pretty simply stuff but I keep getting error “blah(1) is not defined”.
HTML CONTAINED IN METABOX:
<a href="#" class="delete_pimg" id="pimg_1" onclick="blah(1);return false;">Delete Item</a>
JS:
function blah(theid){
if ( confirm("Are you sure you wish to remove this image (Note: Images are not removed from the Media Library)?") ) {
var data = {
action: 'myajax-delete',
imgid: theid
};
jQuery.post(ajaxurl, data, function(response) {
//Parse the JSON Object
var object = jQuery.parseJSON(response);
if ( response.status == 'true' )
{
jQuery('#file_' + theid + '_row').remove(); //remove TR
alert('Image removed from this portfolio');
}else{
alert('Sorry, that image could not removed right now, please reload the page and try again.');
}
});
Note: The PHP server side code works fine and responds absolutely as expected to my manual Posts. The javascript file is definitely present and being downloaded by the browser as expected.
If I use the following line of code below, the AJAX works (so I know the JS is OK) but I need to be able to call the function by name rather use a selector. I’m very keen to work out why I can’t call a simple function!!!!
jQuery('.delete_pimg').click(function() { ^Above code^ }
Just to re-cap the error I get when the link is clicked: ‘blah(1) is not defined’
I hope I’ve explained this clearly – if not, please give me a shout 🙂
Ok Basically – I could not get this to work. My javascript is absolutely fine, so In order to call my own functions, I declared them within the page itself rather than calling in a JS file. This seems to work and my code executed with no errors straight away.
I.e
A work around but at least solved my problem anyway.
Wipes sweat from forehead
I was having the same issue where
blah() is not defined
, and found out I needed to have the enqueued js file just define the function, instead of wrapped with ajQuery(document).ready(function($) { function blah(param){[...]} })
.Here’s what my code looks like now, which got everything working for me:
Inside of functions.php
(short snippet within my file)
Inside of blah-file.js
(this is the full contents of the file)
Inside of header.php and footer.php
(short snippet where I output some link, such as social link)