0

I've got the following function:

function postToDrupal(contacts, source, owner) {
  (function ($) {
    $.post("/cloudsponge-post",function(contacts) {
      alert(contacts);
    });
  }(jQuery));
}

The problem I'm having is, contacts seems to be defined outside the jQuery closure, but not inside it. I'm a javascript newbie so this is confusing me. How can I get this to post contacts?

1
  • contacts is your data to sent to cloudsponge-post url? Am I right? If not can you elaborate little more. Commented Jun 28, 2013 at 8:09

4 Answers 4

7

You're masking the variable with a new variable with the same name when you re-use the name as the AJAX call's callback function parameter.

function postToDrupal(contacts, source, owner) {
  (function ($) {
    $.post("/cloudsponge-post",function(data) {  // <-- !!
      console.log(contacts);  // the first parameter of postToDrupal()
      console.log(data);      // the response from the AJAX call
    });
  }(jQuery));
}
Sign up to request clarification or add additional context in comments.

1 Comment

OK, so to clarify, if I wanted to post 'contacts', I would need: $.post("/cloudsponge-post",contacts,function(data) {
3

You don't need to have contacts as a parameter again in your $.post() function.

If you do, you are making another variable local to $.post.

In javascript, variables are local to functions, not blocks.

I love this article: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

It's a very good read on understanding javascript scoping. Also there's something called "hoisting" you should know about.

Comments

0

Try this one:

function postToDrupal(contacts, source, owner) {
  $.post("/cloudsponge-post",function(responseData) {
    alert(responseData);
    alert(contacts);
  });
}

Comments

-1

you can use this as syncronus ajax call. Rewriting the code and use it.

function postToDrupal(contacts, source, owner) {
var result = undefined;
    $.ajax( {
            type : 'GET',
            url : '/cloudsponge-post',
            async: false,
            success : function(contacts) {          
                result = contacts;
            }
        });
        return result;
}

1 Comment

a) Using async:false in this case is totally unnecessary and bad advice, and b) this doesn't fix the OP's problem (which is not being able to access the original contacts variable inside the success callback)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.