0

I need an json for jquery catcomplete and I would like you to help me...

I have this code

$( ".autocomplete" ).autocomplete({
     source: "files/news.php?listar=json"
});

And I would like "files/news.php?listar=json" to display something like this:

[ 
  { label: "title1", category: "category1" },
  { label: "title2", category: "category2" } 
]

Could you please help me?

@edit:

I tried this, but it didn't work:

if ($_GET['listar'] == 'json')
{
    echo '['."\n";  
    $query = mysql_query("SELECT * FROM noticias WHERE deletada='0' ORDER BY id DESC");
    $a = 0;
    while ($noticia = mysql_fetch_array($query))
    {
        echo ' { label: "'.$noticia['titulo'].'", category: "'.ucwords(Categoria($noticia['categoria'])).'" }';
        $a++;

        if ($a < mysql_num_rows($query))
        {
            echo ",\n";
        }
    }
    echo "\n".']';

    exit;
}
Sergio Toledo Piza
  • 793
  • 1
  • 6
  • 27
  • 1
    So, it is actually a PHP question??? Where do your titles and categories come from? Write some PHP code and use `json_encode` – Bergi Oct 14 '12 at 22:11
  • JSON shown is invalid.. keys should be double quoted. If this is a php issue look into `json_encode( array)`. In future it would help if you spent a little more time putting together a concise and specific question. As it is right now... everyone will guess what your issue is – charlietfl Oct 14 '12 at 22:15

2 Answers2

3

Question is bit confusing. You are expecting JSON in PHP. In PHP, you can use build in function json_encode to convert any array into JSON and return it as response.

Your tags suggest you need it in JS. In JS, try json2.js

Kapil Sharma
  • 10,135
  • 8
  • 37
  • 66
2

You don't need writing own json, because it's already function for json encode(): http://php.net/manual/en/function.json-encode.php

if ($_GET['listar'] == 'json')
{
    $query = mysql_query("SELECT * FROM noticias WHERE deletada='0' ORDER BY id DESC");
    while ($noticia = mysql_fetch_array($query))
    {
    $results[] = array(
        'label' => $noticia['titulo'],
        'category' => $noticia['categoria']
    );
    }
}

$json = json_encode($results);
header('Content-type: application/json');
echo $json;
exit;
Marin Sagovac
  • 3,932
  • 5
  • 23
  • 53