There is something wrong with my AJAX request

Viewed 53

I wrote the following code where i have bootstrap nav with two menu items and then i have some javascript code with ajax request:

 <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Test page</title>
    
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
        <body>
            <div class="container user-profile">
                <ul class="nav nav-tabs">
                    <li class="nav-item" id="p">
                        <a class="nav-link" href="#">Profile</a>
                    </li>
                    <li class="nav-item" id="edp">
                        <a class="nav-link" href="#">Edit profile</a>
                    </li>
                </ul>
    
                <span id="page_content"></span>
            </div>
        </body>
    </html>
    
    <script>
        $(document).ready(function(){
            function load_page_content(id) {
                $.ajax({
                    url: "fetch.php",
                    method: "POST",
                    data: {
                        id: id,
                    },
                    success: function(data) {
                        $('#page_content').html(data);
                    }
                })
            }
    
            $('.nav li').click(function(){
                var page_id = $(this).attr("id");
                load_page_content(page_id);
            })
        })
    </script>

There is my php code:

 <?php
        if ( isset($_POST["id"]) ) {
            echo '<h1>Some content</h1>';
        }
 ?>

I click on menu items and nothing happens. What's wrong with my code?

1 Answers

at first:

you shouldn't declare your function in .ready event statement

move function outside of .ready event and test your code

and at last:

you shouldn't declare your scripts outside of html tag when you wanna use .ready event so can you can declare your codes in tag but when you dont wanna use it, you should define they after declaring your html tags. now you use .ready event. so you should move your scripts into head tag

Related