2

This could be my mis-understanding but i wanted someone to explain what i miss here.

If i have the below implementation for placing POST request using Jquery, the request is not made till i execute "click" event.

$(document).ready(function(){
  $("button").click(function(){
    $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});

However if i give the anonymous function a name by defining it seperately, Then the post request is tried to send even while loading the page.

<script>
$(document).ready(function(){
  $("button").click(callFunction());
});
var callFunction = function(){
    $.post("demo_test_post.asp",
    {
      name:"Donald Duck",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  };
</script>

Can someone explain me what i am lacking in my understanding. To me both should work the same way

Thanks for reading

1
  • 1
    You're using the result of calling the function callFunction instead of just referencing it. Commented Jan 16, 2014 at 17:50

2 Answers 2

3

That's probably because you should reference the function, not call it

$(document).ready(function(){
  $("button").click(callFunction); // no parenthesis
});

adding the parenthesis calls the function immediately and returns the result, you want to reference it only

Sign up to request clarification or add additional context in comments.

Comments

0

Try this format instead and don't forget to add id="btn" to your button

  $('#btn').click(function(event){

      var formData = {
           name:"Donald Duck",
          city:"Duckburg"
      }

    $.ajax({
                type        :   'POST'  ,
                url         :   'someurl',
                data        :   JSON.stringify(formData),
                contentTYpe :   'application/json',
                error       :   function(data,status,error){
                                    console.log(data+': '+status+': '+ error);
                                },
        success     :     function(data,status){
                  alert("Data: " + data + "\nStatus: " + status);
    });
        }).done(function(apiResponse){
                //Do something when done
        });
  });

Comments

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.