Despues de mucho tiempo sin postear nada hoy vengo para postear un pequeño articulo de como usar Ajax con PHP. Como ya sabran la gran mayoria Ajax es la tecnica que se utiliza para hacer peticiones al servidor sin tener que recargar la pagina que hace la peticion al servidor.
Lo que tratare de explicar es el proceso de Login los datos seran introducidos en un formulario HTML
Bueno ahora tratare de explicar un poco como realizar esta acciones
- Lo primero que haremos es crear un archvio JavaScript que se llamara ajax.js
- Una ves creado este archivo agregaremos el siguiete codigo
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObkect()
{
var Http;
try
{
//Objeto para las llamadas asicronas al servidor
Http = new XMLHttpRequest();
}
catch(e)
{
//es intermet explorer6 o anterior
var XmlHttpVersions = new Array(“MSXML2.XMLHTTP.6.0″,
“MSXML2.XMLHTTP.5.0″,
“MSXML2.XMLHTTP.4.0″,
“MSXML2.XMLHTTP.3.0″,
“MSXML2.XMLHTTP”,
“Microsoft.XMLHTTP”);
for(var i=0; i<XmlHttpVesions.length && !xmlHttp;i++)
{
try
{
Http = new ActiveXObject(XmlHttpVersions[i]);
}
catch(e){}
}
}
if(!Http)
alert(“Error al crear el objeto XMLHttpRequest.”);
else
return Http;
}
Despues crearemos un archivo que se llamara proceso.js
function processLogin()
{
var user = document.getElementById(“usr”).value;
var pwd = document.getElementById(“pwd”).value;
if(user == “” || pwd == “”)
{
alert(“No deje campos vacios”);
return;
}
//only continue if xmlHttp isn’t void
if (xmlHttp)
{
try
{
var usr = document.getElementById(“usr”).value;
var pwd = document.getElementById(“pwd”).value;
var params = “usr=”+usr+”&pwd=”+pwd;
xmlHttp.open(“GET”,”login.php?”+params,true);
xmlHttp.onreadystatechange = handleRequestStateChangeLogin;
xmlHttp.send(null);
}
//display the error in case of failure
catch(e)
{
alert(“Can’t connect to server:\n”+e.toString());
}
}
}
function handleRequestStateChangeLogin()
{
//when readyState is 4, we are ready to read the server response
if(xmlHttp.readyState == 4)
{
//continue only if HTTP status is OK
if(xmlHttp.status == 200)
{
try
{
//do something with the response from server
handleServerResponseLogin();
}
catch(e)
{
//display error message
alert(“Error reading the response: “+e.toString());
}
}
else
{
//display status message
alert(“There was a problem retrivering the data:\n”+xmlHttp.statusText);
}
}
}
function handleServerResponseLogin()
{
// retrieve the server’s response packaged as an XML DOM object
var xmlResponse = xmlHttp.responseXML;
// catching potential errors with IE and Opera
if (!xmlResponse || !xmlResponse.documentElement)
throw(“Invalid XML structure:\n” + xmlHttp.responseText);
// catching potential errors with Firefox
var rootNodeName = xmlResponse.documentElement.nodeName;
if (rootNodeName == “parsererror”)
throw(“Invalid XML structure:\n” + xmlHttp.responseText);
// getting the root element (the document element)
xmlRoot = xmlResponse.documentElement;
// testing that we received the XML document we expect
if (rootNodeName != “response” || !xmlRoot.firstChild)
throw(“Invalid XML structure:\n” + xmlHttp.responseText);
// the value we need to display is the child of the root <response>
responseText = xmlRoot.firstChild.data;
// display the user message
if(responseText==”true”)
{
alert(“Usuario Correcto.”);
location.href=”index.html”;
}
else
alert(“Nombre de usuario y/o Password incorrectos.\nVuelva a intentarlo”);
}
Despues creamos el archivo PHP la cual hara la consulta a la base de datos para validar el usuario y password introducio por el usuario
<?php
require(“conexion.php”);
header(‘Content-Type: text/xml’); //Establecemos que php regrasara un documento XML
$usr = $_GET['usr']; //obteemos el usuario introducio por el usuario en la pagina HTML
$pwd = $_GET['pwd'];//obteemos el pass introducio por el usuario en la pagina HTML
$query = “SELECT COUNT(*) FROM usuarios WHERE usuario=’$usr’ AND password=’$pwd’”;
$resQuery = mysql_query($query, $conexion);
$count = mysql_fetch_array($resQuery);
//echo $count[0];
$result;
if($count[0] == 0)
{
$result = “false”;
}
else
{
//Autenticacion del usuario correcta
$result = “true”;
}
$dom = new DOMDocument();
// create the root <response> element and add it to the document
$response = $dom->createElement(‘response’);
$dom->appendChild($response);
// add the calculated sqrt value as a text node child of <response>
$responseText = $dom->createTextNode($result);
$response->appendChild($responseText);
// build the XML structure in a string variable
$xmlString = $dom->saveXML();
// output the XML string
echo $xmlString;
?>
Y por ultimo creamos la pagina HTML que hara la llamada
<table align=”center”>
<tr >
<td >Usuario:</td>
<td ><input type=”text” id=”usr” width=”180″/>
</tr>
<tr >
<td>Password:</td>
<td ><input type=”password” id=”pwd” width=”180″/></td>
</tr>
<tr >
<td></td>
<td align=”right”><input type=”button” value=”Iniciar Sesion” onclick=”processLogin()”/></td>
</tr>
</table>
Escrito por skorer87
Escrito por skorer87
Escrito por skorer87 









