Div Refresh without page load using ajax drupal

1.6k views Asked by At

I want to load the data from db and want to display the counts example: message(5).So i have written the query inside the the div.

<?php
    function load()
    {
        echo "<div id='count'>";
        db_select("query is here");
        echo "Message($count);
        echo "</div>";
    }
?>

I want to refresh the count div without page load in Drupal 7. can anyone help me for this

Thanks in Advance.

3

There are 3 answers

1
Alexey On

If you have referenced JQuery, then you can use:

//Some data to pass, if needed in JSON
var form_data ={
    param1 : "hello"
};

$.ajax({
           type: "POST",
           url: "Here is the URL to your method that will call the database",
           data: form_data,

           success: function(data)
           {
                //In from your file or method, return a value to be displayed. It will be in data variable.

               alert(data); //Alerts the value you passed

           }

         });
1
Andi On

As PHP is processed on the Server, you always have to reload the Page if you want to insert a value via PHP.

To fetch it via ajax, the data update has to be done with javascript on the client.

So put your php code in one file like creatediv.php.

Then load it via javascript (jquery in this example)

$("div").load("creatediv.php");

This function executes your script on the server and puts the returned text inside your div.

0
MilanG On

So, on front-end side you can use jQuery, as guys explained above. On Drupal side, make some php script, add to it's beginning common Drupal bootstarp:

define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

After that you can use all drupal features - drupal is initialized. So, you can read the views, load nodes, what ever. Generate what ever you need (html, json) and print it out.

And you'll call that script with your ajax call. You can of course pass the parameters...as usual.