0

I am requesting this PHP page below (welcome.php) from my local php server.

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

I am requesting in my Nativescript application (main-page.js)

exports.postRequest = function() {
    http.request({
        url:    "http://192.168.3.12:8888/php/welcome.php",
        method: "POST",
        content: JSON.stringify({ name: "test", email: "test@email.com"})
    }).then(function(result) {
        console.log("Success!");
        console.log(JSON.stringify(result));
    }, function(error) {
        console.error(JSON.stringify(error));
    });
}

Question(s):

I assume the problem is that it is looking for a JSON value to be returned? And the welcome.php is just creating two lines in the body of an html page. Should this automatically get parsed and converted into JSON? Is there a function that should return it to the requester? How can I edit this to get a value back into the .js file. Is my whole structure just off?

EDIT:

I mentioned in one of my comments to @Quentin that it doesn't matter whether I logged the 'result' as a plain object or not. This turned out to be untrue: if I just output the result without using JSON.stringify i get the following message:

JS: Success!
JS: Result (plain)[object Object]

I think it is still empty even after editing the welcome.php to be this:

<html>
<body>
<?php 
$_POST = json_decode(file_get_contents('php://input'), true);
?>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>

I think the issue lies with my input of the name & email vars in the main-page.js.

Edit 2

I went ahead and accept Woodrow's answer because it is getting me closer to a solution. I still have a bit more to look through. This post may have an answer for me. Thank you everyone for contributing!

Solution Edit:

I was able to (with help from everyone) to figure this disconnect out between my PHP on the server and .js file in Nativescript client. Thanks @Quentin, @Woodward, and @ MarekMaszay to name a few.

Here are the final files: jsonWelcome.php

<?php
$_POST = json_decode(file_get_contents('php://input'), true);
$name = $_POST['name'];

$email = $_POST["email"];
//This outputs to a log in the server specified in the php.ini. I used it 
// to see if/what the server was receiving from the .js file. I finally got 
// that part down & moved on to outputting the data as JSON below.
error_log("name: " . $name . " email:". $email); 

if ( $name == "taylor"){
  $data = "YESSSS";
} else {
  $data = "NOOO";
}
header('Content-type: application/json');  //I haven't tested without this.
exit (json_encode( $data));  //I needed to use the exit & json_encode together
?>

app/main-page.js (nativescript)

//Note I changed the 'result' to 'data'. I don't think it actually has any impact. I made other major changes.
exports.postRequest = function() {
    http.request({
        //url: "https://httpbin.org/post",
        //url: "https://httpbin.org/post
        url:    "http://192.168.3.12:8888/php/jsonWelcome.php",
        method: "POST",
        content: JSON.stringify({name: "testNS", email: "email@nativescript.com"})
          }).then(function(data) {
        console.log("Success!");
        console.log("Result (plain)" + data);
        console.log("Result 0" + data[0]);
        console.log("Result (json.stringify) " + JSON.stringify(data));
    }, function(error) {
        console.log("Failure");
        console.error(JSON.stringify(error));
    });
}

The result of the two above files will result in the following output from the console when run by clicking on the application.

JS: Result (json.stringify) {"content":"NOOO","statusCode":200,"headers":{"null":"HTTP/1.1 200 OK","Connection":"close","Content-type":"application/json","Date":"Fri, 28 Jul 2017 11:15:55 -0600","Host":"192.168.3.12:8888","X-Android-Received-Millis":"1501262155358","X-Android-Response-Source":"NETWORK 200","X-Android-Selected-Protocol":"http/1.1","X-Android-Sent-Millis":"1501262155342","X-Powered-By":"PHP/7.1.7"}}

Notice that content is equal to "NOOO" which is what we want in this case. Now that I have the basic data exchange down, I am happy. Thanks so much!

Oh and p.s. I think one of the main issues aside from editing the input & output was that I added php tags: <?php ?>

to my jsonWelcome.php file. I had completely missed this. Although there were other major issues, this was a major blindspot for me that was easily fixed with closer inspection.

Thanks!

TrivPants
  • 79
  • 9
  • 1
    "I assume the problem" — What are the symptoms of the problem? You've shown some code, but you haven't explained what result you get or what result you expect. – Quentin Jul 27 '17 at 16:15
  • 1
    Possible duplicate — [Reading JSON POST using PHP](https://stackoverflow.com/questions/19004783/reading-json-post-using-php) — but I'm really not sure what the question is. – Quentin Jul 27 '17 at 16:17
  • Sorry for being vague. In the program i just have a button that submits the Post request & will write to the log if it succeeds (with the 'Success!' line before the result) or write just the error if it fails. It's writing this to the output: "JS: Success!" The result is not writing at all. – TrivPants Jul 27 '17 at 16:19
  • 1
    What if you don't JSON.stringify `result` and just log it directly? It might not be a data type that can be converted to JSON. – Quentin Jul 27 '17 at 16:21
  • @Quentin if I just log the result directly it still doesn't show anything. Do I need to change my PHP to explicitly output anything? I edited the $_POST=json_decode(file_get_contents('php://input'),true); in the .php file. – TrivPants Jul 27 '17 at 16:30
  • 1
    The PHP *is* explicitly outputting a bunch of HTML. Aside from looking at the Network tab to see what is in the response (it's possible something about your server is broken), I'm out of ideas. I've not used nativescript and only have the documentation and knowledge of the underlying APIs to go on. I can't think of any reason why you would get a successful response but not have anything in result given the PHP file isn't empty. – Quentin Jul 27 '17 at 16:34
  • @Quentin Thank you. I'll keep messing with it & keep everyone updated on whether it is actually something of significance or just my own stupidity that is keeping me from achieving the desired results. – TrivPants Jul 27 '17 at 16:37
  • 1
    Try finally to remove that `JSON.stringify` from your function :) And change it to `content: { name: "test", email: "test@email.com"}` @TaylorCoomer – Marek Maszay Jul 28 '17 at 13:45
  • @MarekMaszay I tried removing the JSON.stringify and I still get the same response for the result object. It is still empty (outputing *[object Object]* and *undefined* when I try to output it without stringifying and then accessing result[0] respectively. – TrivPants Jul 28 '17 at 16:29

1 Answers1

1

You need to json_decode the posted data.. since you're sending it over as a JSON payload to the server. To get the POST data, you would have to do this:

$_POST = json_decode(file_get_contents('php://input'), true);
Woodrow
  • 2,740
  • 1
  • 14
  • 18
  • 3
    PHP will never populate `$_POST` with a json encoded string. PHP will never add extra slashes to `$_POST`. That code won't do anything useful. – Quentin Jul 27 '17 at 16:16
  • 2
    "If you are not using dataType : 'json', you might need to do stripslashes on the PHP side" — Rubbish. `dataType: "json"` is (a) jQuery (which the OP isn't using) and (b) has no effect on the formatting of the request body (it sets the `Accept` header and tells jQuery to ignore the response's `Content-Type` and parse as JSON (the PHP outputs as HTML not JSON) – Quentin Jul 27 '17 at 16:18
  • 1
    @Quentin you are correct, have updated my answer to ensure the $_POST input stream is read so it can then be used correctly in the context the OP is trying to use it. – Woodrow Jul 27 '17 at 16:18