JQuery - error undefined con json

 
Vista:
sin imagen de perfil

error undefined con json

Publicado por pablo (1 intervención) el 11/05/2016 16:15:59
Disculpen es la primera vez que uso el foro, y es la primera vez que uso json, estoy comenzando...

cuando recorro el json, todos sus campos me dan undefined,

que es lo que estoy haciendo mal.?

.js
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
jQuery(document).ready(function(){
     //obtenemos los valores en caso de tenerlos en un formulario ya guardado en la base de datos
     lat = jQuery('#lat').val();
     lng = jQuery('#long').val();
 
     //Asignamos al evento click del boton la funcion codeAddress
     jQuery('#pasar').click(function(){
		var parametros = {
            "latitud" : jQuery('#lat').val(),
            "longitud" :jQuery('#long').val()
		};
 
		$.ajax({
			data:  JSON.stringify(parametros),
            url:   'prueba.php',
            type:  'post',
			success:  function (response) {
				if (response) {
					var infowindow = new google.maps.InfoWindow();
					var marker, i;
					for (var i = 0; i < response.length; i++) {
						var lat =response[i].LATITUD;
						var lon =response[i].LONGITUD;
						alert(lon);
						marker = new google.maps.Marker({
							position: new google.maps.LatLng(lat, lon),
							map: map
						});
 
						google.maps.event.addListener(marker, 'click', (function(marker, i) {
						return function() {
							infowindow.setContent(response[i].PCS_ESDW);
							infowindow.open(map, marker);
						}
						})(marker, i));
					}
					//google.maps.event.addDomListener(window, 'load', initialize);
				}
				else{
					alert('ERROR');
				}
            }
        });
 
		codeAddress();
        return false;
 
     });
     //Inicializamos la función de google maps una vez el DOM este cargado
    initialize();
});

.php
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
<?php
		$lat=$_POST["latitud"];
		$lng=$_POST["longitud"];
 
		$distance = 1; // Sitios que se encuentren en un radio de 1KM
		$box = getBoundaries($lat, $lng, $distance);
		try{
			$pdo = new PDO('mysql:host=127.0.0.1;dbname=sancorsalud_cart', 'root','');
 
			$stmt = $pdo->query('SELECT *, (6371 * ACOS(
														SIN(RADIANS(latitud)) 
														* SIN(RADIANS(' . $lat . '))
														+ COS(RADIANS(longitud - ' . $lng . '))
														* COS(RADIANS(latitud)) 
														* COS(RADIANS(' . $lat . '))
														)
										   ) AS distance
								 FROM prw011_w
								 WHERE (latitud BETWEEN ' . $box['min_lat']. ' AND ' . $box['max_lat'] . ')
								 AND (longitud BETWEEN ' . $box['min_lng']. ' AND ' . $box['max_lng']. ')
								 HAVING distance  < ' . $distance . '
								 ORDER BY distance ASC  LIMIT 10');
 
			$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
			$stmt->closeCursor(); //cierre de la consulta
			//print_r($rows);	
			//$json=json_encode($rows);
			header('Content-type: application/json; charset=utf-8');
			//print_r($rows);
			echo json_encode($rows);
 
		}
		catch (Exception $e){
			//mensaje de error
			die('Error :' .$e->GetMessage());
		}
 
function getBoundaries($lat, $lng, $distance = 1, $earthRadius = 6371)
{
    $return = array();
 
    //Los angulos para cada dirección
    $cardinalCoords = array('north' => '0',
                            'south' => '180',
                            'east' => '90',
                            'west' => '270');
    $rLat = deg2rad($lat);
    $rLng = deg2rad($lng);
    $rAngDist = $distance/$earthRadius;
    foreach ($cardinalCoords as $name => $angle)
    {
        $rAngle = deg2rad($angle);
        $rLatB = asin(sin($rLat) * cos($rAngDist) + cos($rLat) * sin($rAngDist) * cos($rAngle));
        $rLonB = $rLng + atan2(sin($rAngle) * sin($rAngDist) * cos($rLat), cos($rAngDist) - sin($rLat) * sin($rLatB));
        $return[$name] = array('lat' => (float) rad2deg($rLatB),
                                'lng' => (float) rad2deg($rLonB));
    }
    return array('min_lat' => $return['south']['lat'],
                 'max_lat' => $return['north']['lat'],
                 'min_lng' => $return['west']['lng'],
                 'max_lng' => $return['east']['lng']);
}
 
?>
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 Vainas
Val: 27
Ha mantenido su posición en JQuery (en relación al último mes)
Gráfica de JQuery

error undefined con json

Publicado por Vainas (96 intervenciones) el 15/05/2016 15:02:19
Buenas:

Deberias por empezar mostrando que desvuelte en realidad tu Servicio. has si quieres un console.log(response):

1
2
3
4
5
$.ajax({
    ...
    success:  function (response) {
                                    console.log(response);
....

Y vemos si los datos que estan viniendo del servidor son correctos.

Saludos.
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