2

i am not able to print the parsed json file on the console outside the ajax call? what am I doing wrong?

function displayData(term) {                                                                                                                                  
   var frmStr =$('#input1').serialize(); 
   var result;                                                                                                            

   $.ajax({                                                                                                                                                  
        url:'./cgi_temp4_1.cgi',                                                                                                                          
        dataType:'json',                                                                                                                                  
        data: frmStr,                                                                                                                                     
        success: function(data, textStatus, jqXHR){                                                                                                       
            //alert(data)                                                                                                                                 
            result = $.parseJSON(JSON.stringify(data))                                                                                                    
        },                                                                                                                                                
        error: function(jqXHR, textStatus, errorThrown){                                                                                                  
            alert("Failed to perform search! textStatus: (" + textStatus +                                                                           
                  ") and errorThrown: (" + errorThrown + ")");                                                                                            
        }                                                                                                                                                 
    });                                                                                                                                                   

    //i get "undefined" message on the console                                                                                                                                                  
    console.log(result);

}

ApisMel
  • 67
  • 1
  • 10

1 Answers1

2

You are sending an asynchronous request but trying to read the result before the result is ready.

Move the console.log(result) to Line 12, as the last line in the success callback.

Schien
  • 3,855
  • 1
  • 16
  • 29