Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous cross-domain POST request via JavaScript?

I could just create a form and use that to do a POST request to any site, thing is the FORM method isn't asynchronous, I need to know when the page has finished loading. I tried messing around with this using an iframe with a form inside, but no success.

Any ideas?

EDIT

unfortunately I have no control over the response data, it varies from XML, json to simple text.

like image 318
Luca Matteis Avatar asked Jan 21 '09 21:01

Luca Matteis


People also ask

How do I send a cross domain POST request via JavaScript?

This will become clear as you continue to read... Setup your cross domain POST from JS (jQuery example): $. ajax({ type: 'POST', url: 'https://to.com/postHere.php', crossDomain: true, data: '{"some":"json"}', dataType: 'json', success: function(responseData, textStatus, jqXHR) { var value = responseData.

How does JavaScript handle CORS policy?

Setting up a CORS policy Your browser applies the Same-origin policy as part of the web security model. To allow the browser to make a cross domain request from foo.app.moxio.com to sso.moxio.com we must set up a CORS policy on the target domain. The CORS policy is enforced by the browser.

How do I enable cross-origin requests in JavaScript?

The server can inspect the Origin and, if it agrees to accept such a request, add a special header Access-Control-Allow-Origin to the response. That header should contain the allowed origin (in our case https://javascript.info ), or a star * . Then the response is successful, otherwise it's an error.

What is cross domain request in JavaScript?

Cross-Domain JavaScript Requests allow developers to work around security restrictions that would prevent an application from contacting Places (Search) API directly. For example, certain location information might not be retrievable without enabling this method.


2 Answers

You can capture the onload event of an iframe. Target your form to the iframe and listen for the onload. You will not be able to access the contents of the iframe though, just the event.

Try something like this:

<iframe id='RS' name='RS' src='about:blank' onload='loaded()'></iframe>

<form action='wherever.php' target='RS' method='POST'>...</form>

script block:

var loadComplete = 0
function loaded() {
    //avoid first onload
    if(loadComplete==0) {
        loadComplete=1
        return()
    }
    alert("form has loaded")
}
like image 90
Diodeus - James MacFarlane Avatar answered Oct 21 '22 14:10

Diodeus - James MacFarlane


IF you want to make cross domain requests you should either made a JSON call or use a serverside proxy. A serverside proxy is easy to set up, not sure why people avoid it so much. Set up rules in it so people can not use the proxy to request other things.

like image 2
epascarello Avatar answered Oct 21 '22 13:10

epascarello