Foros del Web » Programando para Internet » Javascript »

problemas con menu ajax y boton volver

Estas en el tema de problemas con menu ajax y boton volver en el foro de Javascript en Foros del Web. Hola gente, tengo el siguiente problema. Tengo una pagina con dos div, en uno de ellos tengo un menu y en el otro, muestro con ...
  #1 (permalink)  
Antiguo 09/04/2012, 15:38
 
Fecha de Ingreso: septiembre-2010
Mensajes: 74
Antigüedad: 13 años, 7 meses
Puntos: 1
problemas con menu ajax y boton volver

Hola gente, tengo el siguiente problema. Tengo una pagina con dos div, en uno de ellos tengo un menu y en el otro, muestro con ajax la pagina correspondiente al linck que clickee en el menu. El problema es que nose como hacer para que luego de borrar un producto redireccione automaticamente a la pagina anterior en el div contenedor y no el index.

Pego el codigo.

Este es el index donde tengo el menu y el div contenedor:

Código HTML:
<html>
    <head>
        <link rel="stylesheet" type="text/css" media="screen" href="css.css" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<style media="all" type="text/css">@import "css.css";</style>
<script type="text/javascript">

function getPages(divid,url)
{

 if(divid !="" && url != "")
 {
	var ob= AjaxObject();
	var unixTimeStamp= fetch_unix_timestamp();
	var nocacheurl = url+ "?t=" + unixTimeStamp;

	ob.onreadystatechange=function()
	{
      if(ob.readyState==4)
       {
		   if(ob.status == 200)
		   {
			   if(ob.responseText != null)
			   {
				   document.getElementById(divid).innerHTML=ob.responseText;
			   }else
			     {
					 alert('There was an error: no data was received');
				 }
		   }else
		     {
			   alert('Ajax error:' + ob.statusText);
		     }
		}
    }
    ob.open("GET",nocacheurl,true);
    ob.send(null);
	}else{
    alert('Se te a olvidado colocar el id del DIV o el URL en el href  del achor tag, en el evento de onClick ');
	}
}

function fetch_unix_timestamp()
{
    return parseInt(new Date().getTime().toString().substring(0, 10))
}

