Rajendran Nadar
Rajendran Nadar

Reputation: 5438

Jquery ajax call unable to detect 404 from the API

I am working on GitHub rest API, I am able to get the data of a username as soon as I enter the username in the input field. But the ajax call is not able to determine if the link to a user exists or not.

I can see a 404 (Not found) message printed on the console but the #result div never gets updated with the text No users.

$('#username').on('keyup', function() {
  var name = $('#username').val(),
    requri = 'https://api.github.com/users/' + name;

  $.ajax({
    url: requri,
    dataType: "json",
    success: function(data) {

      if (data.message === "Not Found") {
        $("#result").html("No users");
      } else {
        $("#result").html("User found");
      }
      
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="get-user-form">
  <div class="form-group">
    <input id="username" type="text" class="form-control" placeholder="Enter github username" autocomplete="off">
  </div>
</form>

<div id="result"></div>

Upvotes: 1

Views: 1415

Answers (2)

TTomer
TTomer

Reputation: 356

404 is an error code, therefore the xhr will trigger the 'failure' handler, not the "success" handler.

$.ajax({
  url: requri,
  dataType: "json",
  success: function(data) {
    $("#result").html("User found");
  },
  error: function(data) {
     $("#result").html("No users");
  }
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because a 404 response does not go in to the success handler. It goes in to the error handler - assuming you define one.

However in this case as you're specifically looking for a 404 error to indicate the Github user does not exist you can place a handler function for a specific response code using the statusCode property:

$('#username').on('keyup', function() {
  var name = $('#username').val(),
    requri = 'https://api.github.com/users/' + encodeURIComponent(name);

  $.ajax({
    url: requri,
    dataType: "json",
    success: function(data) {
      $("#result").html("User found");
    },
    error: function(x, s, e) {
      console.log('Something went wrong. Handle errors here...');
    },
    statusCode: {
      404: function() {
        $("#result").html("User not found");
      }
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form id="get-user-form">
  <div class="form-group">
    <input id="username" type="text" class="form-control" placeholder="Enter github username" autocomplete="off">
  </div>
</form>

<div id="result"></div>

Note the use of encodeURIComponent() to ensure the value provided in the input is sanitised for use in the URL.

Upvotes: 3

Related Questions