Foros del Web » Programando para Internet » Jquery »

Pasar variable POST JavaScript a php

Estas en el tema de Pasar variable POST JavaScript a php en el foro de Jquery en Foros del Web. Hola foreros del web, tengo una duda revisando unos videos en youtube explicaban como hacer una Barra de Progreso cuando uno sube un archivo al ...
  #1 (permalink)  
Antiguo 23/03/2014, 19:22
 
Fecha de Ingreso: mayo-2012
Ubicación: shilito
Mensajes: 67
Antigüedad: 11 años, 11 meses
Puntos: 3
Sonrisa Pasar variable POST JavaScript a php

Hola foreros del web, tengo una duda revisando unos videos en youtube explicaban como hacer una Barra de Progreso cuando uno sube un archivo al servidor con la técnica de AJAX. Muy interesante que la copie a la adapte a mi sistema, PERO (por eso es el POST) tengo una duda ya que al momento de subir el Archivo al servidor, yo lo quiero dejar con un nombre en especifico.

Voy a tratar de poder expresarme lo mas claro con mi duda haber si me pueden ayudar.


Aquí esta la primera parte del código cargar.php el cual yo hago una consulta a la BBDD y me traigo la información y solicito subir un archivo PDF para completar la operación. Aqui es donde este mi problema, ya que al momento de cargar el archivo yo lo quiero renombrar con el Numero de Movimiento que tengo en Mi base de datos indepenedientemente como se llame el archivo. Esto ya lo habia conseguido con otro archivo PHP, pero como copie este ejemplo y lo adapte a mi sistema quede Pillo al Pasar una variable del TIPO POST a otro archivo PHP con Java.

Código PHP:
Ver original
  1. <?php
  2. include"sesion_valida.php";
  3. include"onexion.php";
  4. include"../querys.php";
  5.  
  6. $consulta_abm = mssql_query($query_mostrar,$conexion);
  7.  
  8. ?>
  9. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  10. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  11.     <head>
  12.         <title>Plataforma</title>
  13.         <meta http-equiv="content-type" content="text/html; charset = utf-8"/>
  14.         <!--<link rel="stylesheet" media="screen" href="JavaScript_Tutorial_9.css"/>-->
  15.         <link href="../../estilos/default.css" rel="stylesheet" type="text/css" />
  16.     </head>
  17.     <body>
  18.         <div id="contenedor-principal">
  19.  
  20.             <h1 class="titulo-mostrar">Plataforma</h1>
  21.  
  22.             <h3 class="titulo">Modulo de carga de Documentos</h3>
  23.  
  24.             <h5 class="caja-izquierda"><a href="../menu_hrd.php">Volver</a><span class="forma"></span></h5>
  25.             <hr />
  26.  
  27.             <br />
  28.             <h5 class="titulo">Seleccione el Archivo a subir según el Número de movimiento</h5>
  29.  
  30.             <div class="busqueda">
  31.                 <form action="" method="post" enctype="application/x-www-form-urlencoded" name="form2" target="_self" id="form2">
  32.                     Buscar Mov
  33.                       <label for="busqueda"></label>
  34.                     <input type="text" name="busqueda" id="busqueda" size="10" />
  35.                     <input type="submit" name="submit" id="submit" value="Buscar" />
  36.                 </form>
  37.             </div>
  38.  
  39.             <?php if(empty($_POST["busqueda"])){?>
  40.             <div id="centra-tabla">        
  41.             <div id="title" class="commonWidth"></div>
  42.             <div id="form_container" class="commonWidth">
  43.                 <?php while($show_info= mssql_fetch_array($consulta_abm)){ ?>
  44.  
  45.                 <form id="upload_form" action="#" method="post" enctype="multipart/form-data">
  46.                     <table>
  47.                         <thead>
  48.                             <tr>
  49.                                 <th class="relleno">N° Mov.</th> <th class="relleno">Ticket</th> <th class="relleno">Fecha Mov.</th>
  50.                                 <th class="relleno">Tipo Mov.</th> <th class="relleno">Estado Asset</th>
  51.                                 <th class="relleno">Descripcion</th> <th class="relleno">Archivo</th>
  52.                                
  53.                             </tr>
  54.                         </thead>
  55.                            
  56.                         <tbody>
  57.                             <tr>
  58.                                 <td><input type="text" name="abm" id="abm" value="<?php echo $show_info['0']; ?>" readonly="readonly" size="10" /></td>
  59.  
  60.                                 <td><input type="text" name="ticket" value="<?php echo $show_info['1']; ?>" readonly="readonly" size="12" /></td>
  61.  
  62.                                 <td><input type="text" name="fecha_crea" value="<?php echo $show_info['fecha_abm']; ?>" readonly="readonly" size="16" /></td>
  63.  
  64.                                 <td><input type="text" name="tipo_mov" value="<?php echo $show_info['tipo_movimiento']; ?>" readonly="readonly" size="18" /></td>
  65.  
  66.                                 <td><input type="text" name="estado" value="<?php echo $show_info['estado']; ?>" readonly="readonly" size="20" /></td>
  67.  
  68.                                 <td><input type="text" name="descripcion" id="descripcion" autocomplete="off" size="20" /></td>
  69.                                
  70.                                 <td>
  71.                                     <input type="file" id="upload_file" size="35"/>
  72.                                 </td>
  73.  
  74.                                 <td>
  75.                                     <input type="button" id="upload_btn" value="Cargar Archivo"/>
  76.                                     <div id="progress_bar_container" class="commonWidth displayNone">
  77.                                     <div id="progress_bar"></div>
  78.                                     </div>
  79.                                     <div class="commonWidth">
  80.                                     <span id="status"></span>
  81.                                     </div>
  82.                                     <script type="text/javascript" src="JavaScript_Tutorial_9.js"></script>
  83.                                 </td>
  84.                             </tr>
  85.                         </tbody>
  86.                     </table>
  87.                 </form>
  88.                 <?php } ?>
  89.             </div>
  90.             </div>
  91.             <?php } ?>
  92.         </div>
  93.     </body>
  94. </html>

