简体   繁体   中英

jQuery Plugin Function Returning Undefined For The Value

I created a jQuery plugin to do various things with cookies. The trouble I am having is the function I created to read the cookie and return the value. No matter what I do, when I call the function as so from the main page

test = $.cookie({
        action:'get', 
        cookie_name:LOGIN_COOKIE_NAME
    });

the return is ALWAYS undefined. Console output is as follows:

Value found is => 10
Returned => undefined

I'm at my wit's end trying to figure out what's going on here. I've tried everything I know to do and spent literally hours Googling this with no solution. Below is the code in my jQuery plugin:

// Get the value of the sought after cookie

  function get_cookie(){ var value = ''; // Get the name to search for var name = settings.cookie_name; // Divide the cookie string into an array var ca = document.cookie.split(';'); // Loop through each element in the main array we just created match_found = false; for(var i=0; i<ca.length; i++){ // Clear the whitespace from the ends to prevent mismatches and split each > element into the cookie name and value var temp = ca[i].trim().split('='); // Now check to see if this is the cookie we are looking for if(temp[0] == name && !match_found){ match_found = true; // If it is, then return the cookie's value cookie_value = temp[1]+''; if(settings.action != 'check'){ value = cookie_value; }else{ value = true; } } } if(!match_found && settings.action == 'check'){ return false; }else if(!match_found && settings.action != 'check'){ return 'dooby'; }else{ console.log('Value found is => '+value); return value; } } 

Does anyone have any insight into what's causing this and how it can be corrected?

Here is the entire code of my jQuery plugin

(function($){
$.cookie = function(options) {

    // Default Settings
    var settings = $.extend({
        action : 'check', // create or delete
        cookie_name : 'cookie',
        cookie_value : 'default',
        expiration : 'Sun, 31 Dec 2017 12:00:00 GMT',
        path : '/'
    }, options);

    switch(settings.action){
        case "create":
            create_cookie();
            break;
        case "delete":
            delete_cookie();
            break;
        case "check":
            return check_for_cookie();
            break;
        case "get":
            get_cookie();
            break;
        default:
            get_cookie();
            break;
    }






    // Create the cookie
    function create_cookie(){
        try{
            document.cookie = settings.cookie_name+"="+settings.cookie_value+"; expires="+settings.expiration+"; path="+settings.path;
            console.log("Cookie Created");
        }catch(e){
            console.log(e);
        }
    }


    // Delete said cookie
    function delete_cookie(){
        document.cookie = settings.cookie_name+"="+settings.cookie_value+"; expires=Sun, 29 Dec 2013 12:00:00 GMT; path="+settings.path;
    }


    // Get the value of the sought after cookie
    function get_cookie(){
        var value = '';
        // Get the name to search for
        var name = settings.cookie_name;

        // Divide the cookie string into an array
        var ca = document.cookie.split(';');

        // Loop through each element in the main array we just created
        match_found = false;
        for(var i=0; i<ca.length; i++){
            // Clear the whitespace from the ends to prevent mismatches and split each element into the cookie name and value
            var temp = ca[i].trim().split('=');

            // Now check to see if this is the cookie we are looking for
            if(temp[0] == name && !match_found){
                match_found = true;
                // If it is, then return the cookie's value
                cookie_value = temp[1]+'';
                if(settings.action != 'check'){
                    value = cookie_value;
                }else{
                    value = true;
                }
            }
        }
        if(!match_found && settings.action == 'check'){
            return false;
        }else if(!match_found && settings.action != 'check'){
            return 'dooby';
        }else{
            console.log('Value found is => '+value);
            return value;
        }
    }


    // Check to see if said cookie exists
    function check_for_cookie(){
        var is_set = get_cookie(settings.cookie_name);
        if(is_set){
            return true;
        }else{
            return false;
        }
    }
};
}(jQuery));

SOLUTION:

Thanks to OJay below for the keen eye and the solution to this. Scroll down and give him some upvotes.

The call to get_cookie() in the main switch statement that handles what action to take was not returning anything. So following OJay 's solution it now works by looking like this:

case "get":
    return get_cookie();
    break;

inside your cookie 'plugin', you do a case statement on the action, and call the corresponding private method. Now the get method returns a value, but you are not doing anything with it, the return value of get is not being returned by the parent function

ie

 switch(settings.action){
        ///... snipped for brevity
        case "get":
            //the get_cookie returns something, but you are not returning it past here
            get_cookie(); 
            break;
        ///... snipped for brevity
    }

This will mean that the parent function ($.cookie) doesn't have a return statement in it for get, so returns undefined (default javascript behavior)

Return the value of the get action, like you did with the "check" one.

It doesn't have a return value for "create" or "delete" either, but they don't necessarily need to. Although I would probably return a boolean (true or false) to indicate that the create or delete was successful

Check if the symbol $ is defined and check if the symbol jQuery is defined. if $ is not defined and jQuery is, try jQuery.cookie instead of $.cookie .

If both are undefined, I would check if the jQuery scripts are included in your HTML code. One of the ways to include jQuery is described here . Look for something like <script src="jquery.. in your page's HTML code to see if it is already included. If it is not, you should include it. The scripts should be included before you try to use $ or jQuery symbols

Try defining your plugin using

$.fn.cookie = function(options) {
    //... your plugin
}

according to the jquery documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM