Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX POST to PHP without JQuery

I had a PHP assignment that I decided that I wanted to try and add AJAX to because in our class we will not learn AJAX just PHP. I can't seem to get the response to work. However in the network section of my console on Fire Fox I can find the POST send with the values I entered into the form and the PHP echo as a result from the php function working. But, it will not show up in my div tag. Any help would be most welcome, thanks.

Here is the HTML and JavaScript:

<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">
        function testPass() {
            var username = document.getElementById("uname").value;
            var passwrd = document.getElementById("passwd").value;
            var creds = "uname="+username+"&passwd="+passwrd;
            var ajx = new XMLHttpRequest();
            ajx.onreadystatechagne = function () {
                if (ajx.readyState == 4 && ajx.status == 200) {
                    document.getElementById("message").innerHTML = ajx.responseText;
                }
            };
            ajx.open("POST", "authenticate.php", true);
            ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            ajx.send(creds);
            //document.getElementById("message").innerHTML = creds;
        }
    </script>
</head>
<body>
    <p>
        <form id="login">
            <strong>Login</strong><br/><br/>
            Username :<br/><input type="text" id="uname"><br/>
            Password :<br/><input type="text" id="passwd"><br/><br/>
            <div id="message" style="color:red;"></div>
            <br/><button type="button" value="Submit" onclick="testPass();">Sign In</button>
        </form>
    </p>
</body>
</html>

And here is the PHP:

<?php
$uname = $_POST['uname'];
$passwd = $_POST['passwd'];

if (empty($uname) && empty($passwd)) {
    echo "The username and password are required!";
} else if (empty($uname)) {
    echo "The username is required!";
} else if (empty($passwd)) {
    echo "The password is required!";
} else {
    echo "It works!";
} ?>
like image 586
user5931457 Avatar asked Sep 25 '22 09:09

user5931457


1 Answers

Try to use functions as much as possible to make code reusable and easier to troubleshoot. I suggest the following code.

<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript">

        function createAjaxRequestObject() {
            var xmlhttp;

            if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else { // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }

            // Create the object
            return xmlhttp;
        }

        function AjaxPost(ajaxURL, parameters, onComplete) {
            var http3 = createAjaxRequestObject();

            http3.onreadystatechange = function() {
                if(http3.readyState == 4) {
                    if(http3.status == 200) {
                        if(onComplete) {
                            onComplete(http3.responseText);
                        }
                    }
                }
            };

            // Create parameter string
            var parameterString = "";
            var isFirst = true;
            for(var index in parameters) {
                if(!isFirst) {
                    parameterString += "&";
                } 
                parameterString += encodeURIComponent(index) + "=" + encodeURIComponent(parameters[index]);
                isFirst = false;
            }

            // Make request
            http3.open("POST", ajaxURL, true);
            http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            http3.send(parameterString);
        }

        function completedAJAX(response) {
            alert(response);
        }

        function testPass() {
            var parameters = {
              "uname" : document.getElementById("uname").value,
              "passwd" : document.getElementById("passwd").value
            };

            AjaxPost("authenticate.php", parameters, completedAJAX);
        }
    </script>
</head>
<body>
    <p>
        <form id="login">
            <strong>Login</strong><br/><br/>
            Username :<br/><input type="text" name="uname" id="uname" /><br/>
            Password :<br/><input type="password" name="passwd" id="passwd" /><br/><br/>
            <div id="message" style="color:red;"></div>
            <br/><button type="button" value="Submit" onclick="testPass();">Sign In</button>
        </form>
    </p>
</body>
</html>

Another tip is to use Firebug if you are using Firefox or the developers tools in Chrome (Press CTRL + SHIFT + J) when testing some scripts. This error would have popped up in the console and you would immediately noticed the mistake.

like image 121
Gilles Lesire Avatar answered Oct 11 '22 16:10

Gilles Lesire