1

I'm having a problem with getting data over to my PHP file after decoding Json and I am getting an error. Can someone help me to know where I am going wrong?

app.js

 $scope.formPost = function(){


        $http.post('sendmail.php',{msg: 'helo'})
            .success(function(data,status,headers,config){


                console.log('data: ' + data);
                console.log('status: ' + status);
                console.log('headers: ' + headers);

            }).error(function(data,status,headers,config){

            });


};

sendmail.php

$data = json_decode(file_get_contents("php://input"), true);

$msg = $data->msg;
echo $msg;

And the error message I'm getting is

Notice: Trying to get property of non-object in /Applications/MAMP/htdocs/my-new-project/sendmail.php on line 5

Any thoughts?

arsenalist
  • 391
  • 4
  • 18

3 Answers3

0

Whether this is the whole of the problem, I can't say at the moment, but you have specifically asked json_decode() to return an associative array by passing it a second parameter of true.

Either start using $data as an array, or get rid of the true.

Jonnix
  • 4,121
  • 1
  • 30
  • 31
0

looks like you are sending regular form data, not json, so you can use the php superglobal $_POST];

//$data = json_decode(file_get_contents("php://input"), true);

$msg = $_POST['msg'];
echo $msg;
Steve
  • 20,703
  • 5
  • 41
  • 67
  • still showing empty array when using the global POST. In my console I can see the data, however when I try to show it via the url (php) nothing is sent. The array is empty and var_dump shows NULL. – arsenalist Jun 01 '15 at 19:44
  • @arsenalist `". In my console I can see the data, however when I try to show it via the url (php) nothing is sent"` Please explain what you meaan by `"show it by the url"`? – Steve Jun 01 '15 at 19:53
  • I meant when I try to send it to the php file. For example, in my console I get data: object(stdClass)#1 (1) { ["msg"]=> string(4) "helo" } (this is for the data portion) however, when sending it to sendmail.php, I am getting NULL when using var_dump... also for status getting 200 so I know it's successful. – arsenalist Jun 01 '15 at 19:56
0

Here what I did to solve same issue:

$scope.submitData = function() { 

    var myobject = {'destination': destination, 'title': _title, 'message': _message};

    Object.toparams = function ObjecttoParams(obj) {
        var p = [];
        for (var key in obj) {
            p.push(key + '=' + encodeURIComponent(obj[key]));
        }
        return p.join('&');
    };   

    $http({
        method: 'POST',
        url: "data/insert.php",
        data: Object.toparams(myobject)
    })

}   

And Php:

$data = file_get_contents("php://input");
$destination = $_POST["destination"];
$title = $_POST["title"];
$message = $_POST["message"]; 

As based to this answer: https://stackoverflow.com/a/15485690/5255820

Community
  • 1
  • 1
Arda Ilgaz
  • 65
  • 1
  • 7