Created
November 5, 2013 10:36
-
-
Save mrded/7317066 to your computer and use it in GitHub Desktop.
Drupal: Update item by ajax.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
Drupal.behaviors.Foo = { | |
attach:function (context, settings) { | |
// unbind() because click events firing multiple times. | |
$('#foo a.update', context).unbind().click(function (event) { | |
// Get parrent of item. | |
var item = $(this).closest(".item"); | |
// Get some data of item. | |
var uid = item.data('uid'); | |
// Get some data of another items. | |
var existed = []; | |
$('#foo .item', context).each(function() { | |
existed.push($(this).data('uid')); | |
}); | |
item.hide(300); | |
$.ajax({ | |
type: 'POST', | |
url: window.location.protocol + "//" + window.location.host + '/foo/ajax', | |
cache: false, | |
dataType: 'html', | |
data: { | |
uid: uid, | |
existed: existed | |
}, | |
complete: function(msg) { | |
item.html(msg.response).show(300); | |
Drupal.attachBehaviors(context); | |
} | |
}); | |
return false; | |
}); | |
} | |
} | |
})(jQuery); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_menu(). | |
*/ | |
function foo_menu() { | |
$items = array(); | |
$items['foo/ajax'] = array( | |
'page callback' => '_foo_ajax', | |
'page arguments' => array(), | |
'access callback' => 'user_is_logged_in', | |
'type' => MENU_CALLBACK, | |
); | |
return $items; | |
} | |
function _foo_ajax() { | |
$uid = $_POST['uid']; | |
$existed = $_POST['existed']; | |
// Do something here | |
// Store data for ajax. | |
$vars['attributes_array']['data-uid'] = $account->uid; | |
// Return to ajax. | |
print $html; | |
exit; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment