PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] How to post data with Angular JS?

 February 21, 2022     angularjs, cakephp-3.0     No comments   

Issue

I'm trying to POST data to my application but it's simply not working. in PHP i have made some try with CURL and i don't have any issue.

In Angular, trough the console i'm getting :

Object { data: null, status: 0, headers: headersGetter/<(), config: Object, statusText: "" }

With Curl, i can post data with the following code :

# the POST data 
$email = 'test@test.fr';
$password = 'blabla';

$data = array("email" => "$email", "password" => "$password", "active" => TRUE);
$data_string = json_encode($data);

$ch = curl_init('http://localhost:8888/app/api/users/register');
# An HTTP POST request 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json')
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;

With Angular, this code is producing the console message on the top :

.controller('TestCtrl', ['$scope', '$http', function($scope, $http) {

  $scope.data = {};

  $scope.newUser = function() {

      $http({
        method: 'POST',
        url: 'http://localhost:8888/app/api/users/register',
        data: {
          email:'test@test.fr',
          password:'blabla'
        },
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      }).then(function successCallback(response) {
        console.log("GREAT");
      }, function errorCallback(response) {
        console.log(response)
      });

    }

}])

More Information :

With CURL/PHP, the user is created and a token too.

string(199) "{ "success": true, "data": { "id": 18, "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE4LCJleHAiOjE0NTI4NTIxODd9.vYU6YcuGS2rUUD2cBG233hSARWHp7dc1uBF7TdMrGeM" } }" 

Header Sent trough Angular :

Accept :"application/json, text/plain, */*"
Content-Type :"application/json; charset=utf-8"
X-Requested-With :"XMLHttpRequest"

Also, i've follown this tutorial to create the Cakephp 3 api : http://www.bravo-kernel.com/2015/04/how-to-build-a-cakephp-3-rest-api-in-minutes/

EDIT , on Chrome :

OPTIONS http://localhost:8888/perles/app/users/register (anonymous function) @ ionic.bundle.js:23826sendReq @ ionic.bundle.js:23645serverRequest @ ionic.bundle.js:23357processQueue @ ionic.bundle.js:27879(anonymous function) @ ionic.bundle.js:27895Scope.$eval @ ionic.bundle.js:29158Scope.$digest @ ionic.bundle.js:28969Scope.$apply @ ionic.bundle.js:29263(anonymous function) @ ionic.bundle.js:62385eventHandler @ ionic.bundle.js:16583triggerMouseEvent @ ionic.bundle.js:2948tapClick @ ionic.bundle.js:2937tapMouseUp @ ionic.bundle.js:3013
(index):1 XMLHttpRequest cannot load http://localhost:8888/app/api/users/register. Response for preflight has invalid HTTP status code 500

Solution

Try following:

var config = { headers : {'Content-Type': 'application/json; charset=utf-8'}};
//Stringify the JSON data
var data = JSON.stringify({email:'test@test.fr', password:'blabla', active: true});
$http.post(
      'http://localhost:8888/app/api/users/register', 
      data, 
      headers
  ).then( function(response){
         // success callback
  }).catch( function(error) {

  });

I prefer to separate the success and failure callbacks this way, it makes my code bit more cleaner.

Now the CORS issue, it seems your api is not allowing it, please ensure you are sending right access control headers:

Access-Control-Allow-Origin: *

Use suggestion from one of these threads, and I hope your problem should be resolved:

  • Restangular api calls to external getting 'No Access Allowed'
  • How to enable CORS in AngularJs

Remember your server must allow these api calls, then only Angular service will be able to get data from them.



Answered By - Ravish
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing