elvenbyte
elvenbyte

Reputation: 776

Trying to get the JSON data, but nothing happens

javascript code:

$.getJSON("comprueba_login.php", {usuario:$("#usuario").val(), pwd:$("#contrasena").val()}, function(data){
            alert("resultado: " + data.resultado);
        });

php code:

<?php
    include 'db.php';
    $usuario = $_GET['usuario'];
    $pwd = $_GET['pwd'];
    $sql = "SELECT IDUSUARIO FROM USUARIOS WHERE USERUSUARIO = '" . $usuario . "' AND PWUSUARIO = '" . $pwd . "'";
    $res =  mysql_query($sql, $db) or die("fallo query: " . mysql_error());
    // echo $sql . "<br>";      

    if(mysql_num_rows($res)){?>
        {'resultado':'OK'}
    <?php }else{ ?> 
        {'resultado':'NO_OK'}
    <?php }?>

The alert in the javascript code never appears. What am I doing wrong?

Thanks in advance.

Upvotes: 0

Views: 109

Answers (2)

Dave
Dave

Reputation: 4412

First and most importantly, don't put your database credentials in your web pages.

Silent failure from getJSON usually indicates a syntax error in the JSON string.

$.getJSON("comprueba_login.php", {usuario:$("#usuario").val(), pwd:$("#contrasena").val()}, function(data){
            alert("resultado: " + data.resultado);
        }).error(function() { alert("Error in getJSON") });

Will confirm this.

I believe the correct syntax for what you're trying to do is this:

   if(mysql_num_rows($res)){?>
        { resultado :"OK"}
    <?php }else{ ?> 
        { resultado : "NO_OK"}
    <?php }?>

But if you're going to be using JSON extensively, you should look into using a package to create it for you.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

JSON keys and string values MUST be enclosed in " double quotes. Single quotes (') WILL NOT work.

Upvotes: 2

Related Questions