Buenos días.
Estoy tratando de enviar un dato simple de un archivo php (manage.php) a otro (view.php).
No puedo enviar los datos a través de un formulario, quiero enviarlos a través de un script JS. Aquí está mi intento:
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); }En view.php, el uso de $_POST["id"] provoca un error que indica que el índice "id" no está definido.
¿Cuál es la forma correcta de enviar los datos? Gracias.
Su entrada no está completa. Así que hice el ejemplo completo a continuación que puedes seguir. Hice una función, llamada readid(id), haciendo lo mismo que tú quieres. Luego llamo a esa función desde html, cuando sea necesario.
<!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>ver.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>Ahora los datos en ajax se pueden recopilar numerosos, por ejemplo, serializados y nuevos FormData (formulario) para nombrar rápidamente dos.