0

I have the following code:

    $("#search").keyup(function(){
      if($("#search").val().length > 2){
        var returnedValue = (notes.search($("#search").val()));
        console.log(returnedValue);
      }
    });


    notes = (function(){

    return{

        search : function(data){
                var result = "";
                $.ajax({
                    type:"GET",
                    url:"/search",
                    dataType:"text",
                    timeout:2000,
                    data:{noteTitle:data},
                    success:function(data){
                        if(data == 'false'){
                            console.log('no data');
                        }else{
                            result = JSON.parse(data);
                            return(result);
                        }
                    },
                    error:function(xhr,type){
                        console.log("ajax error");
                    }
                });
        },
})();

Returned value is always undefined. It's obviously a scoping issue, but I can't seem to figure out how to return the data from the ajax request to anything outside the module.

Diego
  • 916
  • 1
  • 13
  • 36
  • 1
    That IEFE is totally unnecessary. – Bergi Oct 01 '13 at 22:00
  • IIFE's are useful to enclose variables within a limited scope, as var defined variables in javascript are scoped to the function in which they are defined, not the block. In this case, you are initializing a global (notes) with the return value of a function. No need to wrap it in an IIFE. Just call it. – dwerner Oct 01 '13 at 22:02
  • Looking at JQuery promise pattern as alternative, but how would you structure with the module pattern? – user2701624 Oct 02 '13 at 03:28
  • Hey Diego. That link was the answer. Thanks for the heads up. – user2701624 Oct 03 '13 at 23:58

1 Answers1

0

The data variable is getting overriden.

Corrected code:

$("#search").keyup(function(){
  if($("#search").val().length > 2){
    var returnedValue = (notes.search($("#search").val()));
    console.log(returnedValue);
  }
});


notes = (function(){

return{

    search : function(str){
            var result = "";
            $.ajax({
                type:"GET",
                url:"/search",
                dataType:"text",
                timeout:2000,
                data:{noteTitle:str},
                success:function(msg){
                    if(msg== 'false'){
                        console.log('no data');
                    }else{
                        result = JSON.parse(msg);
                        return(result);
                    }
                },
                error:function(xhr,type){
                    console.log("ajax error");
                }
            });
    },

})();
Pupil
  • 23,834
  • 6
  • 44
  • 66