4

How do I post data using React and Angular?

Is there has function like $.ajax for React and Angular?

I mean I need just like this post function for React and Angular

$.ajax{
url:"test.php",
type:"POST",
cache:false,
success...
etc.
Omar Ali
  • 8,467
  • 4
  • 33
  • 58
  • `$.ajax` is jQuery... for pure JS, use `XMLHttpRequest`. See [here](http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery) – Andrew Li Nov 13 '16 at 06:07
  • Depending on what browsers you want to support, you might be able to use fetch(). Check it out at https://developer.mozilla.org/en/docs/Web/API/Fetch_API – Harry Pehkonen Nov 13 '16 at 06:17

4 Answers4

2

A tool that can perform an asynchronous HTTP (Ajax) requests
that will work in both React and Angular? I tend to use:

axios

"A Promise based HTTP client for the browser and node.js" [ github page], [npm page]


Usage comparisons:

"...takes the good parts from Angular’s $http, and throws out everything else"
~ Six essential javascript libraries - JK Nelson

axios XMLHttpRequest version

let http = new XMLHttpRequest();
http.open("POST", 'http://readyourlevel.jamesknelson.com/api/grade', true);
http.setRequestHeader('Content-type', 'text/html; charset=UTF-8');
http.onreadystatechange = function() {
    if (http.readyState == 4) {
        if (http.status == 200)
            onGradeResult(JSON.parse(http.responseText));
        else
            onGradeError(http);
    }
};
http.onerror = onGradeError;
http.send(text);

axios version

axios({
    url: 'http://readyourlevel.jamesknelson.com/api/grade',
    method: 'post',
    headers: {'Content-type': 'text/html; charset=UTF-8'},
    data: text
}).then(onGradeResult, onGradeError)


Comparison with Angular shortcut methods:

axios Angular (only) shortcut version

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
  .success(function(data, status, headers, config) {
      $scope.data = data;
  }).error(function(data, status, headers, config) {
      $scope.status = status;
  });

axios version (works with Angular and React)

axios.post('http://example.appspot.com/rest/app', { foo: 'bar' })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Pineda
  • 7,435
  • 3
  • 30
  • 45
1

For React:

You can use fetch API from Javascript to call the service.

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  } else {`enter code here`
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

function parseJSON(response) {
  return response.json()
}

fetch('/users')
  .then(checkStatus)
  .then(parseJSON)
  .then(function(data) {
    console.log('request succeeded with JSON response', data)
  }).catch(function(error) {
    console.log('request failed', error)
  })
user3278612
  • 201
  • 2
  • 11
1

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).success(function(data, status, headers, config) {
    $scope.data = data;
}).error(function(data, status, headers, config) {
    $scope.status = status;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.success(function(data, status, headers, config) {
    $scope.data = data;
}).error(function(data, status, headers, config) {
    $scope.status = status;
});

There are number of things to notice:

AngularJS version is more concise (especially using .post() method)

AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)

Callback functions are named success and error respectively (also please note parameters of each callback)

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

from: from jquery $.ajax to angular $http

For REACT: http://andrewhfarmer.com/react-ajax-best-practices/

Community
  • 1
  • 1
Hemakumar
  • 639
  • 9
  • 24
0

Have a look at reqwest, very similar to the jQuery api.

Mark Williams
  • 2,268
  • 1
  • 11
  • 14