Aqui va la función en java (la cual copie )

Código Javascript:
Ver original
  1. //  Trigger function when upload button is pressed
  2. div("upload_btn").onclick = upload_process;
  3.  
  4. //  Start the upload process
  5. function upload_process()
  6. {
  7.     upload_file("upload_file");
  8.     return false;
  9. }
  10.  
  11. //  Upload the selected file
  12. function upload_file(file)
  13. {
  14.     //  Initialize the XMLHttpRequest
  15.     var xhrq = check_ajax_version();
  16.     var form = new FormData(); //   Internet Explorer does not support it.
  17.     var file = div(file).files[0];
  18.    
  19.     //agregamos el post para PHP
  20.     var abm =  $('#abm').val();
  21.    
  22.     form.append("upload_file", file);
  23.    
  24.     xhrq.upload.addEventListener("progress", upload_progress, false);
  25.     xhrq.addEventListener("load", upload_response,false);
  26.     xhrq.open("POST", "JavaScript_Tutorial_9.php", {postabm:abm});
  27.     xhrq.send(form);
  28.  
  29.     return false;
  30. }
  31.  
  32. //  Event listener for the progress of the file
  33. function upload_progress(event)
  34. {
  35.     var upload_percentage = 0;
  36.     if(event.lengthComputable)
  37.     {
  38.         upload_percentage = Math.round((event.loaded / event.total) * 100);
  39.         div("progress_bar_container").style.display = "block";
  40.         div("progress_bar").style.width = (upload_percentage * 1).toString() + "px";
  41.         div("status").innerHTML = upload_percentage.toString() + "% cargado";
  42.     }
  43.     return false;
  44. }
  45.  
  46. //  Response from server whether success or failure
  47. function upload_response(event)
  48. {
  49.     var response = null;
  50.     if(event.target.responseText)
  51.     {
  52.         response = event.target.responseText;
  53.         if(response == 1)
  54.         {
  55.             div("status").innerHTML = "Cargado satisfactoriamente...";
  56.             div("upload_file").value = "";//    Reset the form
  57.             div("progress_bar_container").style.display = "none";
  58.         }
  59.         else
  60.         {
  61.             div("status").innerHTML = response;
  62.         }
  63.     }
  64.     return false;  
  65. }
  66.  
  67. //  Function to check the AJAX version of the browser
  68. function check_ajax_version()
  69. {
  70.     var version = false;
  71.     var ie_versions = ["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "Microsoft.XMLHTTP"];
  72.     for(var i = 0; i < ie_versions.length; i++)
  73.     {
  74.         try
  75.         {
  76.             version = new ActiveXObject(ie_versions[i]);
  77.             break;
  78.         }
  79.         catch(e)
  80.         {
  81.             continue;
  82.         }
  83.     }
  84.     if(version == false)
  85.     {
  86.         version = new XMLHttpRequest();
  87.     }
  88.     else
  89.     {
  90.         version = version;
  91.     }
  92.     return version;
  93. }
  94.  
  95. //  Mimic jQuery
  96. function div(id_of_element)
  97. {
  98.     id_of_element = document.getElementById(id_of_element);
  99.     return id_of_element;
  100. }


Y este el el archivo PHP, el cual se encarga de copiar el archivo al servidor, es aqui donde quiero pasar una variable llamada ABM desde la otra pagina que tiene un formulario con el método POST .

Si se fijan yo comente el la función que da un nombre aleatoreamente renombrando su función.

Código PHP:
Ver original
  1. <?php
  2.  
  3. $file = $_FILES["upload_file"];
  4.  
  5. if($file && $file["error"] == 0)
  6. {:-D
  7.         $tempnames = $file["tmp_name"];
  8.  
  9.         $extension = explode(".", $file["name"]);
  10.         $extension = $extension[1];
  11.  
  12.         $filenames = generate_random(16);
  13.  
  14.         $movedfile = move_uploaded_file($tempnames, "$filenames.$extension");
  15.         if($movedfile)
  16.         {
  17.                 echo 1;
  18.         }
  19.         else
  20.         {
  21.                 echo 0;
  22.                 exit();
  23.         }
  24. }
  25. else
  26. {
  27.     echo 0;
  28.     exit();
  29. }
  30.  
  31. function generate_random($number_of_characters)
  32. {
  33.     $nombre = $_POST['abm'];
  34.     $randomchar = $nombre;
  35. /*      $characters = array();
  36.         $randomchar = "";
  37.         $x = 0;
  38.         for($i = 48; $i < 123; $i++)
  39.         {
  40.                 if(ctype_alnum(chr($i)))
  41.                 {
  42.                         $characters[$x] = chr($i);
  43.                         $x++;
  44.                 }
  45.         }
  46.         for($i = 0; $i < $number_of_characters; $i++)
  47.         {
  48.                 $randomchar .= $characters[rand(0, count($characters) - 1)];
  49.         }
  50.         return $randomchar;*/
  51. }
  52. ?>

Etiquetas: formulario, html, input, javascript, js, php, post, variable
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 19:41.