Hector Chacon Perez
Hector Chacon Perez

Reputation: 45

jQuery $.each loop and json mysql data

Well i have this php for get the value of mysql. I get two rows in this query.

include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT
accion_inmediata.accion,
accion_inmediata.responsable,
accion_inmediata.peligro,
accion_inmediata.ambiente,
DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion
FROM
accion_inmediata
WHERE
accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = mysql_fetch_array($result);
echo json_encode($array);

and this is my Jquery code

function traerAcciones(pnc){

      $.ajax({                         
      url: 'php_ajax/select_acciones.php?pnc='+pnc,               
      data: "",                        
      dataType: 'json',                
      success: function(data)          
      {

  $.each(data, function() {
 alert(this.accion);

});
      } 
    }); 
    }

when i execute this code the alert show me "undefined". The $.each loop works fine but the value is the problem. Please help and sorry for my bad English

Upvotes: 0

Views: 1638

Answers (2)

Suthan Bala
Suthan Bala

Reputation: 3299

Currently you are returning the array of your first row only. So to retrieve both you might want to do this:

include('../funciones/funciones.php');
$link=Conectarse();
$pnc=$_GET['pnc'];
$query="SELECT accion_inmediata.accion, accion_inmediata.responsable, accion_inmediata.peligro, accion_inmediata.ambiente, DATE_FORMAT(accion_inmediata.fecha,'%m-%d-%Y') as fechaAccion FROM accion_inmediata WHERE accion_inmediata.id_pnc = '$pnc'";
$result = mysql_query($query,$link);
$array = array();
while($row = mysql_fetch_array()):
$array[] = $row;
endwhile;
echo json_encode($array);

Now your jquery should be able to retrieve the data. Also, please avoid using MYSQL_QUERY it's deprecated.

Upvotes: 0

homtg
homtg

Reputation: 1999

Try to pass the value and the Index as parameters, this is how it works:

$.each(data, function(index, value) {
 alert( value.accion );
});

Might also be a problem with the data object not containing what you think it does, do a

console.log(index, value);

inside your loop and a

console.log(data);

before the loop and you will see what you have and how to handle it.

Hope it helps!

Upvotes: 2

Related Questions