1

I am just using this code and I wanted to alert its response

$http.post('test.php',{id:index});

so I used this code

alert(($http.post('test.php',{id:index}).data));

I dont understand how angularjs method $http.post is differ from below code. and how data comes in above code ?

$http({
    url: "test.php",
    method: "POST",
    data: {id:index}
}).success(function(data) {
   alert(data);
}).error(function(error) {
});

test.php is

<?php
    echo "TestName";
?>
1
  • For your information: The success and error methods are deprecated: "The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error." So instead of using $http().success().error(); use $http().then(function resolved () {}, function rejected () {}); See: docs.angularjs.org/api/ng/service/$http#deprecation-notice Commented Feb 19, 2016 at 11:33

1 Answer 1

3

Your code

  1. Assumes that the post function returns an object with a data property on it.

  2. Assumes that the post function blocks while doing the POST (e.g., is synchronous).

Neither of those assumptions is correct. post starts the POST but returns immediately, before the POST completes. The value it returns is a promise, which is a formalized means of handling callbacks for asynchronous operations. Promises have then, error, and similar functions on them.

In your second example, the code runs, and then later when the POST is complete, if it's successful the success callback is called, passing in the data.

This is covered in here and (for promises) here.

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

1 Comment

Thanks, Now I noticed

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.