Ver Mensaje Individual
  #1 (permalink)  
Antiguo 20/11/2010, 16:10
Avatar de tomymolina
tomymolina
 
Fecha de Ingreso: noviembre-2010
Mensajes: 50
Antigüedad: 13 años, 6 meses
Puntos: 1
Enviar formulario por ajax utilizando include con php y ajax

Hola a todos ya postee un tema para un include dinamico con ajax y php y un usuario me ayudo y lo consegui ahora el problema que se me plantea es el siguiente: (antes de nada debo decir que no domino ajax)

Yo quiero enviar un formulario sin refrescar la pagina, he mirado por internet y he visto varios ejemplos para enviar un formulario con ajax muy faciles que funcionan correctamente en un archivo.html o archivo.php?var=1 pero el problema es cuando estoy en una pagina.php#var=1&go=algo.

Os dejo el code que tengo que funciona en documentos normales (sin ser include con ajax #) y os pregunto si es posible enviar el formulario sin recargar la pagina (con ajax jquery o lo que sea) en mi caso del include con # ?

index.php (el archivo ajax para el include):

Código PHP:
<?php 
include ("files/functions/p_style.php");
include(
'files/news/db-cnx.php');
include(
"files/news/PHPcake.lib.php");
include (
"files/settings/index.php");
include (
"files/news/PHPBBcode.lib.php");
;
?>
<?php  

if(isset($_GET['q'])){ 
    
parse_str($_GET['q'],$output); 


/* Para saber si ai varias variables en la url */    
if (count($output) == 1){
    
$next '';

elseif (
count($output) == 2){
   
$next '&go='.$output["go"] ;
    

elseif (
count($output) == 3){
   
$next '&go='.$output["go"].'&id='.$output["id"] ;

}
elseif (
count($output) == 4){
   
$next '&go='.$output["go"].'&category='.$output["category"].'&id='.$output["id"] ;

}


    
    switch(
$_GET['q']){
        case 
'action=contacto':
        include (
"files/contacto/index.php");
        break;
        
        case 
'action=login:
        include ("files/micarpeta/login.php");
        break;
        
        case '
action=posts'.$next:
        include ("files/news/PHPNews/index.php");
        break;
        
        case '
action=user'.$next:
        include ("files/user/index.php");
        break;        



        default:
        echo '
contenido por defecto';
    }

    exit; 

?> 





<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>ejemplo</title> 
<style type="text/css"> 
.menu{ width:50px; line-height:20px; font-family:Verdana, Geneva, sans-serif; font-size:10px; background:#F93; cursor:pointer; text-align:center; float:left; margin-right:5px;} 
#pp{ clear:both; margin-top:20px;} 
</style> 
<script type="text/javascript"> 
function http(){ 
    if(typeof window.XMLHttpRequest!='
undefined'){ 
        return new XMLHttpRequest();     
    }else{ 
        try{ 
            return new ActiveXObject('
Microsoft.XMLHTTP'); 
        }catch(e){ 
            alert('
Su navegador no soporta AJAX'); 
            return false; 
        }     
    }     

function request(url,callback,params){ 
    ns.p=params.q; 
    params.q=params.q.split('
#').join('') 
    
var H=new http(); 
    if(!
H)return; 
    var 
p=''
    for(var 
i in params){ 
        
p+='&'+i+'='+escape(params[i]);     
    } 
    
H.open('get',url+'?'+p+'&'+Math.random(),true); 
    
H.onreadystatechange=function(){ 
        if(
H.readyState==4){ 
            
callback(H.responseText); 
            
H.onreadystatechange=function(){} 
            
H.abort(); 
            
H=null
        } 
    } 
    
H.send(null); 

var 
ns={} 
ns.p=-1
onload=function(){ 
        
setInterval(function(){if(location.hash!=ns.p){request('<?php echo basename($_SERVER['PHP_SELF']) ?>',function(r){document.getElementById('pp').innerHTML=r;},{'q':location.hash});};},100); 

</script> 
</head> 

<body> 
<div onclick="location.hash='action=desing'" class="menu">desing</div> 
<div onclick="location.hash='action=contacto'" class="menu">contacto</div> 
<div onclick="location.hash='action=posts&go=view&id=17'" class="menu">c</div> 
<div onclick="location.hash='action=posts&go=view&id=18'" class="menu">d</div> 

<div id="pp"></div> 

</body> 
</html>
el login.php:

Código HTML:
<?php 
//en este ejemplo lo enviamos a la misma página
if(isset($_POST['Submit']) && !empty($_POST['Submit'])){
echo '<pre>';
print_r($_POST);
echo '</pre>';
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>test</title>
<script>
//acá cada uno crea el objeto a su manera
function aj(){
    if(window.XMLHttpRequest){
        return new XMLHttpRequest();
    }
    else{
        try{
            return new ActiveXObject('Microsoft.XMLHTTP');
        }catch(e){
            alert('tu navegador no soporta ajax');
            return false;
        }
    }
}
function sendAndLoad(){
    var rpc=aj();
    if(rpc){
        //si pudo crearse el objeto, avanzamos (respetar el orden)
        rpc.open('POST','<?php echo basename($_SERVER['PHP_SELF']) ?>',true);
        rpc.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        //preparamos las variables a enviar
        var aEnviar='';

        for(ii=0; ii<arguments.length;ii++){
//usamos el objeto arguments para obtener y parsear los datos a enviar
//encodeURI es semejante a urlencode de PHP
            aEnviar+=arguments[ii].desc+'='+encodeURI(arguments[ii].dato)+'&';
        }
        //creamos una función anónima que sirva de handler
        rpc.onreadystatechange=function(){
            if(rpc.readyState==4){
                //nos conectamos, recibimos y hacemos algo con lo que recibimos si queremos
                //en este caso, mostramos lo que enviamos
                document.getElementById('pp').style.display='block';
                document.getElementById('pp').style.color='green';
                document.getElementById('pp').innerHTML=rpc.responseText;
            }else{
                //no nos conectamos todavía y mostramos la precarga
                document.getElementById('pp').style.display='block';
            }
        }
//Recién ahora, que tenemos todo lo anterior terminado, podemos enviar el request
        rpc.send(aEnviar);
    }
}
//asignamos la función al botón de envío al cargar la página, así no tocamos el html
window.onload=function(){
    document.getElementById('Submit').onclick=function(){
        //pasamos objetos escritos en notación json como argumentos
sendAndLoad({desc:'uno',dato:document.getElementById('uno').value},{desc:'dos',dato:document.getElementById('dos').value},{desc:'tres',dato:(document.getElementById('tres').checked)?document.getElementById('tres').value:'no'},{desc:'Submit',dato:document.getElementById('Submit').value});
    }
}
</script>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <input name="uno" type="text" id="uno" />
  <input name="dos" type="text" id="dos" />
  <input name="tres" type="checkbox" id="tres" value="si" checked="checked" />
  <input type="button" id="Submit" name="Submit" value="Enviar" />
</form><div id="pp" style="display:none;color:#F00">Cargando...</div>
</body>
</html>