1


After using jquery .load() in drupal 7, the database doesn't seem to work


module

   <script type='text/javascript'>            
   function loadPage (id,level) {
   $.ajax({   
          beforeSend: function () {   
            // here you can do things before the action start    
          },
          success: function () {
          $('#contenpage').load(\"$path/pages/page.php\", { 'var': [id,level]})
          }
        });
   } 
   </script>

I want to use the database in the page "page" and echo the result back.

page

 $query = db_select('course_function', 'f');
  $query
      ->fields('f', array('id'))
      ->condition('f.chapter_id', $id, '=')
  ;
  $result = $query->execute();
  print_r($result);
  foreach ($result as $res) {
    $id = $res->id;
  }
echo $id;

But it does not work - do I need to use the PHP manner?

2

Most likely that drupal database API is not available in your page.php file because corresponding files are not included in it. What I usually do if I want to do stuff like this, is declaring a menu item:

function MYMODULE_menu(){
    $items['path/page'] = array(
        'type' => MENU_NORMAL_ITEM,
        'page callback' => 'your_function_name',
        'title' => 'AJAX: Page callback'
    );
    return $items;
}

the code above adds a new page to drupal menu system and makes it available as: http://www.yoursite.com/path/page

and then in your function

function your_function_name() {
    $query = db_select('course_function', 'f');
    $query->fields('f', array('id'))
          ->condition('f.chapter_id', $id, '=');
    $result = $query->execute();
    print_r($result);
    foreach ($result as $res) {
        $id = $res->id;
    }
    echo $id;
    //You need to have exit in such callback functions to prevent drupal theme 
    //functions from taking over the page processing
    exit;
}    

Then in your javascript you can approach this page just like this:

<script type='text/javascript'>            
function loadPage (id,level) {
$.ajax({   
      beforeSend: function () {   
        // here you can do things before the action start    
      },
      success: function () {
          $('#contenpage').load("http://yoursite.com/pages/page", { 'var': [id,level]})
      }
    });
} 
</script>
  • Thank you verry much, if I had more points, I would give it +1 – Dieter Verbeemen Apr 24 '12 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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