11

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.

Nikhil
  • 2,028
  • 7
  • 24
  • 33

2 Answers2

14

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.

Prestaul
  • 83,552
  • 10
  • 84
  • 84
  • i want to get data form other site without using proxy, are there solution to resolcve this problem – Ayoub Benayache Apr 16 '18 at 23:49
  • 1
    @AyoubBenayache, yes, you have to implement CORS headers (which weren't available when this answer was written a decade ago). There is a ton of good information about this if you just search CORS. – Prestaul May 07 '18 at 19:22
12

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"
    }
);
nickf
  • 537,072
  • 198
  • 649
  • 721