2

I have a index.php page with a link as follows:

<a id="link" href="test.php?id=1">Test</a>

I have a div container on same page as follows:

<div id="container" class="panel-body">

and ajax jQuery code on same page as follows:

<script type="text/javascript">
$("#link").click(function(){
    $.ajax({
    type: "get",
      url: "test.php",
      data: {'data':dataString}, 
      success: function(data){
           $('#container').html(data); 
      }
    });
}); 
</script>   

My job is to pass the above id=1 in the link to test.php and get value displayed in the same page in the div #container.

The issue is that clicking on link opens a new page in a new windows with url test.php?id=1 rather than displaying content of php on same page.

How can i display the result of test.php page on div named #container of same page in jquery???

Thanks in advance.

user3790186
  • 239
  • 6
  • 21
  • 1
    Possible duplicate of [jQuery disable a link](http://stackoverflow.com/questions/970388/jquery-disable-a-link) – Scimonster Mar 28 '16 at 13:04

2 Answers2

1

The issue is that clicking on link opens a new page in a new windows with url test.php?id=1 rather than displaying content of php on same page.

You need to stop the default behavior of anchor with event.preventDefault():

$("#link").click(function(e) {
  e.preventDefault(); // <-------stop the def behavior here.
  var id = this.href.split('=').pop(); // extract the id here
  $.ajax({
    type: "get",
    url: "test.php",
    data: {id:id}, // now pass it here
    success: function(data) {
      $('#container').html(data); //copy and paste for your special case
    }
  });
});
Jai
  • 74,255
  • 12
  • 74
  • 103
0

Just prevent a default behavior of the link:

$("#link").click(function(event){
    event.preventDefault();

    $.ajax({
    type: "get",
      url: "test.php",
      data: {'data':dataString}, 
      success: function(data){
           $('#container').html(data); //copy and paste for your special case
      }
    });
}); 
smnbbrv
  • 23,502
  • 9
  • 78
  • 109