1

I'm trying to make a application using phonegap. I am trying to make a select using php return the result to ajax function and print the result...but I don't know if I am doing right and what I need to put in my html code to show the result.

AJAX CODE:

$(document).ready(function() {

$.ajax({

    url : 'http://ip/again/www/index.php',

    dataType : "json",

    success : function(data){

        var html = "";


        for($i=0; $i < data.length; $i++){

            html += "<strong>Nome:</strong> "+data[$i].nome +" "+   
            data[$i].sobreNome;

            html += " <strong>Cidade:</strong> "+data[$i].cidade;

            html += "<br />";
        }


        $('body').html(html);
        }
    });
   });
</script>

PHP CODE:

<?php
$hostname = 'localhost';
$username = 'root';
$password = 'pass';
$database = 'mydb';

try {
$pdo = new PDO("mysql:host=$hostname;dbname=$database", $username,   
$password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    //echo 'Conexao efetuada com sucesso!';
}
catch(PDOException $e)
{
    echo $e->getMessage();
}

 $sql = 'SELECT * FROM incidente ORDER BY codigo' ;


try {

$recebeConexao = $pdo->prepare($sql);

$recebeConexao->execute();

$result = $recebeConexao->fetchAll();


if ( count($result) ) {
foreach($result as $row) {
    $incid=$row;
      echo (json_encode($incid));

}
} else {
$incid=0;
}


} catch (PDOException $ex) {
echo "Erro no Banco";
}

?>
Kenster
  • 23,465
  • 21
  • 80
  • 106
  • What is the problem or error you are currently seeing? There's not enough information in your post to help you. Is your AJAX request returning? If so what is the content of the response? – thatidiotguy Nov 05 '15 at 17:18
  • My AJAX is not returning any response...My php return something like: {"codigo":"61","0":"61","nome":"kelly","1":"kelly","sobrenome":"kinder","2":"kinder","cidade":"rio","3":"rio"} {"codigo":"62","0":"62","nome":"jack","1":"jack","sobrenome":"jones","2":"jones","cidade":"bh","3":"bh"} – Amanda Pistolato Nov 05 '15 at 17:30

1 Answers1

0

You're writing the for loop incorrectly. You must declare your variable with the var keyword like so:

for(var $i = 0; $i < data.length; $i++) {
    // ...
}

Since your script does not return an array, the length property will not be available.

When you're dealing with an object in Javascript, you will want to use the for...in syntax (making sure to validate that the property belongs to the object you're iterating over).

However, the code you provided will not return an object or an array, because the JSON is malformed.

The correct way for an API to return multiple, unordered Javascript objects would be to wrap them in an array, like so:

if(count($result)) {
    $list = array();

    foreach($result as $row) {
        $list[] = $row;
    }

    echo json_encode($list);
}
$.ajax({
    // ...
    success: function (data) {
        // Loop over each object, since your script should ideally return an array
        for (var $i = 0; $i < data.length; $i++) {
            var object = data[$i];

            html += '<strong>Nome:</strong> ' + object.nome + ' ' + object.sobreNome;

            // etc...
        }
    }
});
Community
  • 1
  • 1
P810
  • 28
  • 1
  • 5
  • I changed my code, but still not happening...the screen still white and I would like to print the result of "nome", "sobrenome","cidade". But Thank you :) – Amanda Pistolato Nov 05 '15 at 18:00
  • What response are you getting when you use this approach? Are you seeing any error messages in your PHP or Javascript? – P810 Nov 06 '15 at 19:41
  • No, I am not seeing any error messages...My php works, but my ajax function is not working... – Amanda Pistolato Nov 07 '15 at 19:12
  • @AmandaPistolato see my updated answer with a more in depth explanation of why your example code is not being handled like you expected. – P810 Nov 07 '15 at 19:55
  • My PHP is returning: {"codigo":"61","0":"61","nome":"kelly","1":"kelly","sobrenome":"kinder","2":"kin‌​der","cidade":"rio","3":"rio"} {"codigo":"62","0":"62","nome":"jack","1":"jack","sobrenome":"jones","2":"jones"‌​,"cidade":"bh","3":"bh"} – Amanda Pistolato Nov 07 '15 at 22:23
  • I don't know what happened, but now it working...Thanks very much!! – Amanda Pistolato Nov 08 '15 at 22:19