Home > Software engineering >  How to get information from link with ajax
How to get information from link with ajax

Time:12-20

I searched a lot but I couldn't find a solution can you help me

<ul >
  <li >
    <a  id="click" href="#" data="new">New product</a>
  </li>
  <li >
    <a  href="#" id="click" data="sale">Sale product</a>
  </li>
  <li >
    <a  href="#" id="click" data="trent">Trend product</a>
  </li>
</ul>
<div ></div>
  1. I want to pass data="new" , data="sale" and data="trend" information between <li> tags with ajax on every click.
  2. I want data new to be active when it is not clicked.

I tried a few times, but I was unsuccessful:

$(document).ready(function() {
  $('.nav-link').click(function() {
    var datas = $(this) attr("data");
  });
  $.ajax({
    url: 'indextab.php',
    type: 'POST',
    data: { datas: datas },
    success: function(datal) {
      $('.tabspane').html("").html(datal);
      alert(datas);
    }
  });
});

Please help on this issue.

CodePudding user response:

Your datas variable is out of scope for the ajax call. You are instanciating the variable on the click of the nav link, but the ajax call is running when the DOM is ready.

The following should give you what you want:

$(document).ready(function() {
  $('.nav-link').click(function() {
    var datas = $(this) attr("data");
    $.ajax({
      url: 'indextab.php',
      type: 'POST',
      data: { datas: datas },
      success: function(datal) {
        $('.tabspane').html("").html(datal);
        alert(datas);
      }
    });
  });
});

CodePudding user response:

    $(document).ready(function() {
  $('.nav-link').click(function() {
    var datas = $(this) attr("data");
    $.ajax({
      url: 'indextab.php',
      type: 'POST',
      data: { datas: datas },
      success: function(datal) {
        $('.tabspane').html("").html(datal);
        alert(datas);
      }
    });
  });
});

yes, that's it, thanks, but when it's not clicked, I want the new data to be retrieved

  • Related