Search code examples
ajaxrequestresponse

AJAX request response


I'm new with AJAX. I'm sending a request to start a PHP code on another page where couple of things need to happen. I have an algorithm on that page checking if all the things were done properly in right order. What I need is to return that boolean back to AJAX file, so that it would know that request was not only received, but finished in an intended way, so that I can add a success: function that would give a OK/NEY experience to the user.


Solution

  • Your folder:

    AnyFolderName
                 |--- index.php
                 |--- script.php
    

    Index.php:

    <!DOCTYPE html>
    <html>
    <head>
        <title>AJAX Request Sample</title>
        <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
        <script type="text/javascript">
            function submitform(){
                //get value of input whos id is username
                var username = $('input#username').val();
                //data to post to script.php
                var post = {username: username};
                $.ajax({
                    url: "script.php", //<-- PHP Script where you want to post your data
                    type: "POST",
                    data: post,
                    success: function(data){
                        //callback when request is finished.
                        //in our script.php, we just echoed the posted username, so it alerts whatever username you have input.
                        alert(data);
                    }
                });
            }
        </script>
    </head>
    <body>
        <form id="myForm">
             <input id="username" name="username">
        </form>
        <button onclick="submitform();"></button>
    </body>
    </html>
    

    script.php:

    <?php
         //print out the posted data you have passed from the AJAX request
         echo $_POST['username'];
    ?>