开发者

PHP Arrays - jQuery referencing issue

I have the following php:

1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));

I also have the following:

2) $row = mysql_fetch_assoc($result);
   echo(json_encode($row));
开发者_高级运维

Now consider the following jQuery:

 $.ajax({
           type: "POST",
           url: "get_login.php",
           data: {username: getusername, password:getpassword, usertype:getusertype},
           dataType: "json",
           success: function(data) {
              $("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
           }
        })

This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...

How can I make $row in the php compatible with the data.message in the jQuery?


try:

$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
   echo(json_encode($data));

message = row:

$data = array();
$data["message"] = mysql_fetch_assoc($result);
   echo(json_encode($data));

or two line solution (inspired by val):

$row = mysql_fetch_assoc($result);
   echo(json_encode(array("message" => $row)));


Try

$row = mysql_fetch_assoc($result);
   echo(json_encode(array('message'=>'I am the message','result'=>$row));

Then to answer your second question on the comments something similar to this could show the information ....

 $.ajax({
           type: "POST",
           url: "get_login.php",
           data: {username: getusername, password:getpassword, usertype:getusertype},
           dataType: "json",
           success: function(data) {
              $("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
              var html = '';
              for(var i = 0; i<data.result.length;i++){
                 html +='<div>'+data.result[i].fname+'</div>';
               }
              $('#result').html(html);
           }
        })

ofcourse you need to edit it abit where applicable .


i believe you don't have $row['message'] from mysql_fetch_assoc. you have to explicitely define the message key on the array before json_encode.


    $row = mysql_fetch_assoc($result);
    $row['message'] = 'Hello '.$row['username'];
    echo(json_encode($row));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