function AjaxObject()
{
var xmlHttp;
  try{
   return xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
    }
     catch (e){
     try{
      return xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
       }
       catch (e){
       try{
        return xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
       catch (e){
     alert("Sorry AJAX is not supported by your browser.");
    return false;
  }
 }
}
}
</script>

</head>
<body>
    <div class="principal" style="background-color: #e0e0e0;">
    
        
    
    
    <div id="menu" class="menu">
            <ul>
            <li><a id="current" href="stock.php" onClick="getPages('response',this); return false" >HOME</a>
            </li>
            <li><a href="borrar.php" onClick="getPages('response',this); return false" >Borrar</a>
            </li>
            
            </ul>
               
        
       </div>

       
       
         
        <table cellpadding="0" cellspacing="0" style="margin-top: 20px" >
            <tr>
                <td>
                    <div id="response" style="height: 500px">
                        <?php include ("stock.php"); ?>
                        

                    </div>
                </td>
            </tr>
        </table>
    
    </div>
 </body> 
 </html> 
Esta es la pagina borrar en la cual selecciono los productos que deseo borrar

Código HTML:
<?php
include_once 'lib.php';


$conexion= mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($database, $conexion);
$result = mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'", $conexion);
?>
<form name='borrar' method='post' action='borrar_prod.php'>
    <table id="etiquetas" border='1'>
<tr style="background-color: #ffff99">
    <th>ID</th>
    <th>Codigo</th>
    <th style='width: 500px'>Descrip</th>
    <th>Prec.Min</th>
    <th>Prec.May</th>
    <th>Disponibles</th>
    <th></th>
</tr>
<?php
$i=0;
while($row = mysql_fetch_array($result)){
?>
    <tr>
        <td><?php echo $row['id_stock'] ?></td>
        <td><?php echo $row['codigo'] ?></td>
        <td style='width: 500px'><?php echo $row['descrip'] ?></td>
        <td align=right><?php echo "$"; echo $row['pre_min'] ?></td>
        <td align=right><?php echo "$"; echo $row['pre_may'] ?></td>
        <td align=center><?php echo $row['disponibles'] ?></td>
        <td><input name='seleccion[]' type='checkbox' value=<?php echo $row['id_stock']?>></td>
     </tr>
<?php     
    $i++;
}
?>
</table>
<br>
<input type='submit' name='submit' value='enviar'>
</form> 
Y esta es la pagina donde borro y como ven en la parte inferior tengo un header que apunta al index y como explique arriba quiero que vuelva a cargar la pagina borrar (osea la anterior) denuevo en el contenedor

Código PHP:
<?php

require_once 'lib.php';
     foreach (
$_POST['seleccion'] as $id){ 
   echo 
$id."<br>"
}  
$conexionmysql_connect($dbhost$dbuser$dbpassword);
mysql_select_db($database$conexion);
// Generamos una lista de los ID's (campo value= ..) que tenemos en nuestro array. 
$lista=implode(',',$_POST['seleccion']); 

// Y lo aplicamos al SQL correspondiente y ejecutamos la consulta. 
mysql_query("UPDATE stock set activo = 0 WHERE id_stock IN(".$lista.")"); 
header("Location: index.html");
     
?>

Última edición por tesistas; 09/04/2012 a las 16:41
  #2 (permalink)  
Antiguo 10/04/2012, 06:05
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Sabadell
Mensajes: 4.897
Antigüedad: 16 años, 1 mes
Puntos: 574
Respuesta: problemas con menu ajax y boton volver

Si se ha hecho el borrado en bbdd simplemente vuelve a llamar la pagina de borrado se cargará con lo que haya en la bbdd....

Junta las dos ultimas paginas que nos muestras (sin el header), pero rodeando de un condicional las primeras lineas de la ultima si no llega nada por post que no haga el update ... y si el resto de la pagina (la segunda que nos muestras).... despues de la seleccion rellamas a la misma pagina, por AJAX, pero con el post lleno asi se ejectura el UPDATE y despues te mostrará los productos que queden...

Se trata de recargar solo el div "response" no recargar todo el index...

Te adjunto las funciones de js que deben substiuir el action del formulario...

Algo asi


Código PHP:
Ver original
  1. <?php
  2. include_once 'lib.php';
  3. $conexion= mysql_connect($dbhost, $dbuser, $dbpassword);
  4. mysql_select_db($database, $conexion);
  5.  
  6. // Si hay una seleccion modificamos la bbdd
  7.  
  8. if (isset($_POST['seleccion'])){
  9.        foreach ($_POST['seleccion'] as $id){
  10.             echo $id."<br>";
  11.        }  
  12.        // Generamos una lista de los ID's (campo value= ..)
  13.        //que tenemos en nuestro array.
  14.        $lista=implode(',',$_POST['seleccion']);
  15.         // Y lo aplicamos al SQL correspondiente y ejecutamos la consulta.
  16.         mysql_query("UPDATE stock set activo = 0 WHERE id_stock IN(".$lista.")");
  17. }
  18.  
  19.  
  20. // Haya o no seleccion mostramos el contenido de stock
  21.  
  22. $result = mysql_query("SELECT id_stock, codigo, descrip, pre_min, pre_may, disponibles  FROM stock where activo = '1'", $conexion);
  23.  
  24. ?>
  25. <form name='borrar'>
  26.     <table id="etiquetas" border='1'>
  27. <tr style="background-color: #ffff99">
  28.     <th>ID</th>
  29.     <th>Codigo</th>
  30.     <th style='width: 500px'>Descrip</th>
  31.     <th>Prec.Min</th>
  32.     <th>Prec.May</th>
  33.     <th>Disponibles</th>
  34.     <th></th>
  35. </tr>
  36. <?php
  37. $i=0;
  38. while($row = mysql_fetch_array($result)){
  39. ?>
  40.     <tr>
  41.         <td><?php echo $row['id_stock'] ?></td>
  42.         <td><?php echo $row['codigo'] ?></td>
  43.         <td style='width: 500px'><?php echo $row['descrip'] ?></td>
  44.         <td align=right><?php echo "$"; echo $row['pre_min'] ?></td>
  45.         <td align=right><?php echo "$"; echo $row['pre_may'] ?></td>
  46.         <td align=center><?php echo $row['disponibles'] ?></td>
  47.         <td><input name='seleccion[]' type='checkbox' value=<?php echo $row['id_stock']?>></td>
  48.      </tr>
  49. <?php    
  50.     $i++;
  51. }
  52. ?>
  53. </table>
  54. <br>
  55. <input type='button' name='submit' value='enviar' onclick='clSdInFrZnPost("response","stock.php",this.form)'>
  56. </form>

Funciones que te serviran para recargar solo el div "response", deberás modificar la primera para que cargue el array de la selección...


Código Javascript:
Ver original
  1. function clSdInFrZnPost(id,url,formulari){
  2.     var parametres="";
  3.     var j=0;
  4.     for (i=0;i<formulari.elements.length;i++){
  5.         if (formulari.elements[i].type!="button"){
  6.             j++;
  7.             if(j!=1)parametres+="&";
  8.             if (formulari.elements[i].type=="checkbox"){
  9.                 if(formulari.elements[i].checked){
  10.                     parametres+=formulari.elements[i].id+"="+true;
  11.                 }else{
  12.                     parametres+=formulari.elements[i].id+"="+false;
  13.                 }
  14.             }else if (formulari.elements[i].type=="radio"){
  15.                     if(formulari.elements[i].checked){
  16.                         parametres+=formulari.elements[i].id
  17.                                                               +"="+formulari.elements[i].value;
  18.                     }
  19.             }else{
  20.             parametres+=formulari.elements[i].id
  21.                                                    +"="+formulari.elements[i].value;
  22.             }
  23.         }
  24.     }
  25.          //Si descomentas este alert veras que parametros lanzas....
  26.     //alert(parametres);
  27.     clientSideIncludePost(id, url, parametres)
  28. }
  29.  
  30. function clientSideIncludePost(id, url, parametres) {
  31.   var req = false;
  32.   // For Safari, Firefox, and other non-MS browsers
  33.   if (window.XMLHttpRequest) {
  34.     try {
  35.       req = new XMLHttpRequest();
  36.     } catch (e) {
  37.       req = false;
  38.     }
  39.   } else if (window.ActiveXObject) {
  40.     // For Internet Explorer on Windows
  41.     try {
  42.       req = new ActiveXObject("Msxml2.XMLHTTP");
  43.     } catch (e) {
  44.       try {
  45.         req = new ActiveXObject("Microsoft.XMLHTTP");
  46.       } catch (e) {
  47.         req = false;
  48.       }
  49.     }
  50.   }
  51.  //req.expires=-1;
  52.  var element = document.getElementById(id);
  53.  if (!element) {
  54.   alert("Bad id " + id +
  55.    "passed to clientSideInclude." +
  56.    "You need a div or span element " +
  57.    "with this id in your page.");
  58.   return;
  59.  }
  60.   if (req) {
  61.     // Synchronous request, wait till we have it all
  62.     req.open('POST', url, false);
  63.     req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  64.     req.send(parametres);
  65.     element.innerHTML = req.responseText;
  66.   } else {
  67.     element.innerHTML =
  68.    "Sorry, your browser does not support " +
  69.       "XMLHTTPRequest objects. This page requires " +
  70.       "Internet Explorer 5 or better for Windows, " +
  71.       "or Firefox for any system, or Safari. Other " +
  72.       "compatible browsers may also exist.";
  73.   }
  74.    
  75. }
__________________
Quim
--------------------------------------------------
Ayudar a ayudar es una buena práctica!!! Y da buenos resultados.

Última edición por quimfv; 10/04/2012 a las 06:18

Etiquetas: ajax
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 03:12.