0

<script type="text/javascript">
  $(document).ready(function() {
    $('a').click(function(){
      $.get('data.php', {'page':$(this).attr("data")}, function(data){
        $('#content').html(data);
      });                         
    });
 });
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
<a href="#" data ="ajkdfk">apple</a>
<a href="#"data ="kasnfjk">pear</a>
<a href="#" data ="ankjlfs">banana</a>
<div id="content"></div>

I want to send value of data attribute of href tag to ajax function like "data=ajkdfk" and send to this value to data.

PHP page to update it to my database.

Naresh Kumar P
  • 4,127
  • 2
  • 16
  • 33
  • Possible duplicate of [jQuery Ajax POST example with PHP](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php) – Aman Sharma Mar 06 '17 at 18:13

2 Answers2

2

Only data attribute won't work. It should be data-* where you replace the * with the key you want to use.

And then retrieve the value by using the defined key,

HTML code would look something like this,

<a href="#" data-pagename ="ajkdfk">apple</a>
<a href="#"data-pagename ="kasnfjk">pear</a>
<a href="#" data-pagename ="ankjlfs">banana</a>
<div id="content"></div>

Along with following jQuery code,

<script type="text/javascript">
  $(document).ready(function() {
    $('a').click(function(){
      var pagenamevalue=$(this).data('pagename');
      $.get('data.php', {'page':pagenamevalue}, function(data){
        $('#content').html(data);
      });                         
    });
 });
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>

We've used jQuery's .data() function to access the value by data-key.

data-* attributes are used to store arbitrary data associated with the matched elements.

Alok Patel
  • 7,842
  • 5
  • 31
  • 47
1

Only data attribute WILL work, but you should use a data-key.

You should add

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>

before your document.ready [ I hope you are getting $ is not a function ].

It must be like —

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
      $(document).ready(function() {
        $('a').click(function(){
          var pagenamevalue=$(this).data('pagename');
          $.get('data.php', {'page':pagenamevalue}, function(data){
            $('#content').html(data);
          });                         
        });
     });
    </script>
kloik friend
  • 119
  • 5
  • I think it sends the "data-pagename" value to data.php page but I want to echo that value in the same page. and my PHP page code is $page = $_GET['pagename'];//$_GET['page'] should be apple or pear or banana if(isset($page)){ echo $page;} – Aman Sharma Oct 09 '16 at 07:14