2

how can i send the post id on this URL inside my id variable, i needed for an ajax function This is the URL

https://barrera.pe/prueba/productos/barrera-3/?id=204

$(document).on('click','.more-link',function(e){
        e.preventDefault();
        link = $(this);
        id   = link.attr('href').replace(/^.*?id=/,''); 
        
        $.ajax({...
        ...
Always Helping
  • 14,316
  • 4
  • 13
  • 29
  • Does this answer your question? [How to parse a URL?](https://stackoverflow.com/questions/6168260/how-to-parse-a-url) – kmoser Sep 01 '20 at 02:42

2 Answers2

1

Simplest way to get the id is use URLSearchParams() and pass in the search property of the <a> element

$(document).on('click', '.more-link', function(e) {
  e.preventDefault();
  const params = new URLSearchParams(this.search)
  console.log('id=', params.get('id'))
  // do ajax

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="more-link" href="https://barrera.pe/prueba/productos/barrera-3/?id=204">Click me</a>
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

You can simply use new URL function and use searchparams with get to extract id from your href which will be in the a element and pass it your ajax request.

Live Working Demo:

$(document).on('click', '.more-link', function(e) {
  e.preventDefault();

  var url = new URL(this.href); //get href
  var id = url.searchParams.get("id"); //get-id

  console.log(id) //204
    
  //Ajax
  $.ajax({
    url: 'your_url',
    data: {id: id},
    success: function(response) {
       //handle success
    },
    error: function(xhr) {
      //handle error
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a class="more-link" href="https://barrera.pe/prueba/productos/barrera-3/?id=204">Click me</a>
Always Helping
  • 14,316
  • 4
  • 13
  • 29