JavaScript - Enviar variable javascript a PHP

 
Vista:
sin imagen de perfil

Enviar variable javascript a PHP

Publicado por Angélica (2 intervenciones) el 19/03/2014 22:02:54
Buen día a todos,

Necesito ayuda con lo siguiente,

Quiero ejecutar un qery en mysql al momento de seleccionar una opción de un item select,
esto lo hago con javascript, dependiendo de la opción que se elija así mismo cambiara el valor en un campo de precio.

este es el script que se ejecuta cuando cambio el la opcion en el select.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function asigna_valor(id) {
	var id_sublinea = document.getElementById('sublinea_'+id).value;
	var new_precio;
 
if(window.XMLHttpRequest) {
    peticion_http = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
    peticion_http = new ActiveXObject("Microsoft.XMLHTTP");
  }
  peticion_http.onreadystatechange=handleStateChange;;
 
  peticion_http.open('GET', 'change_precio.php?id_linea=id_sublinea', true);
  peticion_http.send(null);
 
  function handleStateChange(){
	if(peticion_http.readyState == 4){
		if(peticion_http.status ==200){
			new_precio = peticion_http.responseText;
 
		}
	}
}
 
	var id_precio = document.getElementById('precio_' + id);
	id_precio.setAttribute("value",new_precio);
}

y el documento php es asi:

1
2
3
4
5
6
<?  	$id_sublinea = $_GET('id_linea');
	 		$qry2 =  mysql_db_query($database, "select precio from sublinea_articulos where sublinea_articulo = $id_sublinea") or die (mysql_error());
	 		$result2 = mysql_fetch_array($qry2);
			$new_precio = $result2['precio'];
			echo $new_precio:
	 ?>;

Estoy comenzando con AJAX y necesito ayuda, no se que estoy haciendo mal.

Saludos.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Enviar variable javascript a PHP

Publicado por xve (2100 intervenciones) el 20/03/2014 08:40:59
Hola Angélica, nos puedes mostrar el formulario para poder probarlo?

Creo que el problema lo tienes en que dentro de la función handleStateChange() no sabe que es la variable peticion_http

Prueba a modificar esta linea:
1
peticion_http.onreadystatechange=handleStateChange;;
por:
1
2
3
4
peticion_http.onreadystatechange=function()
{
	handleStateChange(peticion_http);
}

