Remote REST webservice in PHP receiving JSON via POST with problems

Asked

Viewed 2,187 times

5

I have the following situation...

  1. A purely javascript client application that runs with Node.js, where you post a JSON, as follows:
    doLoad = function (livrosList){
            var xmlhttp = new XMLHttpRequest();    
            xmlhttp.open("POST", "http://servidor_remoto/webservice/webs.php", true);
            xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
            arqJson = JSON.stringify(livrosList);

        xmlhttp.send(arqJson);
    }
  1. A PHP Webservice that receives the free listList and stores your data in the Mysql database:
       include('LivrosList.php');
       header('Content-Type: application/json; charset=utf-8');
       header("access-control-allow-origin: *");

     $obj_php = json_decode(stripslashes($_POST['arqJson']));       
     if(empty($_POST['arqJson'])){
        return;
     }

    $livros = new Livros;

    foreach ( $obj_php as $liv ) { 
        $livros->insertLivros($liv->nome, $liv->numeropaginas);
    }

The problem is that $_POST['arqJson'] is not being recognized. I see that in the apache log is occurring that arqJson is not defined. I don’t know about the fact that it’s on a remote server. So how could I send this data list to the webservice and store such data in the database? Thanks for your help!

1 answer

12


The problem is that Webservice is sending the POST with the Content-Type: application/json and PHP does not $_POST with the data sent in this way.

$_POST will only be automatically filled in if the Content-Type be it application/x-www-form-urlencoded or multipart/form-data.

To read the objects received in this POST you must do as follows:

// lê o json diretamente dos dados enviados no POST (input)
$json = file_get_contents('php://input');
$obj_php = json_decode($json); // $obj_php agora é exatamente o objeto/array enviado pelo servidor

$livros = new Livros;

foreach ( $obj_php as $liv ) { 
    $livros->insertLivros($liv->nome, $liv->numeropaginas);
}

I’ve already broken my head a lot with this same problem. I hope it helps!

  • Thank you very much, that was the problem. It worked!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.