-1

I want to get data from my Database into my Angluar.js.

So i created a php file, which selects my data. I read that i have to use jsonp, elsewhise i will not get the data.

data.php

<?php 
    $db = mysqli_connect("xxx", "xxx", "xxx", "xxx");
    $select = "select * from product;";
    $result = mysqli_query($db,$select);        

    if ($result) {
        $i=0;
        $outp = "";
        while ($row = mysqli_fetch_assoc($result))
        {
            if ($outp != "") {$outp .= ",";}
            $outp .= '"preis":"'   . $row["preis"]        . '",';
            $outp .= '"name":"'. $row["name"]     . '"}';
        }
        $outp ='{"records":['.$outp.']}';

        echo($outp);
    }
 ?>

App.js

var url = "http://server/data/data.php?callback=JSON_CALLBACK"

    $http.jsonp(url)
    .success(function(data){
        console.log(data.found);
    });

Now i get a syntax error: "SyntaxError: unexpected token: ':'"

Thanks for your help

Fabian
  • 177
  • 1
  • 14
  • "I read that i have to use jsonp, elsewhise i will not get the data." — No. You need to do *something* to work around the Same Origin Policy if you want to do Ajax across origins. JSONP is a dirty hack that achieves that. We have CORS now. Use CORS. – Quentin May 18 '18 at 14:23
  • Do not generate JSON by mashing strings together manually. PHP has had [`json_encode`](http://php.net/json_encode) for ages. – Quentin May 18 '18 at 14:24
  • Now I use the json_encode and it looks like the SyntaxError is gone. But I get a 404 Error when I run the js... Even the php reports the correct data. I can put my url in for example https://jsonformatter.org/. And it says it's a valid json. The question you linked in here as the duplicate is not helping me. Any other suggestions? – Fabian May 20 '18 at 09:09
  • 404 just means you got the URL wrong on top of any other problems you have. – Quentin May 20 '18 at 10:20
  • But i can reach the url. That's why i wonder, why it says 404... – Fabian May 20 '18 at 10:30

1 Answers1

0

Don't build JSON by yourself. Try this instead. Main thing is, just create an array the way you'd like it, then use json_encode()

$result = [];
while ($row = mysqli_fetch_assoc($result))
{
    $result[] = $row;
}

echo json_encode($result);
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
  • This helped me for the moment. It looks like the json Object is now correct. But I always get an 404 error. looks like i can't reach the data. But I can open the url in my browser and I can see the data. – Fabian May 20 '18 at 11:04