views:

22

answers:

2

Hello,

I'm using jquery's .ajax() method on a button click.

I wanted to know if there a way in whcih I can use the data that I passed in the data-part of the AJAX call in my success() function.

This is my code,

$.ajax({
  url: //my URL here..
  type: 'POST',
  data:{
    projDets : projDetailsArray,
  },
  datatype:'html',
  error: function(){
    alert('Error loading Project Information');     
  },
  success: function(html){
    //I wanted to re-use 'projDets' that I'm passing in the 
    //'data' part of my code..                  
  }
});

Any help will be appreciated.

Thanks,
Pritish Devurkar.

A: 

Pritish - a quick and dirty way would be to store the json array in a jquery .data() object and then retrieve it as required.

1st, set the data: element to a named array:

// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);

// the data part of the $ajax call
data: projDetailsData,

to retrieve it again:

// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");

worth a try maybe!!

jim

[edit] - also, you could of course store the array in a module level vaiable -yuk!! :)

jim
When I try that in the success() function and try to print it out using alert(projDetailsArrayCopy), I get 'undefined'..
Pritish
oh, sorry, i thought you wanted to save and restore the array for use as the parameter in the $ajax method. i think because of closure, you won't be able to access the array from within the success function. sorry for the misunderstanding.
jim
maybe, you could add an additonal parameter onto the success function i.e success: function(html, projDetailsData){ and then use it that way - no??
jim
I tried the other solution, and it worked just the way I wanted!
Pritish
yes, now that i fully understand the question, i can see that :)
jim
A: 

You could wrap the $.ajax parameter in a closure, set up the "data" value as a local variable, and then reference it both for the "data" value and inside the "success" function:

$.ajax(function() {
  var data = {
    projDets: projDetailArray
    // ...
  };
  return {
    url: // your URL here..
    type: 'POST',
    data: data,
    datatype:'html',
    error: function(){
      alert('Error loading Project Information');     
    },
    success: function(html){
      // just reference "data" here!          
    }
  };
}());
Pointy
Thanks, this works just fine!
Pritish