y en:
1
function handleStateChange(){
reemplaza por:
1
function handleStateChange(peticion_http){

No lo he probado...

Te indica algún error en la consola de errores?

Aquí tienes un ejemplo:
http://www.lawebdelprogramador.com/codigo/AJAX/1494-Actualizar_pagina.html
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Enviar variable javascript a PHP

Publicado por Angélica (2 intervenciones) el 20/03/2014 14:49:30
Hola, gracias por responder.
Aun no me funciona, sigue saliendo undefined en el campo de precio

Este es el formulario completo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
<!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" />
<?php
include "../config.php";
	// connect to the mysql server 
	$link = mysql_connect($server, $db_user, $db_pass)
	or die ("Could not connect to mysql because ".mysql_error());
 
	// select the database
	mysql_select_db($database)
	or die ("Could not select database because ".mysql_error());
 
      	$qry =  mysql_db_query($database, "select sublinea_articulo,descripcion from sublinea_articulos where ind_activo = 'S'") or die (mysql_error());
	while ($result = mysql_fetch_array($qry)) {
		$text = $text."<option value='".$result['sublinea_articulo']."'>".$result['descripcion']."</option>";
	 }
	 $option = array($text);
	 $qry1 =  mysql_db_query($database, "select precio from sublinea_articulos where sublinea_articulo = 101") or die (mysql_error());
	 $result1 = mysql_fetch_array($qry1);
	 $tot_precio = $result1['precio'];
 
	?>
<script type="text/javascript">
 
var idcot = 1;
function suma()    {
var sublinea = "sublinea_"+idcot;
var codigo = "codigo_"+idcot;
var precio = "precio_"+idcot;
var talla = "talla_"+idcot;
var id_borrar = "BORRAR_"+idcot;
    var miTabla = document.getElementById("cuerpoTabla");
    var fila = document.createElement("tr");
    fila.id = "rowDetalle_" + idcot;
    var celda1 = document.createElement("td");
    var celda2 = document.createElement("td");
    var celda3 = document.createElement("td");
	var celda4 = document.createElement("td");
	var celda5 = document.createElement("td");
	var opcion = [];
	var tot_precio=0;
    <?php
            for($i=0; $i < count($option); $i++ ){
                echo 'opcion['.$i.'] = "'.$option[$i].'";';
            }
			echo 'tot_precio = "'.$tot_precio.'";';
        ?>
    celda1.innerHTML = '<select name="'+sublinea+'" id="'+sublinea+'" onchange="asigna_valor('+idcot+')">' +  opcion + '</select>';
    celda2.innerHTML = '<input type=text name="'+codigo+'" id="'+codigo+'" size="30">';
	celda3.innerHTML = '<input type=text name="'+precio+'" id="'+precio+'" size="7" value="'+tot_precio+'">';
	celda4.innerHTML = '<input type=text name="'+talla+'" id="'+talla+'" size="5">';
    celda5.innerHTML = '<center><img src="../image/delete.png" width="16" height="16" alt="Eliminar" onclick="if(confirm(\'Realmente desea eliminar este artículo?\')){eliminarFila(' + idcot + ');}"/></center>';
    fila.appendChild(celda1);
    fila.appendChild(celda2);
    fila.appendChild(celda3);
	fila.appendChild(celda4);
	fila.appendChild(celda5);
    miTabla.appendChild(fila);
	document.form1.cantidad.value=idcot;
	idcot = idcot + 1;
}
 
function eliminarFila(idcot1){
		var objHijo = document.getElementById('rowDetalle_' + idcot1);
		var objPadre = objHijo.parentNode;
		objPadre.removeChild(objHijo);
		var cantidad1 = document.form1.cantidad.value-=1;
		var cantidad_ant = cantidad1 + 1;
		idcot1 = idcot1 + 1;
		var a;
		while (document.getElementById('rowDetalle_' + idcot1)) {
		var idnew = idcot1-1;
		var objnew = document.getElementById('rowDetalle_' + idcot1);
		var sublinea = document.getElementById('sublinea_' + idcot1);
		var codigo = document.getElementById('codigo_' + idcot1);
		var precio = document.getElementById('precio_' + idcot1);
		var talla = document.getElementById('talla_' + idcot1);
 
		objnew.id = 'rowDetalle_' + idnew;
 
		sublinea.setAttribute('name','sublinea_'+idnew);
		codigo.setAttribute('name','codigo_'+idnew);
		precio.setAttribute('name','precio_'+idnew);
		talla.setAttribute('name','talla_'+idnew);
 
		sublinea.setAttribute("id","sublinea_"+idnew);
		codigo.setAttribute("id","codigo_"+idnew);
		precio.setAttribute("id","precio_"+idnew);
		talla.setAttribute("id","talla_"+idnew);
		idcot1 = idcot1 + 1;
		idcot = idnew+1;
		}
		//return false;
	}
function asigna_valor(id) {
	var id_sublinea = document.getElementById('sublinea_'+id).value;
	var new_precio;
 
if(window.XMLHttpRequest) {
    peticion_http = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
    peticion_http = new ActiveXObject("Microsoft.XMLHTTP");
  }
 
  peticion_http.open("GET", "change_precio.php?id_linea="+id_sublinea, true);
 
  peticion_http.onreadystatechange=function(){
	if(peticion_http.readyState == 4 && peticion_http.status ==200){
			new_precio = peticion_http.responseText;
	}
}
	 peticion_http.send(null);
 
	var id_precio = document.getElementById('precio_' + id);
	id_precio.setAttribute("value",new_precio);
}
</script>;
<title>Untitled Document</title>
<style type="text/css">
body {
	background-image: url(../image/background.png);
}
h1,h2,h3,h4,h5,h6 {
	font-family: "Agency FB";
}
h1 {
	font-size: 12px;
	color: #333;
	font-family: Verdana, Geneva, sans-serif;
}
h2 {
	font-size: 24px;
	color: #333;
}
h3 {
	font-size: 16px;
	color: #C00;
}
#caja {
	background-color: #FFFFFF;
	height: 700px;
	width: 810px;
	padding: 10px;
	/*para Firefox*/
-moz-border-radius: 20px 20px 20px 20px;
	/*para Safari y Chrome*/
-webkit-border-radius: 20px 20px 20px 20px;
	/* para Opera */
border-radius: 20px 20px 20px 20px;
}
#form1 #caja table tr td {
	font-family: Verdana, Geneva, sans-serif;
	color: #333;
	font-weight: bold;
	font-size: 9px;
}
strong {
	color: #AB81D6;
}
#form1 #caja table tr td div p {
	font-weight: normal;
}
#cuerpoTabla
{ background-color: white;
 }
