2

I want to be able to obtain the value of the variable view_data_id and store inside another variable called view_data_id_fk.

The last line of code doesn't seem to work on my end, so I'm wondering how I can go about doing it?

var view_data_id = val['view_data_id'];

// How to obtain the value of view_data_id?
<td><a href="datamapmain.php?view_data_id='+view_data_id+'" 
class="link">Link</a></td>

//Will be passed on to ajax file
view_data_id_fk:$('.link').val();
Vedran Maric
  • 855
  • 9
  • 21

2 Answers2

1

You can get the value using jQuery and attr(..) method (or just standard JavaScript) and regular expressions :

jQuery:

var q = $('.link').attr('href').match(new RegExp('[?&]view_data_id=([^&#]*)'));
var view_data_id_fk = q ? q[1] : '';

Standard JavaScript:

var q = document.querySelector('.link').href.match(new RegExp('[?&]view_data_id=([^&#]*)'));
var view_data_id_fk = q ? q[1] : '';

[Edited, thanks to Alexei Levenkov]

There is a standard way to do this, with URLSearchParams api, but it has limited browser support (caniuse, MDN):

var q = new URLSearchParams(document.querySelector('.link').href).get('view_data_id');
var view_data_id_fk = q || '';
Vedran Maric
  • 855
  • 9
  • 21
0

Create a reusable function as below

function getUrlParam(url,name){
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  var results = regex.exec(url);
  return results === null ? '' : 
                     decodeURIComponent(results[1]).replace(/\+/g,'');
}

Get the href attribute value using JQuery var url = $('.link').attr('href')

var view_data_id_fk = getUrlParam(url, 'view_data_id');