user3387522
user3387522

Reputation: 127

Running a javascript function on a <a href>

I was just wondering how to trigger a JavaScript function on a <a> like this:

$('a').click( function() { your_code_here; return false; } );

and then using this to run a JavaScript function that runs something like this:

$.post("queries.php")

that runs a PHP function that runs a SQL query like this:

public function GetResults()
{ 
    list($subjectID, $sectionID, $principleID) = explode('#', $_POST["comboboxselections"]);
    $box = ""; // placeholder for the html results to be returned to 
    $sql = "SELECT media_id,title,blurb 
            FROM media 
            WHERE subject_id = $subjectID AND section_id = $sectionID AND principle_id= $principleID AND verified = 1"; 
    try
    {
        return $this->getResultsAndGenerateHTML($sql, $this->conn);
    }catch(exception $e)
    {
        echo 'Caught exception: ',  $e->getMessage(), "\n";

    }
}
  1. Would this be the best option to run a SQL query from a HTML <a> or is there a better way of doing this?

  2. I already know about MySQLi and PDO this project is not going live so I do not need to worry about SQL injection.

  3. It has to be done on a HTML <a>. I know I could use a button which would be easier, but with my specification, it uses a <a> .

Upvotes: 0

Views: 86

Answers (3)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can call it from anything you want, but an anchor tag is preferred since if the user doesn't have JavaScript activated, you will have a fallback and can redirect the user to an other page. Just be sure to prevent the default behaviour.

return false is not recommended for for that since it also prevent the event from bubbling. You should use event.preventDefault().

Upvotes: 1

Abhinav
Abhinav

Reputation: 8168

e.preventDefault(); 

prevents the default action of clicking he link and allows us to do our stuff.

$("a").click(function(e){

e.preventDefault();

//Do ur stuff

});

Visit this link:

http://api.jquery.com/event.preventdefault/

They have beautifully explained its functionality with examples

Upvotes: 2

Behzad Hassani
Behzad Hassani

Reputation: 2139

This way you have written includes all of your a tag, and if you have hyperlink in your menus your menus will do thus function too, at first give an id to your hyperlink

<a href="#" id="Something">Click On Me</a>

then use this in jquery:

$("#Something").click(function(e){
     e.preventDefault();
     //write your function here
});

this prevents page changing and will do your function.

Upvotes: 2

Related Questions