2

I want to use ajax to load some html from a php file. I don't want to write a module. So, here's the thing I did:

In sites/all/themes/mytheme/js/myjs.js:

$('#color_main_id a').click(function() {
  $.ajax({
    url: "get_node_details.php",
    type: 'GET',
    cache: false,
    // data: nid <--- Question#1
    data:  "color=" + this.rel,
    success: function(data, status, jqXhr) {
      $('.product-summary').html(data);
    }
  });
});

In sites/all/themes/mytheme/js/get_node_details.php I wrote some code to get a node detail with entity_load and field_view_field.

Here's the questions:

  1. How can I pass the current node id from my js function in js file to php function in php file? (See the comment above)
  2. In get_node_details.php I've got Call to undefined function entity_load(). How can I solved this?

Thanks

  • A statement like "I don't want to write a module.", is worth motivating. – Letharion Mar 5 '12 at 8:46
  • Ok. Is it possible to do this without a module? – Pedram Behroozi Mar 5 '12 at 8:53
  • Is there a particular reason why you don't want to write a module? – Chapabu Mar 5 '12 at 9:11
  • This is a simple ajax call and it should be trigger on a link in a node form. So my module should alter node's menus and pages which doesn't seem a good idea. – Pedram Behroozi Mar 5 '12 at 9:33
  • 1
    You can always use script tags inside your tpl files and make it dirty like <?php <script> //all kinda codes written here doesnt follow any standards</script>?> – GoodSp33d Mar 5 '12 at 9:40
5

I'm sorry to say but, you are doing it wrong.

In some very few cases it could be worth not to write a module for an ajax request. The reason would be that you want to do something simple, not related to Drupal that needs to be very fast. I did this once for a site where I needed to look up if a domain name was registered or not.

In this case you are not isolated from Drupal. You need to know the context of your script (The node id) and you need to use the Drupal API's entity_load, so instead of creating a custom PHP file and writing code in there, why not create a module which is a PHP file, only it's named foo.module, use the drupal API's to in make the ajax callback hook_menu, and add the javascript with context drupal_add_js and you will save yourself a lot of work, by doing things the Drupal way. Drupal is made it make it easy to develop stuff by creating modules, instead of adding custom PHP files, which makes things a lot more difficult to manage.

If you really wanted to do this without creating a module, you would need to bootstrap Drupal in your custom PHP file (making it pointless to use a custom php file), and add the node id in the preprocess_node hook in your theme.

| improve this answer | |

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.