Johnny
Johnny

Reputation: 39

HTML TAG <A> pass variable both with href and onclick

I want when someone clicks this link to go first on myfunction that I have in JS and after that follow the href function that exists in <a> tag. The problem is that it follows first the href and I can't pass the variable I want from the js function.

here is my code:

PHP

echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction();">
        <div class="icon-lock">
            <img  src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
        </div>';
echo '</a>';

JS

<script>
function myFunction() {
$.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php"
        });
 }
</script>

I am very confused on how href and myfunction will work in order to print

$id=$_POST['id'];
echo $id;

in php after the page has been reloaded...
Any thoughts?

Upvotes: 1

Views: 3004

Answers (3)

Sushanth --
Sushanth --

Reputation: 55740

Prevent the default action in your myfunction method which takes the event object. And then in the success call back of your ajax request, do what ever you wanna do .

<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(e);">

function myFunction(e) {
   e.preventDefault();
   $.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php"
   }).done(function() {
        // What ever following the link does
   });
}

Upvotes: 0

Muhammad Waqas
Muhammad Waqas

Reputation: 1150

you do simply pass this on your function

your php code will look like this

 echo '<a href="category.php?id=' . $_SESSION['id'] . '" onclick="myFunction(this);">/*pass this keyword to function */
            <div class="icon-lock">
                <img  src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
            </div>';
    echo '</a>';

function myFunction(str) {
   $.ajax({
        type: "POST",
        url: str.getAttribute("href")
   }).done(function() {
        // What ever following the link does
            window.location.href=str.getAttribute("href")

   });
}

Upvotes: 1

David
David

Reputation: 439

You could pass the 'id' as a parameter in your function and use javascript to change the window location after the ajax is successful.

HTML

<div class="icon-lock">
    <img onclick="myFunction(<?=$_SESSION['id']?>)" src="/test/images/lock.png" alt="Locked Button" width="35" height="35" border="0">
</div>

Javascript

function myFunction(id) {
    $.ajax({
        type: "POST",
        data: {id: "1"},
        url: "category.php",
        success: function() {
            window.location.assign("category.php?id="+id);
        }
    });
}

Upvotes: 1

Related Questions