2

I have a button in my custom module

  function sign_up_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['captcha']['#suffix'] ='<input type="button" id="test" name="test" value="OK">';

    $form['#attached']['js'][] = array
      (
       'type' => 'file',
       'data' => drupal_get_path('module', 'sign_up') . '/js/sign_up.js',
    );

         $form['actions']['submit'] = array("#type" => "submit", "#value" => "Create Account", 
        "#ajax" => array(
        "wrapper" => "formwrapper", "effect" => "fade", "method" => "replace",));
   }

Note: Ive removed the callback key of #ajax inorder to avoid page refresh.

In my sign_up.js I made an ajax call when this button is clicked.

  $(function() {

      $("#test").click(function(){

         $.ajax({url:"/path/to/normalphp/page/userLogin.php",success:function(response){

          alert(response);


      }});
    });
  });

The onclick is working and the ajax call is also successful.

In my userLogin.php (not a module file.Normal php file) I just hardcode the uid and call user_login_submit() .

<?php

 chdir($_SERVER['DOCUMENT_ROOT'].'/');
 define('DRUPAL_ROOT', getcwd());
 //Load Drupal
 require_once './includes/bootstrap.inc';
 drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); 


  $account = array('uid' => 49); //existing uid
  user_login_submit(array(), $account);

The result which I expect is to automatically redirect the user to welcome screen.But this is not happening.When I try to login with this user from the drupal login page its successful. This is just a test as I wanted to customize my registration screen (make ajax calls,jquery validations etc) and then automatically redirects to welcome screen when the validation is success. Note: I have already done the settings in drupal where email notification is not needed. Can someone help me out in this?

1 Answer 1

2

Instead of using jQuery AJAX, you can achieve this by Drupal Form API AJAX.

You can hide the Actual submit button in the hook_form_alter using hide() and add a custom button with AJAX callback.

Or if you still want to practice this using jQuery AJAX, Drupal's way of handling AJAX calls is little different. You may have to first understand the hook_menu in Drupal. Once you have a clear understanding of this system, you have to create pages using this hook. In drupal, it is not advisable to create custom php files for handling AJAX callbacks. Instead you can create a page using hook_menu and handle the server callback there. For the JS part, the Drupal way is to use Drupal Behaviors

This is a small example of how it would look like.

Your custom module to handle AJAX login (sign_up.module)

<?php
function sign_up_menu {
    $items = array();
    $items['custom/user-login'] = array(
        'page callback' => 'custom_user_login_callback',
        'type' => MENU_CALLBACK,
        'access callback' => TRUE
    );
    return $items;
}
function custom_user_login_callback(){
    /**
     *  You can validate the User credentials here and provide error message for invalid credentials or send him to welcome page using drupal_goto() for valid credentials
    **/
}

-

The custom JS file (sign_up.js)

Drupal.behaviors.customSignUp = {
    attach: function(context, settings) {
        $("#test", context).once(function(){
            $(this).click(function(){
                $.ajax({
                      url: Drupal.settings.basePath + 'custom/user-login',
                      type: 'POST',
                      data: {
                        username: /** Pass the User Name **/
                        password: /** Pass the Password **/
                      },
                      success: function(response) {
                        $('#ajax-response-wrapper').html(response);
                        Drupal.attachBehaviors();
                      }
                });
            });
        });
    }
};
5
  • Excellent! Ive just started working on drupal, sorry for the avg knowledge, didnt know about hook_menu() .Thanks for the detailed example.
    – wilNev
    Apr 7, 2015 at 7:16
  • A quick clarification, how do I get the response from callback function? I tried with an echo and its working.Just wanted to know if there are any other ways.
    – wilNev
    Apr 7, 2015 at 9:14
  • 1
    Preferred method is to use drupal_json_output Apr 7, 2015 at 9:18
  • One more thing I noticed is the page is not redirecting when Ive gave drupal_goto('path') , instead return that 'path' as druupal_json_output and redirect from js file like window.location.replace(path)
    – wilNev
    Apr 7, 2015 at 9:22
  • Yes. You are correct !! Apr 7, 2015 at 10:25

Your Answer

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

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