Srujan Barai
Srujan Barai

Reputation: 2365

alert when jQuery fails to get the ip address.

I am new to javascript and jQuery. I want trying to get the ip when the page loads.

I am using this code to get and alert IP:

$.get("http://ipinfo.io", function(response) {
            $myip = response.ip;
            alert($myip);
        }, "jsonp");

This pop out IP only if the internet if connected. I want to show a pop-message "Connection problem" if it fails to get ip. How can I achieve that?

Upvotes: 1

Views: 161

Answers (1)

Zverev Evgeniy
Zverev Evgeniy

Reputation: 3712

Have a look: jQuery.get()

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get( "http://ipinfo.io", function(response) {
    $myip = response.ip;
    alert($myip);
    }, "jsonp")
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

Besides, the jqhrx object exposes the following to make it easy to get the call status any time later:

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

readyState

status

statusText

statusCode()

Upvotes: 2

Related Questions