简体   繁体   中英

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM