0

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;

3 Answers 3

1

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

i.e.

 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

Sign up to request clarification or add additional context in comments.

2 Comments

YOU, my friend, are a friggin genius with a sharp eye!! If you were a single hot female and standing close to me I'd kiss you right now. You gave solution and for that I am EXTREMELY grateful! Thank you so much!
Thanks for the explanation too. It's always better to know WHY your code isn't working instead of just simply getting a solution. That way you'll be more educated and hopefully not make the same mistake in the future. So thank you not only for the solution, but also for the education aspect as well.
0

Try defining your plugin using

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

according to the jquery documentation

Comments

0

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

3 Comments

Thanks for the reply. When I replace $ with JQuery the console reports JQuery is not defined. I tried with a lowercase jQuery as well, but the result was the same as using $. It still returns the value as undefined.
Thank you for you comment, "jQuery" is spelled with lower case "j". I updated my answer
It seems you have both $ and jQuery defined, look for other answers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.