[support] How to use ajax in form_submit_handler
Doug
doug.duboulay at gmail.com
Tue May 11 01:15:52 UTC 2010
On Mon, 10 May 2010, Scott wrote:
> I'm venturing into new territory regarding drupal module development.
> I'm working on a module that creates a form for collecting information
> used to build a url. The url is for an api that returns XML (not JSON).
> I need to know the preferred method for using ajax to either populate a
> div on the existing page or redirect to a new page. About all I've come
> up with while searching is AHAH and JSON.
This is just my experience - I've got no idea about "best practice".
Basically, for the page containing the form, you would need to call
drupal_add_js(file.js) to pipe your AJAX javascript to the client.
In the file.js you add your jquery AJAX callback function to
your module menu defined 'type'=>MENU_CALLBACK function - (which
is a hidden URL that never appears in the menu)
And for me, at least, my callback func had to finish with
if (!empty($_POST['js'])) {
//jQuery made the call.
//This will return a result to jQuery's request.
drupal_json($myReturnedJSON);
exit();
}
One of the issues I encountered, in Drupal 6 is that every Forms API
button, thinks its a "submit" button and wants to callhome for a
page refresh, rather than an asynchronous background page update.
I had to work around that with a from element like this:
$fform['apply']['Update'] = array(
'#weight' => 200,
// #button_type attribute ignored (=submit) bug work-around
'#type' => 'markup',
'#prefix' => '<input type="button" id="edit-apply-Update"' .
' value="Save new schedule" onclick="' .
'mymodule_update_schedule_js(\'' .
$base_url . '/?q=mymodule/admin/bookings/schedule/update\');" ' .
'/>',
'#value' => ' ',
);
where mymodule_update_schedule_js() is something you defined in file.js
and its argument is your target MENU_CALLBACK url.
I had something like this:
function proposaldb_update_schedule_js(updateTarget) {
var jsonData = JSON.stringify( stuff );
var instrument = $('#edit-filter-instrument').val();
$.ajax({
type: 'POST',
url: updateTarget + "/" + $('#edit-filter-instrument').val(),
dataType: 'json',
data: 'js=' + jsonData,
error: function( XmlHttpObj,status,errorT) {
alert("error uploading new JSON schedule " + status + ": " +errorT);
},
success: function( data) {
alert("successfully rescheduled");
}
});
}
Hope this helps
Cheers
Doug
More information about the support
mailing list