I am currently starting a new project on node.js. I'm new to node.js, so I'm probably still doing mistakes. Before this day, I've always been mixing the client-side code with my php code. Now, because Node.js can't do PHP, I have to separate my Javascript from my PHP. My solution to overcome this problem is to use AJAX.
As of now, my client-side code and PHP are running on the same computer, but on 2 different servers (Node.js and Apache). I couldn't come up with a better way to do it, if there is any. I have selected jQuery to test this setup, because I have used it with success in the past.
I have prepared a little PHP script for my backend server which returns the content of the $_GET variable.
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
echo $_GET['callback']."(".json_encode($_GET).")";
On the client side, here is what I've got:
$.ajax({
url:"http://localhost/backend/index.php",
dataType: 'jsonp',
method: "GET",
data: {
name: 'John Doe',
},
success:function(json){
console.log("Success");
console.log(json);
},
error:function(){
console.log("Error");
}
});
Because of the CORS, I think I am limited to using the jsonp option. When I run this code, it works very well, and my console displays the following object:
{
callback: "jQuery33107847483665543953_1517785619328",
name: "John Doe",
_: "1517785619329"
}
I don't really understand the callback and the _ properties, but it works so I'm happy.
But now, I would like to send my data via POST instead of GET.
In my AJAX code, I replace method: "GET"
by method: "POST"
.
I don't touch anything in the PHP code.
I would expect my script to return an empty object or the same one without the name property.
Instead, it sends back the exact same object. It looks like my code doesn't want to send data as POST.
Then, if I modify the last line of my PHP code to what's below, I get an empty array in return:
echo $_GET['callback']."(".json_encode($_POST).")";
I am quite puzzled, because I have never encountered this issue. And I've used AJAX many times.
Anyone knows what's happening?
Thanks a lot!