Domanda

I use a jQuery Ajax function to install some demo data on a WordPress theme. This script below has worked on previous themes I have worked on, however now for some reason I am receiving the error

Uncaught TypeError: Cannot call method 'hasOwnProperty' of null

Here is the script I am using

/* Install Dummy Data */
function install_dummy() {
    $('#install_dummy').click(function(){
    $.ajax({
            type: "post",
            url: $AjaxUrl,
            dataType: 'json',
            data: {action: "install_dummy", _ajax_nonce: $ajaxNonce},
            beforeSend: function() {
                $(".install_dummy_result").html('');
                $(".install_dummy_loading").css({display:""});
                $(".install_dummy_result").html("Importing dummy content...<br /> Please wait, this process can take up to a few minutes.");                    
            }, 
            success: function(response){ 
                var dummy_result = $(".install_dummy_result");
                if(typeof response != 'undefined')
                {
                    if(response.hasOwnProperty('status'))
                    {
                        switch(response.status)
                        {
                            case 'success':
                                    dummy_result.html('Dummy Data import was successfully completed');
                                break;
                            case 'error':
                                    dummy_result.html('<span style="color:#f00">'+response.data+'</span>');
                                break;
                            default:
                                break;
                        }

                    }
                }
                $(".install_dummy_loading").css({display:"none"});
            }
        }); 

    return false;
    });
}
install_dummy();

Any help would be greatly appreciated.

È stato utile?

Soluzione

if(typeof response != 'undefined')

That means: "Is there a variable called 'response'?". Since you are receiving that as a function parameter, there is/exists a variable called response.

Existence of a variable does not mean that it can not be null. Here, response is defined/exists, but it is null. And when you say:

if(response.hasOwnProperty('status'))

you try to invoke hasOwnProperty on a null value, and hence you get that exception. You must do:

if (response !== null && response.hasOwnProperty(..)) { ... }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top