Benjamin Oats Benjamin Oats - 3 months ago 10
jQuery Question

inject last part of URL dynamically and uniquely using javascript or php

I am trying to work out how to get thye last part of a url on click of a button dynamically from a pre populated csv file.

For example on click of

<a href="mysite.com/" >button</a>

would grab a code from a CSV file (or something better) and the link would be
mysite.com/code1.


However each code from the CSV will only be used once and be removed after

So first click =
mysite.com/code1


Second click =
mysite.com/code2


and so on getting
code1
and
code2
from the CSV file and never to be gotten again.

I can use either JavaScript or PHP, either is good, I'm just not sure on the syntax.

Answer

Like this:

<?php
 $first = true;
 $links = "";
 $file = fopen('myCSVFile.csv', 'r');
 while (($line = fgetcsv($file)) !== FALSE) {
   if (!$first) $links.=",";
   $first=false;
   //$line is an array of the csv elements
   $links.='"'.$line.'"';
 }
 fclose($file);
?>

Plain JS

<script>
var links = [<?php echo $links ?>];
cnt = 0;
window.onload=function() {
  document.getElementById("csvLink").onclick=function() {
    window.open(this.href+links[cnt],"_blank"); // otherwise you need cookies
    return false;
    cnt++; 
  }
}
</script>

jQuery using Ajax:

<script>
var links = [<?php echo $links ?>];
cnt = 0;
$(function() {
  $("#csvLink").on("click",function(e) {
    e.preventDefault();
    $("#someContainer").load(this.href+links[cnt]);
    cnt++; 
  });
});
</script>