</style>
</head>
<body>
<div align="center">
  <p><img src="../image/Movie1-000001.png" width="546" height="272" /></p>
  <form id="form1" name="form1" method="post" action="register.php"  onSubmit="return validate()">
  <div id="caja">
    <table width="776" height="193" border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td height="9" colspan="2" bgcolor="#CCCCCC">&nbsp;</td>
        <td height="9" colspan="3" align="right" bgcolor="#CCCCCC"><h1>Bienvenido:</h1></td>
        </tr>
      <tr>
        <td height="9" colspan="5" bgcolor="#CCCCCC" align="center"><h1>CONSULTA PEDIDOS &nbsp;&nbsp;&nbsp;&nbsp;| &nbsp;&nbsp;&nbsp;&nbsp;CREAR PEDIDO&nbsp;&nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp;&nbsp;PERFIL&nbsp;&nbsp;&nbsp;&nbsp; | &nbsp;&nbsp;&nbsp;&nbsp;SALIR</h1></td>
        </tr>
      <tr>
        <td height="3" colspan="5" bgcolor="#999999"></td>
        </tr>
      <tr>
        <td height="54" colspan="5"><h1><strong>CREACION DE PEDIDO</strong></h1></td>
        </tr>
      <tr align="center" bordercolor="#000000">
        <td width="92"><h1>&nbsp;</h1></td>
        <td height="27" colspan="3"><h1>&nbsp;</h1></td>
        <td width="125">&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td colspan="3">&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>&nbsp;</td>
        <td colspan="3">&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
    </table>
    <table border="0">
      <tr>
        <td><input name="cantidad" type="text" size="1" maxlength="2"  disabled="disabled"/></td>
        <td><input type="button" name="Agregar" value="Agregar" onclick="suma()" /></td>
        <td> </td>
        <td><input type="submit" name="cnslt_total" value="Consulta final" /></td>
      </tr>
      <tr>
        <td><tr></td>
      </tr>
      <table width="200xp" border="0" id="tblDetalle">
        <thead>
          <tr bgcolor="d9d9d9">
            <th><font size='-1'><b>Artículos</b></th>
            <th><font size='-1'><b>Código</b></th>
            <th><font size='-1'><b>Precio</b></th>
            <th><font size='-1'><b>Talla</b></th>
          </tr>
        </thead>
        <tr></tr>
        <tbody id="cuerpoTabla">
        </tbody>
        <tr>
          <td></tr></td>
        </tr>
      </table>
      <tr>
        <td></tr></td>
      </tr>
    </table>
  </div>
  </form>
  <p>&nbsp;</p>
</div>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar