28

I want to call a webservice from jQuery. How can I do that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jalpesh Vadgama
  • 13,653
  • 19
  • 72
  • 94
  • 2
    I suggest closing the question, if this is answered sufficiently well in the link I posted below – shahkalpesh May 14 '09 at 06:17
  • It is somewhat related to Stack Overflow question *[How to use jQuery to call an ASP.NET web service?](http://stackoverflow.com/questions/230401/how-to-use-jquery-to-call-an-asp-net-web-service/230605)*. – shahkalpesh May 14 '09 at 06:15
  • http://docs.jquery.com/Ajax – Gromer May 14 '09 at 06:22

5 Answers5

29

You can make an AJAX request like any other requests:

$.ajax( {
type:'Get',
url:'http://mysite.com/mywebservice',
success:function(data) {
 alert(data);
}

})
theIV
  • 25,434
  • 5
  • 54
  • 58
7

EDIT:

The OP was not looking to use cross-domain requests, but jQuery supports JSONP as of v1.5. See jQuery.ajax(), specificically the crossDomain parameter.

The regular jQuery Ajax requests will not work cross-site, so if you want to query a remote RESTful web service, you'll probably have to make a proxy on your server and query that with a jQuery get request. See this site for an example.

If it's a SOAP web service, you may want to try the jqSOAPClient plugin.

John G
  • 3,483
  • 1
  • 23
  • 12
3

I blogged about how to consume a WCF service using jQuery:

http://yoavniran.wordpress.com/2009/08/02/creating-a-webservice-proxy-with-jquery/

The post shows how to create a service proxy straight up in javascript.

poeticGeek
  • 1,001
  • 10
  • 14
3

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

1

In Java, this return value fails with jQuery Ajax GET:

return Response.status(200).entity(pojoObj).build();

But this works:

ResponseBuilder rb = Response.status(200).entity(pojoObj);
return rb.header("Access-Control-Allow-Origin", "*").build();

----

Full class:

@Path("/password")
public class PasswordStorage {
    @GET
    @Produces({ MediaType.APPLICATION_JSON })
    public Response getRole() {
        Contact pojoObj= new Contact();
        pojoObj.setRole("manager");

        ResponseBuilder rb = Response.status(200).entity(pojoObj);
        return rb.header("Access-Control-Allow-Origin", "*").build();

        //Fails jQuery: return Response.status(200).entity(pojoObj).build();
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131