1

This is the first time for me to use the jQuery $.ajax() in Drupal. The code is a simple test code but it keeps going to the error: section instead of success:. Could my url path be wrong? The .js file and the test-ajax.php file are in the same folder named "code".

    //This is Javascript
    $.ajax({
        url: 'code/test-ajax.php',
        data: 'a=hello&b=world',
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(){
            alert('FAIL'); //Keep getting "FAIL". It's like it can't find the php file.
        }
    });

Nothing fancy inside the file test-ajax.php:

<?php
$a = $_POST['a'];
$b = $_POST['b'];

echo "$a, $b";
?>

EDIT: To avoid confusion on the paths (I keep it organized):

  • Main theme files: <templatename>/<.info, template.php, style.css, etc.>
  • Template files: <templatename>/templates/*.tpl.php
  • AJAX files: <templatename>/code/<PHP and .JS files>
2
  • Not enough information. I can't see where Drupal part in your example. But if files are in the same folder you don't need code/ prefix in your url.
    – kalabro
    Commented Aug 21, 2011 at 18:42
  • Both url: 'code/test-ajax.php' and url: 'code/test-ajax.php' don't seem to work. Isn't that odd? In WP I use url: TEMPLATEDIR + '/code/test-ajax.php' is there a Drupal version of that?
    – enchance
    Commented Aug 21, 2011 at 19:47

7 Answers 7

1

Change

url: 'code/test-ajax.php',

to

url: Drupal.settings.basePath + 'sites/all/themes/YOURTHEME/code/test-ajax.php',

Anyway, the more Drupal way is to use hook_menu to register your callback instead of putting a PHP file in your theme folder.

1
  • Or, as many having pointed out, you need a debugger like Firebug to understand why there is an error, then to fix it. But a quick look tells me that it's an 404.
    – jcisio
    Commented Aug 21, 2011 at 20:58
1

In Drupal, JavaScript files are added via the drupal_add_js() function or in the theme’s .info file. A simple example of using jQuery in drupal is

    <?php
    drupal_add_js('jQuery(document).ready(function () {
   jQuery.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });
    });', 'inline');
    ?>

you have to use 'jQuery' instead of $.

3
  • I use the .info file but your answer is interesting. So the code above is placed inside a PHP file...which PHP file? Wouldn't this generate errors since it's using jQuery syntax?
    – enchance
    Commented Aug 21, 2011 at 20:17
  • this code is inside the function 'drupal_add_js('your jQuery code','inline');' so this code wouldn't generate any error. Commented Aug 21, 2011 at 20:35
  • This answer is partially correct in that this is one way to do it. What you should do if you prefer to use $ instead of jQuery is wrap your code in (function($){ $(document).ready(...); })(jQuery);
    – Jason Gray
    Commented Jan 30, 2014 at 21:15
0

As with all programs, it's impossible to fix an error unless you know what's wrong.

jQuery will pass three parameters (jqXHR, textStatus, errorThrown) to the error function to help you determine what your problem is. You may be getting a 404 which means you need to fix your path (or flush your drupal cache to get the hook_menu() to be recognized). You may be getting a 500 which means you have a syntax error in your module. Or any of the other numerous problems you can encounter when using AJAX.

The documentation for these parameters is at http://api.jquery.com/jQuery.ajax/

0

I would write the same code like this:

//This is Javascript
    $.ajax({
        url: '/code/test-ajax.php',
        data: {'a':'hello','b':'world'},
        type: 'POST',
        success: function(data){
            alert(data); //Should return "hello, world"
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(textStatus + errorThrown); //Better diagnostics
        }
    });

Note the following:

  • URL is absolute (starts with /). If current page URL is node/x, then code/text-ajax.php will be looked up as node/code/text-ajax.php, which is (probably) wrong
  • error handler has parameters, which gives your better diagnostics
  • data is an object, not an URL string
1
  • That outputs: errorNot Found. Data is not always an object and can in fact be a data string in jQuery.
    – enchance
    Commented Aug 21, 2011 at 19:56
0

I already commented on this under the answer given by Mujtaba but here it is as a proper answer.

You do not have to change all $ to jQuery for this to work. As per the Drupal 7 documentation, you just need to wrap your code like this:

(function($){
  $(document).ready(function(){
    ...
  });
})(jQuery);

Then you can just keep writing your code using $ and it assigns $ to jQuery. It's basically doing the same thing as just writing your code using jQuery instead of the $ but saves you the trouble of find and replace on existing code and saves you characters (and thus file size) when making your code from scratch.

-1

How odd, I got it to work but only by using the complete URL path for the AJAX file.

url: 'http://mydomain.com/sites/all/themes/<themename>/code/test-ajax.php',

This just doesn't feel right. Is there a Drupal way of doing this instead of entering the complete URL path?

-1

Thanks to everyone who's commented (especially @jcisio)! Based on all your answers, I was able to come up with the THEMEPATH global variable which stores the complete path to the theme by using drupal_add_js().

drupal_add_js( array( 'themepath' => base_path() . path_to_theme() ), 'setting' );

Which you can then reference in your .js file as

var THEMEPATH; //a global variable
$(function(){
    THEMEPATH = Drupal.settings.themepath; //assign the variable
})

//THEMEPATH has to be assigned on page load and not before or else it won't work

So in the end, you simply use it in jQuery as: THEMEPATH + '/code/test-ajax.php'. I'm surprised Drupal doesn't have this by default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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