Solució exercici2-ajax

De wikiserver
Dreceres ràpides: navegació, cerca

Fitxer js:

var xhr;

function ajax(){
    if (window.ActiveXObject) { //Iexplorer
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) { //Tots els altres navegadors que soporten ajax
            xhr = new XMLHttpRequest();
    }
    else {
            throw new Error("Ajax is not supported by this browser");
    }
    
    xhr.open('POST', 'http://172.16.105.107/ajax/majuscules.php');
    xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//Llamamos al método setRequestHeader indicando que los datos a enviarse están codificados como un formulario.
    xhr.onreadystatechange = function() {
	if (this.readyState == 4) {
		if (this.status >= 200 && this.status < 300) {
			document.getElementById('content').innerHTML = this.responseText;
		}
	}
    }

    var content = "nombre=" +document.getElementById("nom").value + "&apellido=" + document.getElementById("cognom").value;
    xhr.send(content);
    
    
}
function inici(){
   document.getElementById("boton").onclick = ajax; 
}
window.onload = inici;

Fitxer html:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript" src="exercici2.js"></script>
    </head>
    <body>
        <label>nom:</label><input type="text" id="nom" />
        <label>cognom:</label><input type="text" id="cognom" />
        <button id="boton">enviar</button>
        <div id="content">TODO write content</div>
    </body>
</html>

Fitxer php:

<?php
header("Access-Control-Allow-Origin: *");

if(isset($_POST["nombre"]) && isset($_POST["apellido"])){
    $nom = $_POST["nombre"];
    $cog = $_POST["apellido"];
    echo "<p><h2>Nom: ".strtoupper($nom)."</h2></p><h2>Cognom:". strtoupper($cog)."</h2>";
    exit;
}
echo "ERROR";

?>