Home > database >  Can't get array data from "response"
Can't get array data from "response"

Time:02-15

I can't get array data from "response" in my jQuery script. Command "Alert" shows "undefined" instead of data.

        $.ajax({
            type:'post',
            url:'/action/edit.php',
            data:{'user_id':'<?=$user_id;?>','bid': blckID},
            response:'text',
            dataType: 'JSON',
            success: function(response){        
                var title = response.title;
                var content = response.content;
                alert(title);
            }
        
        });

Handler:

$user_id = $_POST['user_id'];
$blckID = $_POST['bid'];

$query = "SELECT title,content FROM uprt_user_blocks WHERE `user_id`={$user_id} AND `id`={$blckID}";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_assoc($result);


$return_arr[] = array("title" => $row['title'],
                    "content" => $row['content']);


// Encoding array in JSON format
echo json_encode($return_arr);

CodePudding user response:

$return_arr[] = means "Add the assignment to the end of the array in $return_arr, creating that array if needed".

The JSON you are sending looks like this:

[
    { title: "something", content: "something" }
]

response is an array containing an object, but you are trying to treat it as the object itself (with no array).


Either:

  • Return an object by saying $return_arr = instead of $return_arr[] =
  • Deal with the array in response (e.g. with a for loop or directly accessing [0]).
  • Related