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?
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")
});
}
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);
}
});
}
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
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.