0

I am learning JavaScript without jQuery.

Right now I am trying to pass some data from an input field to php and than pass a $variable from php to javascript. In jQuery this is easy with $.ajax.

But how do I do this with ONLY JavaScript? Here is my attempt. Right now I only want to pass the $_POST content from the inputfield. I didn't do any validation at this moment.

My plan is to make a validation with php and then pass an error message or more than one. Or in case of success an success message.

But out of my console log I am only getting NULL.

window.onload = function () {
    var Input = document.querySelector('input#Input');
    var InputButton = document.querySelector('button.formBtn');
    InputButton.onclick = function () {

        var InputRequest = new XMLHttpRequest();

        InputRequest.open("POST", "ajax.php", true);
        InputRequest.send();
        InputRequest.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                 var obj = JSON.parse(InputRequest.response)
                 console.log(obj);
            }
        }
        return false;
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Ajax Example</title>
    <style>
        #Input {
            width: 200px;
            height: 15px;
            padding: 10px 0;
            text-indent: 5px;
        }
        #Input:focus {
            outline: none;
            border: 1px solid lightblue;
        }
    </style>
</head>

<body>
    <form name="form" action="ajax.php" method="post">
        <input type="text" id="Input" name="inputTest">
        <button type="submit" class="formBtn">Absenden</button>
    </form>
    <script src="ajax.js"></script>
</body>

</html>

<?php
$inputResponse = $_POST["inputTest"];
echo json_encode($inputResponse)
?>

1 Answer 1

1

You are missing a line and need to modify your send() line for sending POST content:

// You need to send the type
InputRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the post values in the send
InputRequest.send('key=value&key2=value2');

In the case of the send() you have to turn the keys and values to a query string. I think this is why so many use jQuery, it's done all this for you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.