Ajax error in javascript

hello, i am facing an issue in ajax topic. i have run the code several times and even tallied with the code in the video, still i was not able to get the output name after clicking the submit button can you please solve my issue. i am attaching my html code please check this.

<body>
	<p id="era">hello people</p>
	<input id="user_number"`Preformatted text`>
	<button onclick="update_user()">submit</button>
	<script type="text/javascript">
		function update_user(){
			user_number=document.getElementById("user_number").value;
			httpRequest=new XMLHttpRequest();
			httpRequest.open("GET","http://reqres.in/api/users/"+user_number);
			httpRequest.send();

			httpRequest.onreadystatechange=function()
				{
				if (this.readyState == 4 && this.status == 200)
				{
					user_data=JSON.parse(this.responseText)
					document.getElementById("era").innerHTML=user_data.data.name;
				}
			}
		}
	</script>
</body>

Hi @160418735048,

  1. Add the https in url
  2. Instead of name, change it to first_name.

Check the below code -

<body>
    <p id="era">hello people</p>
    <input id="user_number">
    <button onclick="update_user()">submit</button>
    <script type="text/javascript">
        function update_user(){
            user_number=document.getElementById("user_number").value;
            httpRequest=new XMLHttpRequest();
            httpRequest.open("GET","https://reqres.in/api/users/"+user_number);
            httpRequest.send();

            httpRequest.onreadystatechange=function()
                {
                if (this.readyState == 4 && this.status == 200)
                {
                    user_data=JSON.parse(this.responseText)
                    document.getElementById("era").innerHTML= user_data.data.first_name;
                }
            }
        }
    </script>
</body>

Do let me know in case you need any other information.

1 Like

Thank you. Your answer solved my problem, and what is the difference between http and https like when should we use http and when should we use https?

Hi @160418735048,

HTTP with secure socket layer is called HTTPS. In HTTPS protocol data is transmitted in an encrypted format over the network and it becomes difficult to read the data packets by the middleman in the network.

You can read more about HTTP and HTTPS here https://www.cloudflare.com/en-in/learning/ssl/what-is-https/

If you are going live with your web app, then it is always recommended to use an SSL(Secure Socket layer) certificate.

Do let me know in case you need any other information.

Thank you,your answer solved my problem.

Sir, I’ve used this code of yours for testing and it worked.
But when i typed the same code I was unable to get the result.