Remote REST WebService in PHP receiving JSON via POST with problems

5

I have the following situation ...

  • A pure javascript client application that runs with node.js, where I send via a JSON post, 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);
        }
    
  • A Webservice in PHP that receives the listList books 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 it is occurring that arqJson is not set. I do not know if it's because it's on a remote server. So how could I send this list of data to the webservice and store such data in the database? Thanks in advance for your help!

        
    asked by anonymous 15.01.2015 / 00:01

    1 answer

    12

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

    $_POST will only be automatically populated if Content-Type is application/x-www-form-urlencoded or multipart/form-data .

    To read objects received in this POST you should do the following:

    // 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 with this same problem. Hope it helps!

        
    15.01.2015 / 02:48