Click here to Skip to main content
15,884,298 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
 var s= []; 
s = function1();// want values here in array 
function function1() {
         //var b = [1,2];
          
         $.ajax({
             type: "POST",
             contentType: "application/json; charset=utf-8",
             data: "{}",
             url: "/Bus/AjaxMethod",
             dataType: "json",
             success: function (data) {
                 debugger;
                 var b = [1, 2];
                 //var b = [];
                 //b = data.split(',');
                  
                 
                 //for (var i = 0; i < data.length; i++) {
                  
                 //    alert(data[i].SeatNo.split(',')); // its working
                  
                  
                 //}
      
                 return b;
             },
             
                 error: function (data) {
                     alert("Error");
                     console.log("Error ", data);
                 }

         });
          
         debugger;
         return b;
     };


What I have tried:

Hi, im new to jquery i dont know much how to return values. so pls help me.
Posted
Updated 14-Mar-22 0:06am

 
Share this answer
 
Comments
Raja 22S 12-Mar-22 2:42am    
ok sir, thank u
The first "a" in "AJAX" stands for asynchronous. That means the function returns before the request has completed.

You cannot use the values returned from the AJAX request until that request has completed.

You'll need to return a Promise[^], which will return the array value once the request has completed.
JavaScript
function function1() {
    return $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        url: "/Bus/AjaxMethod",
        dataType: "json",
    }).then(function(data){
        debugger;
        return data.split(',');
    }).fail(function(data){
        console.log("Error ", data);
        alert("Error");
    });
}
You will then need to delay the code which uses the return value until the method returns. You can either use a continuation:
JavaScript
function1().then(function(s) {
    debugger;
    console.log("Returned array", s);
});
or use async and await[^]:
JavaScript
async function doIt(){
    const s = await function1();
    debugger;
    console.log("Returned array", s);
}

doIt();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900