Ajax json Request using Promise

Pugazhenthi

This is a suitable example for promise based ajax call. If we need to display data form json request there are more posibility to get error. Promise based request is clean and easy to hadle errors.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Random Users</title>
    <link href="main.css" rel="stylesheet">
</head>
<body>

<div class="card">
    <img id="photo" />
    <h3 id="userName"></h3>
    <h4 id="email"></h4>
</div>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="randomUser.js"></script>
</body>
</html>

In this example i use JQquery.ajax. And get response from https://randomuser.me/api/

let getUser  = new Promise((resolve, reject) => {
        $.ajax({
            url: 'https://randomuser.me/api/',
            dataType: 'json',
            success: function(data) {
                resolve(data);
            },
            error: function(error) {
                reject(error);
            }
        });
    });

let displayData = data => {
    let userName = data.results[0].name.first + ' ' + data.results[0].name.last;
    let email = data.results[0].email;
    let picture = data.results[0].picture.large;

    $("#userName").html(userName);
    $("#email").html(email);
    $("#photo").attr('src', picture );
};

getUser.then(data => {
    displayData(data);
}).catch(e=>{
    console.log(e);
});
body{
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.card{
    display: flex;
    align-items: center;
    flex-direction: column;
    border: 1px solid #ddd;
    padding: 10px;
    margin: 20px;
    width: 300px
}

.card #photo{
    border-radius: 50%;
}
h3, h4{
    text-align: center;
    margin: 5px;
}
h3{
    text-transform: uppercase;
}

See this code in Action..

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2019, RTP SYSTEMS