Skip to content
Advertisement

how to access specific elements from a promise

in php I return to javascript the following:

if(count($user) == 1){
    $response['email'] = 'FOUND';
    if($_POST['formPassword'] == $user[0]['password']){
        $response['password'] = 'MATCH';
    }else{
        $response['password'] = 'NO MATCH';
    }
}else if(count($user) == 0){
    $response['email'] = 'NOT FOUND';
}else{
    $response['email'] = 'DATABASE CORRRRUPT';
}

print_r2(json_encode($response,true));

in my js file I have:

responseData.then(function(response){
    console.log(response)

this writes out to the console:

<pre>{"email":"FOUND","password":"MATCH"}</pre>

how do I access the value ‘FOUND’ associated with the key ’email’? I’ve tried response[’email’], response.email and response[0][’email’]

Advertisement

Answer

The title is very misleading because the problem is completely unrelated to promises.

The backend doesn’t provide pure JSON but HTML containing JSON. There are two ways to approach this problem. The first approach is to print pure JSON without HTML in PHP.

print_r(json_encode($response,true));

The second approach is to parse the HTML, read the node and parse it as JSON:

const responseData = Promise.resolve('<pre>{"email":"FOUND","password":"MATCH"}</pre>');
responseData.then(function(response){
  const dom = new DOMParser().parseFromString(response, 'text/html');
  console.log(JSON.parse(dom.children[0].innerText).email);
});

Of course, I prefer the first approach if possible.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement