Drupal 7 ajax form submit not working - ajax

I have a node page where I need to create a reply form via ajax for commenting. Commenting in my system is also a kind of node.
When my page first loads it's presented with all comments done and also only one textbox & submit button which is used to add a new comment node. When I click submit button that comment is added via ajax.
Below each comments there is reply option. When I click on this reply, an ajax call is made to bring a new text area & reply button which are coming using same node form that is presented in form above. When this new form is presented I fill it up and submit at that time it's not submitted via ajax instead it redirects to destination URL.
Following is my menu & form alter code.
function mymodule_menu() {
$items['user_reply_comments/%/%'] = array(
'title' => t('Reply to User Comment'),
'page callback' => 'mymodule_user_reply_comment',
'page arguments' => array(1, 2, 3),
'access callback' => TRUE,
'type' => MENU_CALLBACK,
'delivery callback' => 'ajax_deliver',
'file' => 'includes/mymodule.pages.inc',
);
return $items;
}
function mymodule_form_comment_node_statement_form_alter(&$form, &$form_state, $form_id) {
drupal_add_library('system', 'drupal.form');
drupal_add_library('system', 'drupal.ajax');
drupal_add_js($base_url. '/' .path_to_theme().'/js/script.js', 'file');
$form['#action'] = url('user_reply_comments/'.$id.'/'.arg(2) .'/ajax');
$form['actions']['submit']['#ajax'] = array(
'callback' => 'mymodule_comment_node_statement_form_callback',
'wrapper' => 'comment-replies-' . arg(2),
'method' => 'replace',
'effect' => 'fade',
'event' => 'click',
'progress' => array('type'=> 'throbber',
'message' => "<div></div>",
),
'js' => array(
$base_url. '/' .path_to_theme().'/js/script.js',
),
);
}
/**
* Ajax callback for comment_node_statement_form.
*/
function mymodule_comment_node_statement_form_callback($form, &$form_state) {
/*echo '<pre>';
print_r($form);
exit;*/
//echo ' 1 :' . arg(1) . ' 2:' .arg(2); exit; // sub reply dows not came here
$message_empty = drupal_get_messages();
if(!empty($message_empty) && isset($message_empty ['error'])){
global $base_url;
$command_add = array();
if(user_is_anonymous()){
$command_add = ajax_command_invoke(NULL, "redirect_user", array($base_url));
}
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_before('#content', '<div id="inline-messages" class="messages error">'.$message_empty ['error'] [0].'</div>'),
ajax_command_invoke(NULL, "greyout_reply"),
$command_add
)
);
}
else{
$current_path = TRUE;
$statement_page_reply_form = "";
$pos = strpos($_SERVER['HTTP_REFERER'], "statements");
if($pos !== FALSE){
$current_path = FALSE;
}
// print_r($_SERVER['HTTP_REFERER']);
// print "$$$".$current_path."###"; exit;
// Clear the messages (drupal_set_message() doens't work for some reason).
$_SESSION['messages'] = '';
if($current_path){
$html = "<div class='arrow'>arrow</div>";
}
else{
$html = "";
}
$id = $form['#node']->nid;
if (!empty($form['build_info_args_' . $id]['#value'])) {
$form_state = array(
'build_info' => array('args' => $form['build_info_args_' . $id]['#value']),
'values' => array(),
) + form_state_defaults();
}
$form_state['rebuild'] = TRUE;
//$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$comment_form = drupal_rebuild_form('comment_node_statement_form', $form_state, $form);
$node_comments = views_embed_view('statement_replies', 'block', $id);
if($form['current_url']['#value'] == "dashboard"){
$comment_form['current_url'] = array('#type' => 'hidden', '#value' => "dashboard", '#name' => 'current_url');
$html .= '<div class="dashboard-statements-comments">';
}
if($current_path){
$html .= '<div class="statement-comment-reply-box">'.drupal_render($comment_form).'</div>';
}
else{
$statement_page_reply_form = '<div class="arrow">arrow</div><div class="statement-comment-reply-box">'. drupal_render($comment_form).'</div>';
$num_comments = db_query("SELECT COUNT(cid) AS count FROM {comment} WHERE nid =:nid and status = :status",array (":nid"=>$id, ":status" => '1'))->fetchField();
$statement_page_reply_form .= '<span class="statement_total_replies">'.$num_comments. ' Replies</span>';
$statement_page_reply_form .= '<span class="collapse_reply">COLLAPSE</span>';
}
$html .= '<div class="statement-comment-reply-feed">'.$node_comments.'</div>';
if($form['current_url']['#value'] == "dashboard"){
$html .= '</div>';
}
if($current_path){
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
)
);
}
else{
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#statement-replies-' . $id, $html),
ajax_command_html('.statement_upper_part .reply_form_statement', $statement_page_reply_form),
ajax_command_remove('#inline-messages'),
ajax_command_before('#content', '<div id="inline-messages" class="messages status"><h2 class="element-invisible">Status message</h2>Reply posted.</div>'),
ajax_command_invoke(NULL, "alter_elements"),
)
);
}
}
}
/**
* This is function in mymodule.pages.inc
* Callback function for 'user_reply_comment/%/%' path.
*
* Returns the popup modal form consists of reply form
*
* #param $entity_id
* Integer representing node ID
* #param $current_cid
* Integer representing comment ID
*/
function mymodule_user_reply_comment($entity_id, $current_cid, $js = FALSE) {
$logged_in = user_is_logged_in();
$node = node_load($entity_id);
if($node) {
if ($node->type == 'statement' || $node->type == "user_comment") {
$replies = "<div class='arrow'>arrow</div>";
$ajax_css = "";
if ($logged_in) {
$edit = array('nid' => $node->nid);
$form = drupal_get_form("comment_node_{$node->type}_form", (object) $edit);
$replies .= "<div class='statement-comment-reply-box'>";
$replies .= drupal_render($form);
$replies .= "</div>";
}
else{
$ajax_css = ajax_command_invoke(NULL, "views_row_hide_border");
}
$replies .= "<div class='statement-comment-reply-feed'>";
$replies .= "</div>";
return array(
'#type' => 'ajax',
'#commands' => array(
ajax_command_html('#comment-replies-' . $current_cid, $replies),
ajax_command_invoke(NULL, "show_statement_replies", array('#comment-replies-' . $current_cid)),
ajax_command_invoke(NULL, "toggle_reply_links" , array($current_cid)),
ajax_command_invoke(NULL, "mymodule_user_reply_comment_reply" , array($current_cid, $edit)),
$ajax_css
));
}
}
}
/*
Following is there in script.js file
*/
(function($) {
$.fn.mymodule_user_reply_comment_reply = function(cid, nid) {
var form_class = '.comment-form-' + nid + '--' + cid;
var button = form_class + ' input.form-submit';
console.log('reply thread click.' + cid);
$(button).bind('click', 'upload_reply_image');
/*{
console.log($(this).attr('id'));
return false;
e.preventDefault();
e.stopPropogation();
//Drupal.attachBehaviors($(form_class));
return false;
});//*/
console.log('reply thread out.' + cid);
};
})(jQuery);
/* To toggle between Reply expand/collapse mode in statement/Comment box and their reply box - Start */
(function($) {
$.fn.toggle_reply_links = function(cid) {
jQuery('#close-sub-comments-' + cid).parent().find('a').toggle();
};
})(jQuery);
(function($) {
$.fn.show_statement_replies = function(id) {
jQuery(id).slideDown();
};
})(jQuery);
Thanks in advance.

