2

I am having a problem trying to get information from a array using Angular.js + PHP.

The idea is: When the user goes to /post/76 (for example), the script will get the ID and return all relevant information (title, content, views, etc).

$routeProvider

carolvaladares.config(function($routeProvider) {
    $routeProvider.
        when('/post/:postId', {
            templateUrl : 'views/post.html',
            controller  : 'postCtrl'
        })
});

Controller

carolvaladares.controller('postCtrl', function($scope, $http, $routeParams) {

    var postId = $routeParams.postId;

    $http.get("php/get-posts.php?id=" + postId).then(function (response) {
        $scope.post = response.data;
    });

});

PHP

<?php
    require_once("connect.php");
    header('Content-Type: application/json');

    if (isset($_GET['id'])) {
        $id = $_GET['id'];
        $q = mysqli_query($conexao,"SELECT * FROM posts WHERE id = '$id'");
    } else {
        $q = mysqli_query($conexao,"SELECT * FROM posts");
    }

    $result = array();

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

    echo json_encode($result);
?>

(In this case, if the id is specified, it will only get data for one post. Otherwise, it will list data for all posts).

There is no problem until now. But when I try to print a single field of the array, it returns an empty object [] on console and does not show anything in the HTML.

HTML

<div id="post">
    {{post.title}} / DOES NOT WORK /
    {{post}} / WORKS / (PRINTS THE WHOLE ARRAY)
</div>

Thanks in advance.

(EDITED)

Array

