0

I am trying to implement Typeahead.js to my site.

The typeahead.js will take from a remote page that would return JSON,
something like: http://example.org/search?q=%QUERY

For my site, this is what I've wrote for the PHP:

$q=mysql_real_escape_string($_GET['q']);

$getship= @mysql_query('SELECT * FROM `tbl` WHERE data1 LIKE \'%'.$q.'%\' OR schar LIKE \'%'.$q.'%\';');

while($tbl=mysql_fetch_array($getship)){
    $id=$tbl['id'];
    $data1=$tbl['data1'];
    $fplod=explode(" ",$data1);
    $data2=$tbl['data2'];
    $splod=explode(" ",$data2);
    $data3=$tbl['data3'];
    $data4=$tbl['data4'];
    echo '{
            "value":'.$id.',
            "tokens":["'.$fplod[0].'","'.$fplod[1].'","'.$splod[0].'","'.$splod[1].'"],
            "data1" :"'.$data1.'",
            "data2":"'.$data2.'",
            "data3":"'.$data3.'",
            "data4":"'.$data4.'"
        }';
}

But when ever I ask that typeahead thing to return, it seems to return in text/html and not application/json screenshot from Chrome browser .

How can I make this to work?

Thanks in advance

2
  • Also, I'm not familiar with JSON so I'm not really sure my JSON structure is correct for the TypeAhead to work... But I'll work on that later (as soon as this is solved, which I think the reason this snippet won't run) Commented Sep 22, 2013 at 15:30
  • Isn't the answer type set by the client application and then just used by the server for the response? Commented Sep 22, 2013 at 15:33

4 Answers 4

2

You can set the Content-Type header yourself. Before any output is sent, call header:

header('Content-Type: application/json');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I used this code because I don't feel like using the json encoder.
@KoiFish: Er, you should actually use both. What’s wrong with a JSON encoder? It will be a lot safer. And as it is, you have SQL injection problems, too…
2

That is not valid JSON. You do not have quotes around the names. PHP has built in json encoding/decoding functions already so you don't have to build the string yourself.

echo json_encode(array("value" => $id /* etc

Comments

0

It is not a good practice to convert your data into json manually, rather use json_encode

$data = array();
while($tbl=mysql_fetch_array($getship)){
   $data[] = $tbl;
}
$return = array("data"=>$data);
echo json_encode($return);

Comments

0

try something like:

while($row = mysql_fetch_array($getship, MYSQL_ASSOC))
{
    $row_set[] = $row;
}

echo json_encode($row_set);

you can also use mysql_fetch_assoc.

Comments

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.