2015-04-02 4 views
2

Привет, у меня есть форма ajax submit, и я хочу вернуть данные json. По какой-то причине он не работает должным образом. Когда data.error возвращается, он должен сообщить мне, что сообщение исправлено. То же самое для других ответов. Что я сделал не так? У моего php есть json-заголовок, а также тип данных json.Как вернуть с помощью jquery объект массива php json?

$(function() { 

    $("form#login").on('submit', function(e){ 
    e.preventDefault(); 
      $.ajax({ 
      type: "POST", 
      url: "log.php", 
      data: $('form#login').serialize(), 
      dataType:"json", 
      success: function(data){ 

        if(data.error == "yes") 
         { 
         $("#msg").html('Email is incorect.') 
         } 
        else if (data.mandatory == "yes") 
         { 
         $("#msg").html('please complete email and pass') 
         } 
         else if (data.tip =='user') 
         { 

        alert('it works'+ data.id); 
        } 
            }, 

     error: function(){ 
      alert("failure"); 
      } 
       }); 
    }); 
}); 

мой PHP

<?php 
header('Content-Type: application/json'); 
session_start(); 
include ('core/dbconfig.php'); 
$password=$_POST['password']; 
$usernume=$_POST['email']; 
$hash = hash('sha512', $password); 

if ($password=='' or $usernume=='') 
{ 
    $arr[] = array('mandatory' => 'yes'); 
    echo json_encode($arr); 
} 


else 
{ 
$stmt = $dbh->prepare("SELECT * FROM Users where Email=:username and Password= :hashed"); 
       $stmt->bindParam(':username', $usernume); 
       $stmt->bindParam(':hashed', $hash); 
       $stmt->execute(); 
      if ($row = $stmt->fetch()) 
      { 
       $_SESSION['id_user']=$row['ID_User']; 
       $arr[] = array(  
       'tip' => 'user', 
       'id' => '3'  
           ); 
       echo json_encode($arr); 
      } 

      else 

      { 
       $arr[] = array('error' => 'yes',); 
       echo json_encode($arr); 
      } 

}   
?> 
+0

Какие отзывы вы получаете? –

+0

Сделайте 'console.log (data);' и посмотрите на структуру своих данных. Это не то, что вы ожидаете (подсказка: 'data' - это ** массив **). См. [Доступ/процесс (вложенные) объекты, массивы или JSON] (http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) для получения дополнительной помощи. –

ответ

0
   if(data.error != undefined) ///i think this is the right way 
       { 
          $("#msg").html('Email is incorect.') 


       }else if(data.length == 0){ 

         alert("No users available"); 

       }else { 

         /* 
         you will have to do an iteration here of your 
         "data" parent object through your child objects        
         */ 

         for(var x in data){ 

          if (data[x].mandatory == "yes") 
          { 
           $("#msg").html('please complete email and pass') 
          } 
          else if (data[x].tip =='user') 
          { 

           alert('it works'+ data[x].id); 

          } 

         } //close for       


       } //close else