-3

I have a jQuery function, which, on click, itercepts a clicked link:

$("a").click(function(e) {
    e.preventDefault();
    var link = $(this).prop('href'); 
    alert(link);
});

and it works properly, but how to pass that link to a PHP variable to 'echo' it later?

I unsuccessfully tried:

$("a").click(function(event) {
    event.preventDefault();
    var link = $(this).prop('href'); 
    <?php $link = .'link'. ?> 
});

I know it may be a silly question, I looked all over the web but I didn't find any proper answer.

Daniel
  • 538
  • 1
  • 8
  • 21

2 Answers2

0

The only way to do this is to have a script wich stores values passed to it in a session or to a DB and either output the session data later or read from the db

$("a").click(function(event) {
    event.preventDefault();
    var link = $(this).prop('href'); 
    $.post('saveLink.php', {href : link}); 
});

the saveLink.php would be something like this

<?php
   // Clean your POST variable, always clean any POST variables
   // see here for a good discussion on that
   // http://stackoverflow.com/questions/4223980/the-ultimate-clean-secure-function
   $link = htmlspecialchars($_POST['href']);

   $_SESSION['links'] = $link;
?>

then later on you can retrieve all you session data

Note

Session data is not permanent and not shareable between users so if you need to do that you would be better off with a db query also if you need to access a particular link then you will need to send some sort of id with it.

dops
  • 800
  • 9
  • 17
0

PHP is preprocessor running on a server side. jQuery is running on client side (in user's browser) and it can't comunicate with PHP like this.

Although you can send the data to PHP with Ajax request and process them in another php script, for example store them in a database.

$.ajax({
    url: '/ajax_catch.php',
    type:'POST',
    data: {
        link: link
    },
    success: function(m){
      //what to do after its done
    }                   
});     
Ko Cour
  • 929
  • 2
  • 18
  • 29