skip to Main Content

return without executing the ajax function

function weekData(){
    var weekCount={};

 $.ajax({
         url:"http://localhost:8080/getWeeeks",
         headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
     },
     type:"GET",
         dataType:"json",
         data:{},

         success:function(data){

             for (var i = 0; i < data.length; i++) {
             weekCount[i]=data[i];

             }   
             debugger
             return weekCount;       

         },

     });

     return weekCount ;            
    }
var circle = weekData();

3

Answers


  1. You need to add error method along with check request on server-side to make sure that your ajax call is working fine.

    error: function (request, status, error) {
        alert(request.responseText);
    }
    


    Updated

    There are numerous way to get the result from ajax response

    1. Use async: false to make ajax response in sync like below
       $.ajax({
             url:"http://localhost:8080/getWeeeks",
             headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
             },
             async: false // This setting make ajax response in sync.
             ...
    // Note that: It's not a good approach because of its deprecation and stuck the page untill the request comes back.
    
    1. Return promise then manipuplate the done function
    function weekData() {
        return $.ajax({
            url: "http://localhost:8080/getWeeeks",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            type: "GET",
            dataType: "json",
            data: {}
        });
    }
    
    var weekCount = [];
    weekData().done(function(data) {
        for (var i = 0; i < data.length; i++) {
            weekCount[i] = data[i];
        }
    });
    
    1. Use callback function
    Login or Signup to reply.
  2. Remove the data object from ajax call. There is no need to send any data object when the method type is ‘GET’.

    data:{}
    
    
    Login or Signup to reply.
  3. SOLUTION:

    Ajax calls are asynchronous by nature and defaults to true.

    Two approaches may work for this:

    First use Shorthand Ajax function and store the result into weekCount

     var weekCount = $.get( "ttp://localhost:8080/getWeeeks", function( data ) {
      return data.your-object-name;
    });
    

    Second Option

    use setTimeOut() function to ensure the request is completed.

    then callback to store the response in weekCount;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search