views:

89

answers:

2

I'm pretty new to ajax and I applied it succesfully to a Drupal site. But I was wondering, how do I get an URL to a page where part of the content is loaded through ajax. Is this even possible? The JSON object is retrieved on click, so how do I make it work when retrieving a certain URL? I realize this is a very broad questionany, any help would be greatly appreciated. Thanks in advance!

My JS looks like this:

  Drupal.behaviors.ajax_pages = function (context) {
  $('a.categoryLink:not(.categoryLink-processed)', context).click(function () {
    var updateProducts = function(data) {
      // The data parameter is a JSON object. The films property is the list of films items that was returned from the server response to the ajax request.
      if (data.films != undefined) {
        $('.region-sidebar-second .section').hide().html(data.films).fadeIn();
      }
      if (data.more != undefined) {
        $('#content .section').hide().html(data.more).fadeIn();
      }

    }
    $.ajax({
      type: 'POST',
      url: this.href, // Which url should be handle the ajax request. This is the url defined in the <a> html tag
      success: updateProducts, // The js function that will be called upon success request
      dataType: 'json', //define the type of data that is going to get back from the server
      data: 'js=1' //Pass a key/value pair
    });
    return false;  // return false so the navigation stops here and not continue to the page in the link
}).addClass('categoryLink-processed');
}
A: 

I don't know what exactly you are trying to do. But unless you have a module that creates the JSON data you need to do it yourself.

You would need to create a menu callback with hook_menu. In the callback function you can return json data by using drupal_json.

If you create the menu callback etc yourself, the URL will be whatever you make it to. Else you just have to use the URL defined by the module you want to use.

googletorp
+1  A: 

On the begining of the page load ajax based on hash part of the url page#id,

$(document).ready(function() {
  $.ajax({
     type: 'POST',
     url: "/path/to/page",
     success: updateProducts,
     dataType: 'json',
     data: 'id=' + window.location.replace(/.*#/, '')
  });

  $('a.categoryLink:not(.categoryLink-processed)', context).click(function () {

    $.ajax({
      type: 'POST',
      url: "/path/to/page",
      success: updateProducts,
      dataType: 'json',
      data: 'id=' + this.href.replace(/.*#/, '')
    });
});

Or you can use jquery-history but I didn't test it.

jcubic
Remember to add the menu handler within your module.
Andrew Sledge