mfadel
mfadel

Reputation: 897

.get jquery returns "array" string?

I am using .get to fetch a list of words from the db

$.get( "script/get_words.php", function( data ) {
    alert(data);
    words = data;
    $.each( words, function( k, v ) {
        availableTags[k] = v;
    })
});

$( "#tags" ).autocomplete({
    source: availableTags
});

this is the php in the get_words.php request I am calling

$sql = "select answer from questions";
$words =  array();
$result = run_query( $sql );
$i = 0;

// echo "1 $course_is is course_id and  $class_id is class_id <br>" ;   
while ( $row = mysql_fetch_assoc( $result ) ) {
    $words[$i] = $row['answer'];
    //echo $words[$i];
    $i++;   
}

return $words;

the problem it returns only the word Array, and not the list of words I asked for what could be the solution?

Upvotes: 0

Views: 1641

Answers (1)

Sampson
Sampson

Reputation: 268512

You're building an array server-side, and attempting to pass it back to the client. Since PHP doesn't implicitly know that you want an object for JavaScript, it does what it thinks it should, and prints the type.

Return JSON from PHP using json_encode():

json_encode( $php_array );

You can see the difference between in the following example:

$array = array( 'Foo' => 'bar' );

echo $array; // Array
echo json_encode( $array ); // {"Foo":"bar"}

From your $.get(), be sure to declare the response type to be JSON (or consider using $.getJSON() instead), and then you can iterate through its contents.

Upvotes: 1

Related Questions