Van icon

AJAX PHP POST

Links


    //PHP Files-> Ajax4.html, Process.php
    WITH POST We cannot attach the parameter, we use: xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded';)
    xhr.send(params);
    
    <h2>AJAX POST FORM</h2>
    <form id="postForm">
        <input type="text" name="name" id="name2">
        <input type="submit" value="Submit">
    </form>


    //AJAX js
        document.getElementById('postForm').addEventListener('submit', getName2);

        function getName2(e){
            e.preventDefault();

            var name = document.getElementById('name2').value;
            var params = "name= "+name;

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'process.php', true); //With post we can't attach the parameter like with GET
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

            xhr.onload = function(){
                console.log(this.responseText);
            }
        xhr.send(params); //here we pass the params
        }


    //PHP
    
    echo 'Processing...';


    //Check for GET variable 
    if(isset($_POST['name'])){
        echo 'POST: Your name is '. $_POST['name']; 
    }
    if(isset($_GET['name'])){
        echo 'GET: Your name is '. $_GET['name']; 

    }