user3363537
user3363537

Reputation: 121

disable links with jquery inside php

I've been trying to disable some links that are linked in some way to a database, but i only need to disable them depending on the $_SESSION[]

echo '<script language="javascript">';
echo '$("a").removeAttr("href");';
echo "$('a').click(function(event){
    event.preventDefault();
    alert('No tiene permisos para ingresar');
});";
echo "</script>";

these are some of the thins I've tried but the links are still working.

Upvotes: 0

Views: 65

Answers (4)

Krishna M
Krishna M

Reputation: 1195

You need enclose your jquery code with

$(document).ready(function()
{
  });

You can see the result in this link http://jsfiddle.net/2B75J/

Upvotes: 0

rjdmello
rjdmello

Reputation: 863

Use $.bind and $.unbind

$( "a" ).bind( "click", function() {
         alert( "The quick brown fox jumps over the lazy dog." );
 });

and in session check just use unbind

$( "a" ).unbind( "click" );

Upvotes: 0

Lenny
Lenny

Reputation: 5939

First, try using this code as plain JavaScript and get it working (no PHP) just get the links to disable. Like this... should work.

<script language="javascript">
    function disableLinks(){
        $('a').removeAttr('href');
        $('a').click(function(event){
            event.preventDefault();
            alert('No tiene permisos para ingresar');
        });
    }

    //trigger the function after the DOM is ready (possible problem)
    $(document).ready(disableLinks);
</script>

If that doesn't work use Javascript console on chrome and look for errors. Make sure jQuery is loaded. There is a chance with your previous code you were trying to disable the links before the page was loaded. the document.ready ensures the DOM is loaded first.

If this works add the PHP. I advise making the php portion simple like this. Replace the last line of the script block with this.

<?php
    if($_SESSION['whatever']=='whatever'){
        echo('$(document).ready(disableLinks);');
    }
?>

This could be done a bit cleaner, but this should get you going.

As a final note be sure to enforce this on the backend too as this is easily bypassed and if this is the only way you are preventing access it is not safe.

Upvotes: 0

Hardy
Hardy

Reputation: 5631

You are missing the ready function:

$(document).ready(function() {
  // put your code here.
});

Most of JQuery functions will not work before DOM is fully loaded.

Upvotes: 1

Related Questions