Search code examples
phpjquerydatabasedrupal-7

Populate dropdown with data from database using jQuery


Error is seen when i made a drop down list to populate data from Database.
Database : dtable
File in the template of hook_theme named : myModueForm_theme.tpl.php

<?php
$sel = "<select  name=\"select1\" id=\"select1\">
        <option value=\"\">Select...</option>
        <option value=\"data1\">data1</option>
        <option value=\"data2\">data2</option>
        <option value=\"data3\">data3</option>
        <option value=\"data4\">data4</option>
    </select>";
echo "$sel";

?>

script tag starts

jQuery("#select1").change( function(){
if( jQuery(this).val() == "data1" ) {
jQuery.ajax({
    type: "POST",
    url: "<?php echo $base_url;?>?q=search/data1",
    error: function(returnval) {
        alert("Failure");
    },
    success: function (returnval) {
        alert(returnval);
        alert("Sucess"); 
    }
})
}  
});  

script tag ends

The Module file which handles the database connection named : myModule.module

$items['search/data1'] = array() 
'title' => 'Add data', //page title
'description' => 'form',
'page callback' => 'search_data1',
'page arguments' => array('access content'),
'access callback' => TRUE

);

// in the search_data function

function search_data1(){  

$options="<select  name=\"select2\" id=\"select2\">"; 
$result = db_select('dtable', 'c')
    ->fields('c')
    ->execute() 
    ->fetchAll();
foreach ($result as $record) {
$name = ($record->dt1);
    $options.="<option value=\"$name\">".$name."</option>"; 
    //alert(node);

} 
$options.= "</SELECT>";
return $options;

}

What i want is
1-- please tell me where is the error & how to solve
2-- i want to return the page back to the theme php page with the query result , but when i display back the return value from the module file, i get the whole HTML .

Please help & treat me as a beginner.Thanks in advance... /\


Solution

  • The answer is :"Use ajax_deliver " the code will be:

     $items['search/won'] = array( 
     'title' => 'Add data', //page title
     'description' => 'form',
    'page callback' => 'search_won',
    'page arguments' => array('access content'),
    'delivery callback' => 'ajax_deliver',
    'access callback' => TRUE
    );