[
   {
      "id":"76",
      "titulo":"Carrot Cake Americano",
      "sub":"Para esse Fim de Ano, aproveite essa receita maravilhosa de bolo de cenoura!",
      "corpo":"<p>Receitinha mara pra quem vai passar o dia 24 com a barriguinha no fog&atilde;o tipo eu. <strong>o\/<\/strong> Nada mais, nada menos que ele, o tradicional <strong>Carrot Cake Americano.<\/strong><\/p>\r\n<p><strong><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia3_carrotcake_cv.jpg\" alt=\"\" \/><\/strong><\/p>\r\n<h2>Bora cozinhar!<\/h2>\r\n<p><strong>Massa &ndash; Ingredientes:<\/strong> <br \/><strong>2<\/strong> x&iacute;caras de farinha de trigo <br \/><strong>1<\/strong> x&iacute;cara de a&ccedil;&uacute;car <br \/><strong>12<\/strong> x&iacute;cara de a&ccedil;&uacute;car mascavo <br \/><strong>2<\/strong> colheres de ch&aacute; de canela em p&oacute; <br \/><strong>1<\/strong> colher de ch&aacute; de noz-moscada <br \/><strong>2<\/strong> colheres de ch&aacute; de bicarbonato de s&oacute;dio <br \/><strong>1<\/strong> colher de ch&aacute; sal <br \/><strong>1\/2<\/strong> x&iacute;cara de passas <br \/><strong>1\/2<\/strong> x&iacute;cara de ovo <br \/><strong>2<\/strong> claras de ovos <br \/><strong>2<\/strong> x&iacute;caras de cenoura ralada <br \/><strong>1\/2<\/strong> x&iacute;cara de ma&ccedil;&atilde; ralada <br \/><strong>1\/3<\/strong> de x&iacute;cara de &oacute;leo <br \/><strong>3<\/strong> colheres de sopa de &aacute;gua quente<\/p>\r\n<p><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia_carrotcake_cv.jpg\" alt=\"\" \/><\/p>\r\n<p><strong>Cobertura &ndash; Ingredientes:<\/strong> <br \/><strong>500g<\/strong> de Filadelphia <br \/><strong>1<\/strong> x&iacute;cara de ch&aacute; de a&ccedil;&uacute;car de confeiteiro <br \/><strong>1<\/strong> colher de ch&aacute; de extrato de baunilha <br \/>Nozes para decorar<\/p>\r\n<p><strong>Modo de preparo:<\/strong> <br \/>&mdash; Pr&eacute;-aque&ccedil;a o forno a 250&ordm;C <br \/>&mdash; Pulverize duas bandejas de bolo redondo (9 polegadas) com spray de cozinha sem gordura. <br \/>&mdash; Misture a farinha, os dois tipos de a&ccedil;&uacute;car, canela, noz-moscada, bicarbonato de s&oacute;dio e sal em uma tigela m&eacute;dia. <br \/>&mdash; Bata o ovo e as claras em uma tigela grande. <br \/>&mdash; Adicione a cenoura, ma&ccedil;&atilde;, &oacute;leo e passas e &aacute;gua quente, mexendo at&eacute; misturar. <br \/>&mdash; Com uma esp&aacute;tula, adicione a mistura de farinha &agrave; mistura de cenoura e mexa at&eacute; misturar. <br \/>&mdash; Espalhe a massa uniformemente nas bandejas de bolo. <br \/>&mdash; Asse os bolos at&eacute; dourar cerca de 30-32 minutos.<\/p>\r\n<p>Deixe esfriar por 15 minutos. Retire os bolos da forma e deixe esfriar completamente.<\/p>\r\n<p>Para fazer a cobertura, com a batedeira em velocidade m&eacute;dia-alta, bata os ingredientes da cobertura at&eacute; ficar homog&ecirc;neo. Recheie o bolo e cubra com o creme de cream cheese.<\/p>\r\n<p><img src=\"http:\/\/www.carolvaladares.com.br\/staff\/uploads\/2015\/materia_gastronomia2_carrotcake_cv.jpg\" alt=\"\" \/><\/p>\r\n<p>Doce tem que ser bonito, por isso eu sempre fa&ccedil;o cobertura em bolo com bico de confeiteiro, da&iacute; vai da imagina&ccedil;&atilde;o de cada um. Pique as nozes ou use-as inteiras e jogue por cima.<\/p>\r\n<p>Deixe esfriar e depois se<strong> destrua<\/strong> com o <strong>bolo deuso!<\/strong><\/p>",
      "colunista":"denise",
      "slug":"gastronomia\/carrot-cake-americano",
      "thumbnail":"staff\/uploads\/2015\/denise-materia_gastronomia3_carrotcake_cv.jpg",
      "tags":"carrot cake, cake, carrot, cenoura, bolo, receita, americano, estados unidos, eua, usa, bolo de cenoura",
      "source":"",
      "data":"2015-12-22",
      "hora":"13:00:00",
      "views":"56",
      "categoria":"gastronomia",
      "aprovado":"1"
   }
]

(EDITED)

The solution was {{post[0].x}} and for the HTML content ng-bind-html along with the dependence ngSanitize

4
  • If requesting one row don't need a new outer php array for it, just return that row which would then become javascript object ... otherwise try {{post[0].title}} Commented Jan 13, 2016 at 16:50
  • @charlietfl That worked for the title, but {{post[0].body}} is a HTML, and it's printing now as plain text... Commented Jan 13, 2016 at 16:54
  • that needs to use ng-bind-html ...{{}} is only for text. Read docs about ng-bind-html regarding use of $SCE Commented Jan 13, 2016 at 16:58
  • @charlietfl Thanks! Using ng-bind-html and the dependence ngSanitize it worked! Commented Jan 13, 2016 at 17:09

1 Answer 1

1

can you show how the printed out array looks? Would help in debugging.

Anyway... My first guess would be that you are missing 1 level of the array when accessing it like

post[0].title 

Because: mysql_fetch_assoc returns an array and you put that array into an array and encode it with json_encode.

My second guess would be that you have to parse the response first, as its JSON: do

$scope.post = JSON.parse(response.data);
Sign up to request clarification or add additional context in comments.

2 Comments

$http will parse the json internally
JSON.parse() returned a error. But post[0].title worked fine. Thanks!

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.