Search code examples
phpjqueryajaxwordpresswordpress-theming

Wordpress Admin - Function not defined?


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 :)


Solution

  • 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

    <script type="text/javascript">function blah(id){alert("This Works Nicely!");}</script>
    

    A work around but at least solved my problem anyway.

    Wipes sweat from forehead