1

I try to send POST data from html form to PHP script by using Ajax (XML httprequest ) with vanilla JavaScript then retrieve that data and display it to a specific html element.

the problem is when i click the button to submit the form , seems that the code in Ajax part does not send data to php script and at the same does not retrieve data to the specific html element.

//here is my php script I named it data.php

<?php
error_reporting(~E_NOTICE);
   if( $_POST["name"]) {
      echo "Welcome ". $_POST['name']. "<br />";      
      exit();
   }
?>

//and here is my html , JavaScript and ajax

<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>demo</title>
<style>
</style>
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="card">
<div class="card-body">
<form method="post" name="myForm" onsubmit="return validateForm();" action="data.php">
<div class="form-group">
<label for="exampleInputName1">Full name</label>
<input type="text" class="form-control" name="name" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter name">
</div>
<p class="text-center text-danger" id="loader">Load and display the value of name here with ajax</p>                     
<button type="submit" onclick="loadDoc()" class="btn btn-primary">Submit</button>
</form>
<script>
function validateForm(){
let validation = {
name:document.myForm.name.value
};                                              
let msg = new Array("Name required");
if(validation.name == null || validation.name == ""){
alert(msg);
return false;
    }
function loadDoc(){
xhttp = new XMLHttpRequest();
xhttp.open('POST','data.php',false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(validation.name);
document.getElementById("loader").innerHTML = xhttp.responseText;
        }
}                               
</script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
  • 1
    _"but my codes are not working like it was expected ."_ - so what is happening, and what did you expect to happen? – Tangentially Perpendicular Mar 11 '21 at 20:25
  • @tangentially-perpendicular read again the question , but simply i want to retrieve data from php script and display that data to html element with ajax and vanilla javascript, – Justin William Mar 11 '21 at 20:38
  • "not working" isn't a useful description of your problem. We understand what you want to do. What you aren't telling us properly is what's going wrong when you try to run the code. Provide some debugging information so we can narrow down the issue. We can't run your code and debug it, that's your job. Unless the the code contains very obvious mistakes then we can't tell you a solution without more details of the specific problem. – ADyson Mar 11 '21 at 20:40
  • However, from a brief read of the code I will point out that `xhttp.send(validation.name);` probably isn't right. This sends a value but doesn't attach a parameter name to it. You can debug this using your browser's network tool and/or by logging the POST variables in the PHP. Google some basic examples of sending post data using XmlHttpRequest – ADyson Mar 11 '21 at 20:42
  • @adyson i’ve edited the question – Justin William Mar 11 '21 at 21:09
  • Ok. Did you take note of my last comment and investigate it, and find examples of how you're supposed to do it? – ADyson Mar 11 '21 at 21:26
  • @ADyson yeah , i did but still i don’t understand how can i do it properly! can you pls give me an example according to my code ? – Justin William Mar 11 '21 at 21:30
  • In form-URL-encoded format, as a set of names and values. e.g. https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest . (You just had to type "xmlhttprequest send post data" into google and there are a zillion examples). – ADyson Mar 11 '21 at 21:47

1 Answers1

2

Edit: Since the OP asked, I have added a drop-in replacement for loadDoc() implemented using XMLHttpRequest. See below the main body of code.

XMLHttpRequest is an archaic way of doing things, and while it still has its place there are better methods now. See Fetch

It's also better to use addEventListener than in-line event handlers.

So, with that in mind I've rewritten your JavaScript as below.

Note: I've also closed all your unclosed <div>s and removed the unused libraries that you were loading.

Note also that just adding the required attribute to your <input> would achieve the same as the validation that you're doing.

<html lang="en-US">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>demo</title>
    <style>
    </style>
</head>
<body>
<div class="container">
    <div class="row justify-content-center">
        <div class="col-sm-6 col-md-6 col-lg-6">
            <div class="card">
                <div class="card-body">
                    <form method="post" name="myForm" action="data.php">
                        <div class="form-group">
                            <label for="exampleInputName1">Full name</label>
                            <input type="text" class="form-control" name="name" id="exampleInputName1" aria-describedby="nameHelp" placeholder="Enter name">
                        </div>
                        <p class="text-center text-danger" id="loader">Load and display the value of name here with ajax</p>
                        <button type="submit" class="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
        (function(){
            "use strict";
        function validateForm(e){
            e.preventDefault();

            // 'this' points to the form so no need to search for it
            if (!this.name.value) {
                alert("Name required");
            } else {
                loadDoc(this);
            }
        }
        function loadDoc(myForm){
            // Get the form data
            let formData = new FormData(myForm);
            fetch('data.php', {
                method:"POST",
                body: formData
            })
            .then(response =>{
                response.text()
                .then(txt => {
                    document.getElementById("loader").innerHTML = txt;

                })
            })
        }
        document.querySelector("form").addEventListener("submit", validateForm);
        })();
    </script>
 </body>
</html>

loadDoc() implemented with XMLHttpRequest:

   function loadDoc(myForm) {

        // Create the request object
        let xhr = new XMLHttpRequest();

        // monitor the ready state. We're looking for 4 - done. Ignore anything else
        xhr.onreadystatechange = function(){
            if (xhr.readyState === 4) {
                // Check the response status.
                if (xhr.status === 200) {
                    document.getElementById("loader").innerHTML = xhr.responseText;
                } else {
                    document.getElementById("loader").innerHTML = "Unexpected result: "+xhr.status;
                }
            }

        }
        xhr.open('POST', 'data.php');
        // set the mime type
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        // encode the data from the form and send it.
        xhr.send('name=' + encodeURIComponent(myForm.name.value));

    }
  • i’ve run the code and now it works , but how can we do the same thing with XMLHttpRequest? – Justin William Mar 12 '21 at 02:54
  • @JustinWilliam I've added an alternative version of loadDoc(). Realistically, you'd probably only use `XMLHttpRequest` if you need access to its event model (you're implementing a progress bar for file uploads, perhaps), or if you need to support old browsers like Internet Explorer – Tangentially Perpendicular Mar 12 '21 at 21:48
  • @ Tangentially Perpendicular the alternative version of loadDoc() by using XMLHttpRequest is not working – Justin William Apr 04 '21 at 08:41
  • @JustinWilliam I ran the same code I posted here on my development system without a hitch. _"is not working"_ is not useful as a problem description. Clearly, you've done something wrong. You'll need to provide more information about what is actually happening if you want anyone to help you debug it. – Tangentially Perpendicular Apr 04 '21 at 10:23