sukanta
sukanta

Reputation: 541

How to get web service data with javascript?

I have token value in a URL like http://example.com/api.php?action=token I need to consume this URL data which is a random string, I'm trying with following code:

var jqxhr = $.get("http://example.com/api.php?action=token", function() {
    alert( "success" );
})
.done(function() {
    alert( "second success" );
})
.fail(function() {
    alert( "error" );
})
.always(function() {
    alert( "finished" );
});

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
    alert( "second finished" );
}); 

Using $.get()

While trying to load, it's showing an error. I'm just stuck with it, how to get the data?

Upvotes: 4

Views: 6722

Answers (3)

melc
melc

Reputation: 11671

Cross domain calls are restricted by the browser so some solutions are,

1.Cross-Origin Resource Sharing (CORS) or jsonp, but you will require to have access to the server you are calling and configure that (many examples online e.g. How to make cross domain request)

2.server side proxy - create simple server side code e.g. php page that you will call form js and place code in php that calls the targeted cross domain server and return the results to your js. e.g. AJAX cross domain call

Upvotes: 4

aykut aydoğan
aykut aydoğan

Reputation: 327

try this

  $.ajax({
              url:"http://example.com/api.php?action=token",
              type: "POST",           //try this
              success: function (data) {
                   alert(data)
              }
           });

Upvotes: 0

Systematix Infotech
Systematix Infotech

Reputation: 2365

try this

  $.ajax({
              url:"http://example.com/api.php?action=token",
              type: "GET",
              success: function (data) {
                   alert(data)
              }
           });

Upvotes: 0

Related Questions