1

I've a created an Ajax-callback page using my module available as myModule/somepage/%/% - you can see that last two arguments in this page changes dynamically.

I want to make an AJAX call to this page, writing javascript. Say, when I click a button an ajax call will be made to this page (POST method preferably for the two arguments).

I know how to create hyper-links that handle Ajax calls automatically, but in that way links are static, and I can not send arguments to my Ajax-callback page. So how do I write JavaScript to make an Ajax call to my page?

2

3 Answers 3

2

Here is the code to make POST req to a webpage.

$('#yourid').click(function(e) {
    e.preventDefault();
    var theUrl = base_url + 'myModule/somepage';
    $.ajax({
        url: theUrl,
        type: "POST",
        data: "name=John&location=Boston"
        success: function(msg){
        alert(msg);
        $('#displydiv').html(msg);
    }
    });
});
5
  • Is it going to work with Drupal's Ajax framework?
    – Shafiul
    Commented Apr 3, 2012 at 11:39
  • It works, but it returns a complete Drupal page with all it's HTMLs, css, everything... what I need to output is simple JSON data or something like that. :(
    – Shafiul
    Commented Apr 3, 2012 at 13:09
  • Try print and exit the html not return.
    – niksmac
    Commented Apr 4, 2012 at 3:41
  • Would that be a Drupal-way, to exit after printing?
    – Shafiul
    Commented Apr 4, 2012 at 6:06
  • Its just a security belt.
    – niksmac
    Commented Apr 4, 2012 at 6:57
0

Say, when I click a button an ajax call will be made to this page

If you want a form which has AJAX then you need to look at the FormAPI. This article also explain in quite good detail on how to build AJAX forms. If you want something other than forms then I suggest looking at jQuery API for jQuery.ajax. There's also a shorthand for jQuery.ajax which is jQuery.post.

1
  • I saw the FAPI's #ajax property, but in my special case I'm not getting it done. The form is hidden and Drupal is not submitting it at all, which I specified in this question: . I need some other way to submit the form, that's why I'm asking the Ajax way.
    – Shafiul
    Commented Apr 3, 2012 at 13:03
0

There is good documentation about FAPI and AJAX:

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.