How to connect Angular 2 and php backend (mysql)

So, I understand and know how ajax works, since I used it before. But how can I get JSON data with php script?

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

Line error:

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

Php file (for testing purposes):

$json = array (
    "age" => 5,
    "bob" => "Lee",
);  
echo json_encode($json);
+4
source share
2 answers

why don't you use observables. I used php as a backend in one of my dummy project. here is his 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);    
+5
source

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);

SERVER TUNING

php, , php , ​​ http://myphpserver/search.php

, xml.

, .xml .php, .

, / MIME XML. , PHP.

JSON , angular2, , http.get bosh, .

+1

Source: https://habr.com/ru/post/1663044/


All Articles