简体   繁体   中英

Sending data from JavaScript to PHP via XMLHttpRequest

Good day.

I'm trying to send a simple piece of data from one php file (manage.php) to another (view.php).

I cannot send the data via a form, I want to send it via a JS script. Here's my attempt:

 var read = function(id) { xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", "view.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("id=" + id); } 

In view.php, using $_POST["id"] causes an error stating that the index "id" is undefined.

What's the correct way to send the data? Thank you.

Your input is not complete. So I did the full example below that you can follow. I made a function, named readid(id), doing the same thing as you want. Then I call that function from html, when needed.

<!doctype html>
<html lang="fr">
<head>
<meta charset="iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript" charset="iso-8859-1">
function readid(id){
"use strict";   
console.log("id=", id)
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/cgi-bin/view.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 || this.status === 200){ 
        console.log(this.responseText); // echo from php
    }       
};
xmlhttp.send("id=" + id);
}
</script>
</head>
<body>
<p>This is a test</p>
<input type="button" name="Submit" value="Submit" id="formsubmit" onClick="readid(id)">
</body>
</html>

view.php

<?php
$logFile = "view.log";
$id = $_POST['id'];
file_put_contents($logFile, $id);
echo $id;
?>
        <!DOCTYPE html>
    <html>
    <head>
      <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form id="formoid" title="" method="post">
            <div>
                <label class="title">First Name</label>
                <input type="text" id="name" name="name" >
            </div>
            <div>
                <label class="title">Name</label>
                <input type="text" id="name2" name="name2" >
            </div>
            <div>
                <input type="submit" id="submitButton"  name="submitButton" value="Submit">
            </div>
     </form>
    <script type='text/javascript'>
        /* attach a submit handler to the form */
        $("#formoid").submit(function(event) {

          /* stop form from submitting normally */
          event.preventDefault();

          $.ajax({
    type: 'POST',
    data: id,
    url: 'PATH_TO_VIEW.PHP',                        
    success: function(data) {
        //do something 
    },
    error: function(data){
        console.log('Something went wrong.');
    }
});
        });
    </script>

    </body>
    </html> 

Now the data in ajax can be collected numerous eg serialized and new FormData(form) to quickly name two.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM