skip to Main Content

I am trying to make a get request using jQuery ajax, want to get the response on the same page. I tried this code…

   
    <p>This is a Ajax get request.</p>
    <button class='send'>click</button>
    <p id='pritam'></p>

    <?php
    if (isset($_GET['name'])) {
        echo $_GET['name'];
        exit;   
    }
    ?>

    <script>
    $(document).ready(function() {
        $(".send").click(function(){
            $.ajax({
                type: "GET",
                data: {name: 'praveen'},
                success: function(data) {
                    $("#pritam").html(data);
                }
            });
        });
    });
    </script>   
    

But I am getting an error, It executes all page element again when I click on the button including button tag.

2

Answers


  1. You should put your PHP section on top of this php file.


    EDIT:

    That’s because a PHP file executed from top to bottom. When the ajax request was processing, the contents above the PHP section will output first. That will cause the data response you got contains page html tags.

    Login or Signup to reply.
  2. You can do it like this

      <?php
        if (isset($_GET['name'])) {
            echo $_GET['name'];
            exit;   
        }
     ?>
    
     <p>This is a Ajax get request.</p>
        <button class='send'>click</button>
        <p id='pritam'></p>
    
        
    
        <script>
        $(document).ready(function() {
            $(".send").click(function(){
                $.ajax({
                    type: "GET",
                    data: {name: 'praveen'},
                    success: function(data) {
                        $("#pritam").html(data);
                    }
                });
            });
        });
        </script>  
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search