1

I'm trying to get a json coming from an application and saved in the database, I'm trying to do this with php and mysql.

I need to get a json and then save it on the bank. I can not get json and pass it on some variable. Save the variable in the database I could do.

I created a simple table in the bank and this I created is simple, it's just to learn.

Receives_json.php

   <?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");

$assunto_contato = $_POST["assunto_contato"];
$comentario_contato = $_POST["comentario_contato"];
$nome_contato = $_POST["nome_contato"];
$data = date("Y-m-d H:i:s");

$conn = new mysqli("", "", "", "");

$sql_insert = "INSERT INTO contato VALUES ('$assunto_contato', '$comentario_contato', '$nome_contato', '$data')";

$stm = $conn -> prepare($sql_insert);

if ($stm->execute()){
    $retorno = array("retorno" => 'YES');
 } else {
    $retorno = array("retorno" => 'NO');
 }

 echo json_encode($retorno);

 $stm->close();
 $conn->close();
?>

I'm getting json from angularjs, that angularjs function sending json:

    .controller('contatoController', function($scope, $stateParams, $ionicPopup, $ionicHistory, $http, $ionicPlatform, $state) {
     $scope.contato = {};
     $scope.Enviar = function() {
         var linkContato = 'http://apps.greenonetec.com.br/insert_contato.php'
         $http.post(linkContato, {
             "assunto_contato": "$scope.contato.assunto",
             "comentario_contato": "$scope.contato.comentario"
         });
         console.log()
         $ionicHistory.nextViewOptions({
             disableBack: true
         })
         $ionicPopup.alert({
             title: 'Sua mensagem foi enviada'
         }).then(function() {
             $state.go('app.home');
         })
         console.log($scope.contato.assunto);
         console.log($scope.contato.comentario);
     }
 })

But I can not get the json that is coming from angularjs in php, could anyone help me?

Lucas Santos
  • 119
  • 2
  • 7

5 Answers5

0

You have to call post method correctly with desired object. So change your code the below way and access the response coming from your API call the following way

var data = {
     "assunto_contato": $scope.contato.assunto,
     "comentario_contato": $scope.contato.comentario
 }
 data = JSON.stringify(data);
 var linkContato = 'http://apps.greenonetec.com.br/insert_contato.php';
 $http.post(linkContato, data).then(function(response) {
     console.log(response.data);
 }).catch(function(error) {

 });

For more info: https://docs.angularjs.org/api/ng/service/$http

Vivz
  • 6,417
  • 2
  • 16
  • 33
  • This usage is not in the documentation for the $http object. Can you post a source please? – catbadger Jul 27 '17 at 16:53
  • It is from the $http documentation '$http.post('/someUrl', data, config).then(successCallback, errorCallback);' – Vivz Jul 27 '17 at 16:56
0

There seems to be some confusion. According to the documentation at https://docs.angularjs.org/api/ng/service/$http you're not using $http right. have a look at the docs there and you should end up with something like:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
catbadger
  • 1,427
  • 14
  • 25
0

I changed the angularjs, to test. I did as @Vivz said. I think he's like this:

.controller('contatoController', function($scope, $stateParams, $ionicPopup, $ionicHistory, $http, $ionicPlatform, $state) {

      $scope.contato = {};

      $scope.Enviar = function(){

                  var data = {
                       "assunto_contato": $scope.contato.assunto,
                       "comentario_contato": $scope.contato.comentario
                   }
                   data = JSON.stringify(data);
                   var linkContato = 'http://apps.greenonetec.com.br/insert_contato.php';
                   $http.post(linkContato, data).then(function(response) {
                       console.log(response.data);
                   }).catch(function(error) {

                   });

                $ionicHistory.nextViewOptions({
                        disableBack : true
                })

                $ionicPopup.alert({
                  title: 'Sua mensagem foi enviada'
                }).then(function(){
                  $state.go('app.home');
                })
      }

})

But now he is giving this error:

OPTIONS http://apps.greenonetec.com.br/insert_contato.php 500 (Internal Server Error) - ionic.bundle.js:25005

XMLHttpRequest cannot load http://apps.greenonetec.com.br/insert_contato.php. Response for preflight has invalid HTTP status code 500

Lucas Santos
  • 119
  • 2
  • 7
  • The first error is caused maybe because your php is not expecting what you are sending. Unfortunately I don't know php that well to verify if your php code is working or not. But your 2nd error can be fixed by checking this https://stackoverflow.com/questions/33660712/angularjs-post-fails-response-for-preflight-has-invalid-http-status-code-404. Try to solve the second one, maybe the first one will also resolve. – Vivz Jul 27 '17 at 17:09
0

change your $http like this one.. i detect you was '' the $scope values. there are wrong.

.controller('contatoController', function($scope, $stateParams, $ionicPopup, 
$ionicHistory, $http, $ionicPlatform, $state) {

  $scope.contato = {};

  $scope.Enviar = function(){

        var linkContato = 'http://apps.greenonetec.com.br/insert_contato.php'
        $http({
           method:'POST',
           url:linkContrato,
           data:{ 
               "assunto_contato" : $scope.contato.assunto, 
               "comentario_contato" : $scope.contato.comentario 
               },
           headers: { 'Content-Type': 'application/json; charset=utf-8' }
          }).then(function(resp){
             console.log(resp); //success
          }, function(error){
              //if error
          });


})
Jesus Carrasco
  • 1,356
  • 1
  • 8
  • 15
  • about the prefligh check allow headers , allow methods allow origin in your configuration, some .htacces rules, or in your index.php – Jesus Carrasco Jul 27 '17 at 17:48
0

I changed again.

Receives_json.php

<?php

header("Access-Control-Allow-Origin: *");

$assunto_contato = $_POST["assunto_contato"];
$comentario_contato = $_POST["comentario_contato"];
$nome_contato = $_POST["nome_contato"];
$data = date("Y-m-d H:i:s");

$conn = new mysqli("", "", "", "");
$sql_insert = 'INSERT INTO contato(assunto_contato, comentario_contato, nome_contato, data_contato)';
$sql_insert .= 'VALUES (?, ?, ?, ?)';

$stm = $conn -> prepare($sql_insert);
$stm->bind_param("ssss", $assunto_contato, $comentario_contato, $nome_contato, $data);

if ($stm->execute()){
    $retorno = array("retorno" => 'YES');
 } else {
    $retorno = array("retorno" => 'NO');
 }

 echo json_encode($retorno);

 $stm->close();
 $conn->close();
?>

my angularjs

.controller('contatoController', function($scope, $stateParams, $ionicPopup, $ionicHistory, $http, $ionicPlatform, $state) {

  $scope.contato = {};

  $scope.Enviar = function(){

            var linkContato = 'http://apps.greenonetec.com.br/insert_contato.php'
        $http({
           method:'POST',
           url:linkContato,
           data:{ 
               "assunto_contato" : $scope.contato.assunto, 
               "comentario_contato" : $scope.contato.comentario 
               },
           headers: { 'Content-Type': 'application/json; charset=utf-8' }
          }).then(function(resp){
             console.log(resp); //success
          }, function(error){
              //if error
          });

            $ionicPopup.alert({
              title: 'Sua mensagem foi enviada'
            }).then(function(){
              $state.go('app.home');
            })


            console.log($scope.contato.assunto);
            console.log($scope.contato.comentario);
  }

})

In the database is generating a record, but I can not get the variables coming from angularjs. And it's not giving any errors on the chrome console.

Does anyone know what I'm doing wrong in php?

Lucas Santos
  • 119
  • 2
  • 7