I am trying to create a simple on/off link using jquery and ajax. Basically what I want to to is add a link to a page that when clicked will insert a row into my database and update the text of the link. Then when clicked again, that record will be deleted from the database.
So far everything works as expected but the problem is that the second time the link is clicked, the record is deleted like it should, but the page refreshes and redirects to the homepage.
I am following the "plus 1 vote widget" example from Pro Drupal Development and am trying to alter the code to suit my needs. Following is my .js file.
$(document).ready(function() {
$('a.toggle-visibility-links').click(function() {
var parentDiv = $(this).parent();
var toggleSaved = function (data) {
$(parentDiv).html(data.toggleon);
}
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
success: toggleSaved,
data: 'js=1'
});
return false;
});
});
Here is my "toggle_visibility" module code
/**
* Implementation of hook_menu().
*/
function toggle_visibility_menu() {
$items = array();
$items['toggle-visibility'] = array(
'page callback' => 'toggle_visibility_toggle',
'access arguments' => array('toggle profile'),
'type' => MENU_CALLBACK,
);
return $items;
}
/*
* page callback
*/
function toggle_visibility_toggle() {
global $user;
$toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
$toggle_result = db_query($toggle_sql, $user->uid);
$num = mysql_num_rows($toggle_result);
if (!$num) {
db_query('INSERT INTO {toggle_visibility} (uid, visible) VALUES (%d, %d)', $user->uid, 1);
} else {
db_query('DELETE FROM {toggle_visibility} WHERE uid = %d', $user->uid);
}
if (!empty($_POST['js'])) {
drupal_json(array(
'toggleon' => '<a href="/toggle-visibility">Toggle My Profile On</a>'
)
);
exit();
}
//UPDATE THIS TO RETURN TO THE SAME PAGE
$path = drupal_get_path_alias('node');
drupal_goto($path);
}
/**
* Implementation of hook_theme().
*/
function toggle_visibility_theme() {
return array(
'toggle_visibility_link' => array(
'arguments' => array(),
),
);
}
/**
* Return a message for no results
*/
function theme_toggle_visibility_link() {
drupal_add_js(drupal_get_path('module', 'toggle_visibility') . '/toggle_visibility.js');
global $user;
$toggle_sql = "SELECT * FROM {toggle_visibility} WHERE uid = %d";
$toggle_result = db_query($toggle_sql, $user->uid);
$num = mysql_num_rows($toggle_result);
if ( $num == 0 ) {
$link = '<a href="/toggle-visibility" class="toggle-visibility-links">Toggle My Profile Off</a>';
} else {
$link = '<a href="/toggle-visibility" class="toggle-visibility-links">Toggle My Profile On</a>';
}
return $link;
}
Not sure what I'm missing.
Thanks!