I'm trying to figure out how to use jQuery's .ajax() to query a MySQL table and return the results as an array. This is what I have so far:

jQuery:

$.ajax({url: 'procedures?',
    data: {Action: 'GetSuggestList' },
    dataType: "json",
    success: function(oData){
        if(oData.errormsg != null)
              alert('failed: ' + oData.errormsg);
        alert(oData.results);
}});

PHP code (with the assumption that my mysql_connect() and mysql_select_db() are valid):

 $pcAction = isset( $_REQUEST['Action'] ) ? $_REQUEST['Action'] : "" ;
 if($pcAction=='GetSuggestList'){
     $tb_name = 'suggestions';
     echo json_encode( DoGetSuggestList($tb_name) ) ;
 }

 function DoGetSuggestList($ptb_name){
     $qry_suggest = mysql_query('SELECT * FROM ' . $ptb_name . ' WHERE Active ORDER BY updated DESC');
     $rsl_suggest = mysql_fetch_array($qry_suggest);
     $jSONreturn = array("errormsg" => $jSONerror, "results" => $rsl_suggest);

     return $jSONreturn;
 };

I'm not sure what else needs to be in my AJAX success function in order to iterate through each resulting row in the array...

link|improve this question

2  
If you want all of the results, shouldn't you have that mysql_fetch_array call in a while loop? What does the json you're getting back look like now? (you can use console.log(oData) if you have firebug installed) – machinemessiah Apr 20 '11 at 16:15
I would echo $pcAction... the table name $tb_name might not be set – colinmarc Apr 20 '11 at 16:20
@machinemessiah - I think you are right about having mysql_fetch_array in a loop because console.log(oData) is returning the results of just 1 record – sadmicrowave Apr 20 '11 at 16:23
feedback

1 Answer

up vote 3 down vote accepted

I think you need to have the results from the query dumped into an associate array before you json_encode() them.

while( ... ) { $a_results[] = array( 's_column' => $row['column'] ); }

return json_encode( array('errormsg' => $jSONerror, 'results' => $a_results) );

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.