-2
var left=$('.left p');

   left.click(function(){
       var index= $(this).index('.left p');        

      var returned_data= ajaxcall(click_name);
      console.log(returned_data)                

   });


   function ajaxcall(name)
   {
       $.ajax({
                type: "POST",                    
                url: "retriveData.php",                     
                data:{click: name},
                       cache: false,                          
                success: function(data) 
                {
                    var p=data;                        
                    return p;                    
                }

        })
   }

I need the value in variable p to be passed to click function variable returned_data. But the returned_data is showing undefined. Can you please tell me what is wrong with the code here

Vinny
  • 865
  • 1
  • 11
  • 25

1 Answers1

1

You can't return data from ajax like that. Ajax is asynchronous. So the function will not wait for the success event to happen.

You can call a function from the success event with that data. That will be the best possible approach.

$.ajax({
    type: "POST",
    url: "retriveData.php",
    data: {
        click: name
    },
    cache: false,
    success: function(data) {
        var p = data;
        manipulateData(p);
    }

});

function manipulateData(data) {
    console.log(data);
}
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53