Search code examples
jqueryajaxjquery-ajaxq

Pass link id to php page with ajax and opening in another div


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.


Solution

  • 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
        }
      });
    });