How to submit form data using ajax with pure javascript(Post Method) ?

How to submit form data using ajax with pure javascript(Post Method)?



Code -: 

  • index.html
    • <html>
    • <head>
    • <title>

    • Ajax PART- 2
    • </title>
    • </head>
    • <body>
    • <form onsubmit="return myfunction()" >
    • <input id="name" placeholder="Enter your name" required/> <br/><br/>
    • <input id="age" placeholder="Enter your age" required/><br/><br/>
    • <input type="submit" value="submit"/>
    • </form>
    • <div id="di">
    • </div>
    • <script>
    • function myfunction() {
    • const obj = new XMLHttpRequest();
    • obj.onreadystatechange = function () {
    • if(obj.readyState == 4) {
    • if(obj.status == 200) {
    • let rs = obj.responseText;
    • document.getElementById('di').innerHTML = rs;
    • }
    • }
    • }
    • let name = document.getElementById('name').value;
    • let age = document.getElementById('age').value;
    • console.log(name + age);
    • obj.open('POST', 'insert.php', true); //true => wW
    • obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    • obj.send('name='+name+'&age='+age);
    • return false;
    • }
    • </script>
    • </body>
    • </html>
    •  
  • insert.php
    • <?php

    • $name = $_REQUEST['name'];
    • $age = $_REQUEST['age'];

    • $con = mysqli_connect('localhost', 'root', '', 'testing');

    • $q = "INSERT INTO `ajax`(`name`, `age`) VALUES ('$name', '$age')";

    • $r = mysqli_query($con, $q);

    • if($r)
    • echo "data inserted!..";

    • else
    • echo 'error!..';

    • ?>

Github Link -: https://github.com/Master-Tech271/Ajax--2

No comments