Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a web service from javascript

Say I have a web service http://www.example.com/webservice.pl?q=google which returns text "google.com". I need to call this web service (http://www.example.com/webservice.pl) from a JavaScript module with a parameter (q=google) and then use the return value ("google.com") to do further processing.

What's the simplest way to do this? I am a total JavaScript newbie, so any help is much appreciated.

like image 381
Nikhil Avatar asked Sep 23 '08 01:09

Nikhil


People also ask

Can JavaScript call web service?

The code that allows you to call a web service from javascript: First the Javacript code to encapsulate the XMLHttpRequest object. This is a Javascript object with which we will create a new instance and and make the asynchronous call to the host.

How do you call a web service?

To call a Web service programmaticallyUse the Web reference name (or server name) as the namespace, and the name of its . WSDL file (or the service name) as the proxy class. The following code example calls a Web service method to get a string value. Web service variable names and syntax are highlighted.

How do you make a get API call in JavaScript?

val(""); let request = new XMLHttpRequest(); const url = `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=[YOUR-API-KEY-HERE]`; request. onreadystatechange = function() { if (this. readyState === 4 && this. status === 200) { const response = JSON.


2 Answers

EDIT:

It has been a decade since I answered this question and we now have support for cross-domain XHR in the form of CORS.

For any modern app consider using fetch to make your requests. If you need support for older browsers you can add a polyfill.

Original answer:

Keep in mind that you cannot make requests across domains. For example, if your page is on yourexample.com and the web service is on myexample.com you cannot make a request to it directly.

If you do need to make a request like this then you will need to set up a proxy on your server. You would make a request to that proxy page, and it will retrieve the data from the web service and return it to your page.

like image 99
Prestaul Avatar answered Oct 23 '22 07:10

Prestaul


Take a look at one of the many javascript libraries out there. I'd recommend jQuery, personally. Aside from all the fancy UI stuff they can do, it has really good cross-browser AJAX libraries.

$.get(
    "http://xyz.com/webservice.pl",
    { q : "google" },
    function(data) {
        alert(data);  // "google.com"
    }
);
like image 29
nickf Avatar answered Oct 23 '22 05:10

nickf