12

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?

This is what I have so far using jQuery and ajax:

var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
           url: "http://" + environment + "/vizportal/api/web/v1/getViews",
           method: "post",
           dataType:'json',
           data: JSON.stringify(body),
           headers: {
            'Content-Type': 'text/plain',
            'X-XSRF-TOKEN' : XSRFToken,
            'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
           },
           success:function(response){
                alert("success");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            } 
        });

It is throwing a alerts that just says "Status:" and "Error:"

The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."

anton2g
  • 923
  • 6
  • 12
  • 29
  • Are you using any particular JavaScript libraries at the moment? – lintmouse Oct 23 '15 at 19:16
  • Using custom headers and running javascript from a file and not a server cause CORS issues (the no access origin error). You can get around some of these issues if you use IE. – Brian from state farm Oct 27 '15 at 18:01
  • **HTTP Error 405 Method not allowed** So change method to `POST`, also you don't need to do stringify because your body content already string, and change `Content-Type` to `application/json` – Ziki Nov 01 '15 at 16:08

5 Answers5

12

Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.

If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).

Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN

Mathieu Amiot
  • 1,204
  • 8
  • 16
2

You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.

It would be something like that:

$("#ButtonForm").click(function(){
$.ajax({
        url:(Your url),
        dataType:'json',
        type: 'post',
        data: yourForm.serialize(),
        success:function(response){
              ** If yout API returns something, you're going to proccess the data here.
        }
    });
});

Ajax: http://api.jquery.com/jquery.ajax/

  • Thanks. I tried that and it didn't work. I put my code and results in my question. – anton2g Oct 23 '15 at 19:33
  • 1
    That varible body, it was already in JSON before you did the `.stringify()`?? – Arthur Medeiros Oct 23 '15 at 19:36
  • right, sorry. The var body is this: var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxItems":5}}}'; – anton2g Oct 23 '15 at 19:51
2

You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.

Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.

My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.

Fluster
  • 133
  • 1
  • 9
1

If you use jquery, use .post, or .ajax, to submit

$.post(url, data, callbackSuccess, callbackError);

more about these methods here http://api.jquery.com/jquery.ajax/

example:

var url = 'http://example.com/path/endpoint';

$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
    // callback success
}, function(response) {
    // callback error
});
danwellman
  • 9,068
  • 8
  • 60
  • 88
1

When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.

Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/

var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
           url: "http://" + environment + "/vizportal/api/web/v1/getViews",
           method: "post",
           dataType:'jsonp',
           data: JSON.stringify(body),
           headers: {
            'Content-Type': 'text/plain',
            'X-XSRF-TOKEN' : XSRFToken,
            'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
           },
           success:function(response){
                alert("success");
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            } 
        });
Mitul
  • 3,431
  • 2
  • 22
  • 35