I think you have wrong path in your code. You need to change this in hook_menu:
$items['user_reply_comments/%/%'] = array(
With this:
$items['user_reply_comments/%/%/ajax'] = array(
At least there's something that doesn't match in my opinion.
Clear your menu cache to see the changes.
Hope that helps.

Related

Create category on the front-end with Ajax in WordPress

I'm having difficulty getting this to create a category on the front-end with Ajax. It's 99% working.
Here is my form:
<form id="new_idea" name="new_idea" method="POST">
<ul>
<li>
<label>Idea name</label>
<input type="text" name="idea_name" required />
</li>
<li class="full">
<label>Description</label>
<input type="text" name="idea_description" />
</li>
</ul>
</form>
Here is my function (in functions.php):
add_action( 'wp_ajax_add_new_idea', 'add_new_idea' );
add_action( 'wp_ajax_nopriv_add_new_idea', 'add_new_idea' );
function ajax_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('inputs')
);
wp_enqueue_script('my-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('my-ajax', 'inputs', $parameters );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
// New Idea
function add_new_idea() {
if(isset($_POST["new_idea_form"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $_POST['idea_name'];
$idea_description = $_POST['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
...and this is my ajax.js:
$('#new_idea').on('submit', function(e) {
e.preventDefault();
$.post( inputs.ajaxurl, {
action : 'add_new_idea',
nonce : inputs.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
ResponseSuccess(response);
});
return false;
});
As for troubleshooting, if I hardcode values into the $idea array like this and submit the form...
$idea = array(
'cat_name' => 'cool idea',
'category_parent' => '',
'category_nicename' => 'cool-dea',
'category_description' => 'a description of my cool idea',
'taxonomy' => 'ideas'
);
...it actually works and my category gets created.
So from what I can tell, the real problem is that it is not getting the $_POST[] values that were submitted, although I can't see why.
Any help would be awesome.
Try this code.
function add_new_idea() {
$params = array();
parse_str($_POST["post"], $params);
if(isset($_POST["post"])) {
ajaxStatus('error', 'No need to update anything.');
} else {
$nonce = $_POST['nonce'];
if(wp_verify_nonce($nonce, 'inputs') !== false) {
require_once(ABSPATH . 'wp-admin/includes/taxonomy.php');
$idea_name = $params['idea_name'];
$idea_description = $params['idea_description'];
$idea_slug = sanitize_title_with_dashes($idea_name);
$idea = array(
'cat_name' => $idea_name,
'category_parent' => '',
'category_nicename' => $idea_slug,
'category_description' => $idea_description,
'taxonomy' => 'ideas'
);
wp_insert_category( $idea );
//print_r($idea);
//die;
// Success message
ajaxStatus('success', 'Added new idea');
} else {
// No nonce!
ajaxStatus('error', 'Nonce failed!');
}
}
}
Read This
you need to use parse_str for serlize object.
Retrieving serialize data in a PHP file called using AJAX

drupal 7 ajax dependent dropdown

I have created a custom html form that is having 2 dropdowns State and City. When selects a State i want to populate the city dropdown. But the feature is not working. I already followed many urls but unable to solve the issue.
See the code below i have tried. Can anybody help me.
function zenuineform($form, &$form_state) {
$value_dropdown_first = isset($form_state['values']['comp_state']) ? $form_state['values']['comp_state'] : 1;
$form = array();
$form['comp_state']=array(
'#type'=>'select',
'#title'=>t('State : '),
'#options'=> $state_arr,
'#default_value' => $state,
'#ajax' => array(
// When 'event' occurs, Drupal will perform an ajax request in the
// background. Usually the default value is sufficient (eg. change for
// select elements), but valid values include any jQuery event,
// most notably 'mousedown', 'blur', and 'submit'.
'event' => 'change',
'callback' => 'zenuineform_ajax_callback',
'wrapper' => 'filtered_city',
),
);
$form['comp_city']=array(
'#type'=>'select',
'#title'=>t('City : '),
'#default_value' => $city,
'#prefix' => '<div id="filtered_city">',
'#suffix' => '</div>',
'#options' => zenuineform_second_dropdown_options($value_dropdown_first),
);
return $form;
}
function zenuineform_ajax_callback($form, $form_state) {
return $form['comp_city'];
}
function zenuineform_second_dropdown_options($state_id = '') {
if($state_id !='' ) {
$result = db_query('SELECT * FROM zen_city WHERE state_id = '.$state_id);
if ($result) {
$options = '<option value="">--Select--</option>';
while ($row = $result->fetchAssoc()) {
$rows[$row['id']] = $row['city_name'];
}
return $rows;
}
}
else {
return array('--Select--');
}
}

Drupal 7 node_save() causes AJAX to fail

I've created custom node form with only two fields attached. Each field have own "Save" AJAX button. On "Save" button click, everything goes as if it is default node form submission. Here is the full code:
/**
* Form;
*/
function mymodule_custom_form($form, &$form_state) {
$node = node_load(123);
$node->langcode = entity_language('node', $node);
// Store node object in form state
if (!isset($form_state['node'])) {
if (!isset($node->title)) {
$node->title = NULL;
}
node_object_prepare($node);
$form_state['node'] = $node;
}
else {
$node = $form_state['node'];
}
// Basic node information.
// These elements are just values so they are not even sent to the client.
$properties = array('nid', 'vid', 'uid', 'created', 'type', 'language');
foreach ($properties as $key) {
$form[$key] = array(
'#type' => 'value',
'#value' => isset($node->$key) ? $node->$key : NULL,
);
}
// Changed must be sent to the client, for later overwrite error checking.
$form['changed'] = array(
'#type' => 'hidden',
'#default_value' => isset($node->changed) ? $node->changed : NULL,
);
// TEST 1 field
field_attach_form('node', $node, $form, $form_state, $node->langcode, array(
'field_name' => 'field_test_1'
));
// Set the form prefix and suffix to support AJAX
$form['field_test_1']['#prefix'] = '<div id="wrapper-field-test-1">';
$form['field_test_1']['#suffix'] = '</div>';
// the submit button
$form['field_test_1']['save'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#name' => 'button-field-test-1',
'#ajax' => array(
'callback' => 'mymodule_custom_form_ajax_submit',
'wrapper' => 'wrapper-field-test-1',
'method' => 'replace',
'effect' => 'fade',
)
);
// TEST 2 field
field_attach_form('node', $node, $form, $form_state, $node->langcode, array(
'field_name' => 'field_test_2'
));
// Set the form prefix and suffix to support AJAX
$form['field_test_2']['#prefix'] = '<div id="wrapper-field-test-2">';
$form['field_test_2']['#suffix'] = '</div>';
// the submit button
$form['field_test_2']['save'] = array(
'#type' => 'submit',
'#value' => t('Save'),
'#name' => 'button-field-test-2',
'#ajax' => array(
'callback' => 'mymodule_custom_form_ajax_submit',
'wrapper' => 'wrapper-field-test-2',
'method' => 'replace',
'effect' => 'fade',
)
);
return $form;
}
/**
* Form validate;
*/
function mymodule_custom_form_validate($form, &$form_state) {
$field_name = reset($form_state['triggering_element']['#parents']);
// Validate only the stuff we need
$fields = array(
'field_test_1',
'field_test_2'
);
foreach ($fields as $field => $bundle) {
if ($field_name != $field) {
unset($form_state['values'][$field], $form_state['input'][$field]);
}
}
// $form_state['node'] contains the actual entity being edited, but we must
// not update it with form values that have not yet been validated, so we
// create a pseudo-entity to use during validation.
$node = (object) $form_state['values'];
node_validate($node, $form, $form_state);
entity_form_field_validate('node', $form, $form_state);
}
/**
* Form submit;
*/
function mymodule_custom_form_submit($form, &$form_state) {
// Execute all submit functions
$node = $form_state['node'];
entity_form_submit_build_entity('node', $node, $form, $form_state);
node_submit($node);
foreach (module_implements('node_submit') as $module) {
$function = $module . '_node_submit';
$function($node, $form, $form_state);
}
// Save the node
node_save($node);
$form_state['values']['nid'] = $node->nid;
$form_state['nid'] = $node->nid;
}
/**
* Form ajax submit;
*/
function mymodule_custom_form_ajax_submit($form, &$form_state) {
$field_name = reset($form_state['triggering_element']['#parents']);
// validate the form
drupal_validate_form('mymodule_custom_form', $form, $form_state);
// if there are errors, return the form to display the error messages
if (form_get_errors()) {
$form_state['rebuild'] = TRUE;
return $form[$field_name];
}
// process the form
mymodule_custom_form_submit($form, $form_state);
// Show the processing box
$form[$field_name] = array('#markup' => 'Thanks!');
$form[$field_name]['#prefix'] = '<div id="wrapper-' . str_replace('_', '-', $field_name) . '">';
$form[$field_name]['#suffix'] = '</div>';
// return the confirmation message
return $form[$field_name];
}
The code works perfectly, except that node_save($node) causes The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved. error.
No errors, if I remove it. But I need to save node and trigger all the hooks.
I think the issue caused by this line :
// process the form
mymodule_custom_form_submit($form, $form_state);
in your ajax function, try to use the node_save into your ajax function. mymodule_custom_form_submit is the conventional hook usually used. It seems to be several save process at the same time.
I don't know if you've solved it or not, but I've been stuck in a similar situation.
I avoid the error: The content on this page has either been modified..., modifying changed value in $form_state. In your submit function: mymodule_custom_form_submit, right after node_save($node), Add this line:
$form_state['input']['changed'] = $node->changed;
Drupal 7 full Save & Stay callback function, please add wrapper for form:
function <MODULE_NAME>_node_ajax_save_callback($form, &$form_state){
// If error, return form.
if (form_get_errors()) {
return $form;
}
node_form_submit($form, $form_state);
$form['changed']['#value'] = $form_state['node']->changed;
return $form;
}

Drupal Ajax Form Ajax Form to pull two different views

I have two different views that need to be toggled on a node page. I cannot put these two views together so I have created a form that will basically take the values of the form that I create, and send them as arguments to the view and display the view. I am attempting to do with this ajax. It works fine but the problem is the second time I run the form it does not refresh or update that view.
function photoflight_albums() {
photoflight_gallery_themes();
$output = render(drupal_get_form('photoflight_gallery_form'));
$output .= "<div id='gallery-ajax-wrapper'>";
$output .= views_embed_view('gallery', 'default');
$output .= "</div>";
return $output;
}
//Grabs the node titles
function photoflight_gallery_themes(){
$type = "photo_theme";
$theme_list = array();
$nodes = node_load_multiple(array(), array('type' => $type));
foreach($nodes as $themes){
$theme_list[$themes->title] = $themes->title;
}
return $theme_list;
}
//Form calls back to the function above to the gallery-ajax-wrapper div output above
function photoflight_gallery_form($form, &$form_state){
$form = array();
$form['themes'] = array(
'#type' => 'select',
'#options' => array(photoflight_gallery_themes()),
'#ajax' => array(
'callback' => 'photoflight_simplest_callback',
'wrapper' => 'gallery-ajax-wrapper',
),
);
//debug($form);
return $form;
}
//Ajax callback
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = $view->preview('default', $args);
return array("#markup" => $output);
}
The issue was that it was removing the HTML element so the second call had no HTML to replace. Changed to either use ajax update or on the call back wrap the return in the div again
function photoflight_simplest_callback($form, $form_state) {
$view = views_get_view('gallery');
$args = array( 'title' => $form_state['values']['themes']);
$view->set_exposed_input($args);
$output = '<div id="gallery-ajax-wrapper">';
$output .= $view->preview('default', $args);
$output .= '</div>';
return array("#markup" => $output);
}

Drupal.attachBehaviors not effect to returned ajax form

I'm working on Drupal 7, I have a form constructed like this
function qt_debate_response_form($form, &$form_state, $node_id){
$form['node_id'] = array(
'#type' => 'value',
'#value' => $node_id,
);
$form['response_body'] = array(
'#type' => 'textarea',
'#required' => TRUE,
'#row' => 4,
'#default_value' => '',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Post'),
'#ajax' => array(
'callback' => 'qt_debate_response_form_js',
'wrapper' => 'response-message-' . $node_id,
'method' => 'append',
'effect' => 'fade',
),
);
return $form;
}
And an ajax callback function to add new comment
function qt_debate_response_form_js($form, $form_state) {
global $user;
$body_text = $form_state['values']['response_body'];
$node_id = $form_state['values']['node_id'];
$message_js = '
<script language="javascript" type="text/javascript">
qt_debate_response_load_new_item(' . $node_id . ',' . $user->uid . ');
jQuery(".response-form-wrapper textarea").val("");
</script>';
$comment = new stdClass();
$comment->nid = $form_state['values']['node_id']; // Node Id the comment will attached to
$comment->cid = 0;
$comment->pid = 0;
$comment->uid = $user->uid;
$comment->is_anonymous = 0;
$comment->homepage = '';
$comment->status = COMMENT_PUBLISHED;
$comment->language = LANGUAGE_NONE;
$comment->subject = text_summary($body_text, null, 60);
$comment->comment_body[$comment->language][0]['value'] = $body_text;
$comment->comment_body[$comment->language][0]['format'] = 'filtered_html';
comment_submit($comment);
comment_save($comment);
$output = $message_js;
return $output;
}
here are my Javascript that load new created comment into Div (ajax)
function qt_debate_user_post_load_new_items(debate_id) {
// get the latest comment id in context
$top_comment = jQuery(".view-debate-user-posts .views-row").first();
$top_comment_id = jQuery(".nid-field-hidden", $top_comment).html();
jQuery.ajax({
type: "GET",
url: "/qt_debate/ajax/load_new_items/" + debate_id + "/" + $top_comment_id,
data: "",
success: function(html){
$new_items = jQuery(".view-content", html);
jQuery("form", $new_items).attr("action","/debate/199");
jQuery(".form-submit", $new_items).attr("id","edit-submit--5");
if ($new_items.html() != null) {
html = '<div class="new_items_wrapper" style="display: none">' + $new_items.html() + '</div>';
if (jQuery(".view-debate-user-posts .view-content").length == 0) {
jQuery(".view-debate-user-posts .view-empty").remove();
jQuery(".view-debate-user-posts").append('<div class="view-content"></div>');
}
jQuery(".view-debate-user-posts .view-content").prepend(html);
jQuery(".view-debate-user-posts .view-content .new_items_wrapper").fadeIn(500, function() {
jQuery(".views-row", this).unwrap();
Drupal.attachBehaviors();
});
}
},
});
var t = setTimeout("qt_debate_user_post_load_new_items(" + debate_id + ")", 30000)
}
The hook_menu which is return the views content to jQuery call back
function qt_debate_ajax_load_new_items() {
$debate_id = arg(3);
print views_embed_view('debate_user_posts_load_new_items_', 'default', array($debate_id));
exit(0);
}
View template file, i also return a new form inside
print drupal_render(drupal_get_form('qt_debate_response_form', $row->nid));
The return view content rendered good, with Drupal.attachBehaviors in Javascript, all others effect in returned view content also work well. Except the form submit ajax.
Can any one help please ? The attachBehaviors not work with return ajax form.
Thanks so much!
Drupal.attachBehaviors(context);
basically re-runs any functions defined by
Drupal.behaviors.yourFunctionName = function(context) {
$('div.someSelectorclass:not(.already-processed-class)', context).addClass('already-processed-class').bind(someMethod);
}
and these methods must add a selector [already-processed-class] to test for whether the bind(); [ or click(function(e){}); or each(function(){}); or whatever ] has already been added. The "context" is to pass less-than 'document' - say, if your new content is known to be inside a smaller context that will still be found by original behaviors function: in this example I could pass the parent container selector of my new 'div.someSelectorclass'
Drupal.attachBehaviors('div.parentContainerClass');
instead of
Drupal.attachBehaviors(document);

Resources