A. L
A. L

Reputation: 12639

How to connect Angular 2 and a php backend (mysql)

So I understand and know how ajax works, as I've used it before. But how do I retrieve JSON data from a php script?

I've tried to echo the json_encode results (which works) but I get an EXCEPTION: Uncaught (in promise): Unexpected token < in JSON at position 0 error in Chrome.

Erroring line:

search(): any 
{   
     this.http.get('app/php/search.php').toPromise()
        .then(response => this.data = response.json())
        .catch(this.handleError);
}

Php file (for test purposes):

$json = array (
    "age" => 5,
    "bob" => "Lee",
);  
echo json_encode($json);

Upvotes: 4

Views: 9884

Answers (2)

ammy
ammy

Reputation: 326

why don't you use observables.. i have used php as a backend in one my dummy project. here is its code.

ngOnInit() { 

    let body=Path+'single.php'+'?id=' + this.productid;
    console.log(body);
    this._postservice.postregister(body)
                .subscribe( data => {
                            this.outputs=data;
//                            console.log(this.outputs);

                   }, 
                error => console.log("Error HTTP Post Service"),
                () => console.log("Job Done Post !") );  
  }

php code

$faillogin=array("error"=>1,"data"=>"no data found");
$successreturn[]=array(
        "productid"=>"any",
       "productname"=>"any",
      "productprice"=>"any",
    "productdescription"=>"any",
    "productprimaryimg"=>"any",
    "otherimage"=>"any",
    "rating"=>"any");
// Create connection  id,name,price,description,primary_image,other_image,rating

    $productid = $_GET["id"];
    $sql="SELECT * FROM product_list where id='$productid'";
    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);
    $value=0;
    while($line = mysqli_fetch_assoc($result))
       { 

         $successreturn[$value]['productid']=$line['id'];
         $successreturn[$value]['productname']=$line['name'];
         $successreturn[$value]['productprice']=$line['price'];
         $successreturn[$value]['productdescription']=$line['description'];
         $successreturn[$value]['productprimaryimg']=$line['primary_image'];
         $successreturn[$value]['otherimage']=$line['other_image'];
         $successreturn[$value]['rating']=$line['rating'];
         $value++;
        }
     echo json_encode($successreturn);    

 mysqli_close($conn);    

Upvotes: 5

danday74
danday74

Reputation: 56956

RE YOUR CODE

this.http.get('app/php/search.php').toPromise()
    .then((response) => {
      console.log(response); // does it look right?
      // is it in string format or json format?
      // if its in string format then can you JSON.parse(response)? if not you have a problem
      // is this line where your error is?
      this.data = response.json()
    })
    .catch(this.handleError);

RE YOU SERVER SETUP

i dont know a great deal about php but basically you want php to serve up an endpoint such as http://myphpserver/search.php

when you visit this page in the browser you should see xml.

would prob work better if the page extension was .xml instead of .php if thats possible.

Make sure your server is returning the correct MIME type / content type for XML. You may need to set the content type response header in PHP.

once you can see the JSON in your browser, then you just get angular2 to hit the same endpoint using http.get and bosh, job done.

Upvotes: 1

Related Questions