Skip to content Skip to sidebar Skip to footer

Passing Variables Through To AJAX

I have some variables that I would like to pass into an AJAX call: e.g. var moo = 'cow noise'; $.ajax({ type: 'POST', url: '', data: '', success: function(data){

Solution 1:

I guess your code might have been wrapped in $(function(){ ... }); as an jQuery thing. remove var will make it basically window.moo = "cow noise"; Which works, but pollutes the namespaces which is not what you want.

Do not try to pollute the global namespace, it will make your other code hard to debug. Use closure which should solve your issue:

var moo = "cow noise";

(function(moo){
    $.ajax({
        type: "POST",
        url: "",
        data: "",
        success: function(data){
            //return the variable here
            alert(moo);
        }
    });
})(moo);

Solution 2:

This should work, can't see anything wrong with your code. Live demo.


Solution 3:

as long as the variable is defined inside the same function as the $.ajax-call, you should be able to use moo inside the success-callback since it's inside the closure..

However, if the ajax-call is made elsewhere, you have to ensure that moo is inside the same scope. This could be done like this:

function thatDefinesTheVariable () {
  var moo = 'cow noise';
  makeAjaxCall(moo);
}

function makeAjaxCall (moo) {
  $.ajax({
    type: "POST",
    url: "",
    data: "",
    success: function(data){
            //return the variable here
            alert(moo);
    }
  });
}

Post a Comment for "Passing Variables Through To AJAX"