0

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!

  • _"my client-side code and PHP are running on the same computer, but on 2 different servers (Node.js and Apache)"_ <- why not just put your client-side code in Apache's document root? That way, you're just using the one server and there's no cross-origin issues – Phil Feb 04 '18 at 23:36
  • JSONP can **only** be a GET request because it is included as a `` – Phil Feb 04 '18 at 23:38
  • Interesting. So I'm stuck with GET as long as I am running JSONP :( –  Feb 05 '18 at 07:23
  • Putting the client side code on the Apache's document root would mean building the whole code every time I do a modification, and running it with Apache instead of Node.js. That's what you mean? It doesn't sound very convenient as the build process takes time, does it? –  Feb 05 '18 at 07:26

0 Answers0