phpjqueryarraysjsonparsing

jQuery - How to parse the JSON array?


I would like to parse through jquery. When I want to parse, there is an error - undefined.

This is my code:

PHP

try { 

session_start();

require '../SqlConfig.php';

  
 if(isset($_POST["user_name"]) && isset($_POST["user_password"])) {
 {  

$sql = "SELECT * FROM users WHERE user_name='".mysql_real_escape_string($_POST["user_name"]) . "' AND " . "user_password='". mysql_real_escape_string($_POST["user_password"]) ."'";

$result = mysql_query($sql) or die(mysql_error());

$jsonresult = array();

  while($row = mysql_fetch_array($result))
  {
    $thisResult = array();

    $thisResult["user_auth"] = 1;
    $thisResult["user_id"] = $row['user_id'];
    $thisResult["user_name"] = $row['user_name'];
    
    $_SESSION["user_auth"] = 1;
    $_SESSION["user_id"] = $row['user_id'];
    $_SESSION["user_name"] = $row['user_name'];
    
    $jsonresult[] = $thisResult;
  }
  echo json_encode($jsonresult);
  mysql_close();
  }

}
}
catch(Exception $e) 
{
echo $e->getMessage();
}

JSON ARRAY:

[{"user_auth":1,"user_id":"11","user_name":"Jenan"},
 {"user_auth":1,"user_id":"15","user_name":"Jenan2"},
 {"user_auth":1,"user_id":"16","user_name":"Jenan3"}]

JQUERY:

getAuthentification: function(username, password)
    {
        $.post('ActionScripts/Authentification.php',{
            user_name: username, 
            user_password: password
        }, function(data) 
        {
          $.each(data, function(key, value){
                alert(value.user_auth +' - '+ value.user_id +' - '+ value.user_name);
            });
          
          
        });
    }

Here is the error: The result is undefined - undefined - undefined. And an endless cycle. -

$.each(data, function(key, value){
                alert(value.user_auth +' - '+ value.user_id +' - '+ value.user_name);
            });

data -

 [{"user_auth":1,"user_id":"11","user_name":"Jenan"},
 {"user_auth":1,"user_id":"15","user_name":"Jenan2"},
 {"user_auth":1,"user_id":"16","user_name":"Jenan3"}]

alert - output - undefined - undefined - undefined


Solution

  • try this:

    getAuthentification: function(username, password)
        {
            $.post('ActionScripts/Authentification.php',{
                user_name: username, 
                user_password: password
            }, function(data) 
            {
              $.each(data, function(key, value){
                    alert(value.user_auth +' - '+ value.user_id +' - '+ value.user_name);
                });
    
    
            },"json");
        }
    

    all i added was ,"json" to the end to tell jquery that it should expect a json response instead of a string response.