4

I'm trying to recreate Post JSON from angular 2 to php but it doesn't work as there's nothing in the $_REQUEST variable on php side

The code:

searchHttp({body}: any): Promise<any>
{   
    let headers = new Headers ({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: "post" });

    let test_this = {"search": "person"};

    return this.http.post(this.post_url, JSON.stringify(test_this), options)
        .toPromise()
        .then(response =>  
            {   
                return response.text();
            })  
        .catch(this.handleError);
}

Is there something I'm missing? I know that posts works with another format because I have that answered in another question.

Also, is http.request better than http.post?

Edit:

After much consultation with Angular/Javascript experts, they believe this is a php issue. So anyone with knowledge of how to accept JSON objects on php side will be gladly welcomed.

Community
  • 1
  • 1
A. L
  • 11,695
  • 23
  • 85
  • 163
  • You can get rid of the request options. It's useless. What you are using is already the default. I don't use php, but are you sure this is not just a php problem? You angular code like fine. Maybe you want to post a php question instead. – Paul Samsotha Dec 15 '16 at 00:27
  • nope, php works fine since if I use jquery's Ajax it returns the results as expected. And I managed a work around from a previous answer (which you were part of) see... http://stackoverflow.com/questions/41135595/using-json-objects-in-urlsearchparams/41135641?noredirect=1#comment69475362_41135641 . Though if someone has a better answer I'll just leave this here – A. L Dec 15 '16 at 00:29
  • If you're talking about [this jquery](http://stackoverflow.com/q/41132472/2587435), that is not sending JSON. The default data type for jquery is application/x-www-form-urlencded, if you don't configure it for JSON. Google how to send JSON with jquery, then do it. I'm sure it will fail also, if this angular code is failing. Then Google how to accept JSON with php – Paul Samsotha Dec 15 '16 at 00:37
  • I know that `dataType: 'json'` is the format. That was for something else that I was testing. – A. L Dec 15 '16 at 00:39
  • you accept json on php with `json_decode` no? And for Ajax sending JSON, I guess I'll google it later. – A. L Dec 15 '16 at 00:41
  • No that's not it either that is for the type you are expecting back from the server. See the docs http://api.jquery.com/jquery.ajax/ – Paul Samsotha Dec 15 '16 at 00:42
  • Like I said I dont use php – Paul Samsotha Dec 15 '16 at 00:42

2 Answers2

4

angular 2 client side part

 ngOnInit() { 

        let body=Api+'product.php'+'?id=' + this.link_id;
        this._callservice.callregister(body)
                    .subscribe( data => {
                                this.outputs=data;                           
                       }, 
                    error => console.log("Error HTTP Post"),
                    () => console.log("completed") );  
      }    
    }

call.service.ts

import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable}     from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class AuthenticationService {

  constructor(private _http:Http){}

  postregister(api:any){
//      console.log(api);
  let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
  let options = new RequestOptions({ headers: headers, method: "post"});
      return this._http.get(api,options)
          .map(res => res.json())
          .catch(this.handleError);
  }
  private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || ' error');
    }

}

Server side PHP make sure on server side you have these three lines in php code.

   header('Access-Control-Allow-Origin: *');    
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

Php file:

  <?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";

$e=array("error"=>1,"message"=>"Account Already Exists");

$accountCreated = array( "error" =>0, 
                         "data" => array(
                                   "username" => "amit" , 
                                   "password" => "anypassword",
                                   "role"=> "user", 
                                   "id" => "anyid" ) );

// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

    $username = $_GET["username"];
    $Pass = $_GET["password"];
    $role= $_GET["role"];
    $sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
    $result = mysqli_query($conn,$sql);
    $line = mysqli_fetch_assoc($result);
    $count = $line['user'];
    if($count!=0)
       {
          echo json_encode($e);
       }
    else
       {
         $sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
         $result=mysqli_query($conn,$sql);
         $sql="select * from users where username ='$username'";
         $result=mysqli_query($conn,$sql);
         $line=mysqli_fetch_assoc($result);
         {
             $accountCreated['data']['username']=$line['username'];
             $accountCreated['data']['password']=$line['password'];
             $accountCreated['data']['role']=$line['role'];
             $accountCreated['data']['id']=$line['id'];
         }
         echo json_encode($accountCreated);
        }

 ?>

i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.

Amit kumar
  • 6,029
  • 6
  • 30
  • 40
  • I know how to do it via `get` method with the question mark. Just need to know how to do it for JSON format – A. L Dec 15 '16 at 02:01
  • 1
    can you try $str_json = file_get_contents('php://input'); on server side php. This reads the raw POST data. it may work in your case. read about it. – Amit kumar Dec 15 '16 at 05:36
1

There doesn't appear to be anything wrong with the Angular code. The issue is in what the PHP is expecting to receive. I am not a PHP expert, but as you've mentioned that it works fine with jQuery, then that indicates that your PHP is expecting a URL-encoded value (as jQuery tends to work with that), not a JSON value.

In other words, what the server is trying to parse is:

search=person

What you are sending is:

{ "search": "person" }

Try something more like the following to send it in the format you're wanting:

let test_this = { "search": "person" };
let headers = new Headers ({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers, method: "post" });

http.post(this.post_url, test_this, options)
Mitch
  • 1,839
  • 16
  • 23
  • Yeah it's probably the php side, do you know anything about expect a json format? – A. L Dec 15 '16 at 00:58
  • Um pretty much clueless with PHP. Whack a PHP tag on the question though and you might attract the right experts. – Mitch Dec 15 '16 at 01:01