简体   繁体   中英

AJAX and PHP sending “HTTP get request” to the same page

My application gathers some client related information via JavaScript and submits it via AJAX to a php page.

See the code below:

index.php

<html>
<head>
    <script>
        function postClientData(){
            var client_data = new Array(screen.availHeight, screen.availWidth);
            var xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    if(this.responseText == client_data[0]){
                        document.getElementById("message").innerHTML = "Client data successfully submitted!";
                    }

                }
            };

            var parameters = "ajax.php?screen_height=" + client_data[0] + "&screen_width=" + client_data[1];
            xmlhttp.open("GET", parameters, true);
            xmlhttp.send();
        }
    </script>
</head>

<body onload="postClientData()">
    <span id="message"></span></p>
</body>

</html>

ajax.php

<?php
echo $_REQUEST["screen_height"];
//Does something else...
?>

I was wondering if I could merge the ajax.php content to my index.php and eliminate ajax.php. When I try adding the code, I probably get into a endless loop since I don't get my "success" message.

How can I solve this issue?

Correct, IMO I would definitely keep this specific logic separated in the ajax.php file.

If you do really want to merge, add it to the top of index.php (before printing data):

if (isset($_GET['screen_height'])) && isset($_GET['screen_width']) {
    // Execute specific logic and exit to prevent sending the HTML.
    exit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM