4

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);
3
  • would need to see the code that produces the error to have any chance at helping you. Commented Dec 7, 2016 at 2:39
  • I editted to include the php file and function issue. Commented Dec 7, 2016 at 3:00
  • i think your php file must be returning other output. you should be able to check with the firebug tools (f12) Commented Dec 7, 2016 at 3:01

2 Answers 2

5

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);    
Sign up to request clarification or add additional context in comments.

2 Comments

For whatever reason, the problem was that when I was in the 10.x.x.x:port website, it did not load the files properly, but when I went to my www... it was working fine. Thanks for the info anyways.
Don't forget to mark the answer as correct, for people who have the same problem in the future! :)
1

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.

1 Comment

I worked around it by just using jquery's $.ajax method. I don't really understand promises that much anyway :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.