Asynchronous cross-domain POST request via JavaScript? - 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.

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")
}

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.

If the data returned from the cross domain post is JSON, then you can dynamically add a script tag pointing to the URI that returns the data. The browser will load that "script" which then you can access from other javascript.

YUI3's IO object offers cross-domain requests, however it does so using a small Flash control it embeds on the page.
While there is work going into secure cross-domain requests from JavaScript, at this time, you need to use a plugin like Flash or Silverlight as a bridge with which to make the request.

You can't do anything cross-domain using javascript. You'd have to use a backend language like PHP or asp or something.

Related

implement post url in IFrame

How can I make a POST request to some URL (see my code below) in Javascript ?
My code so far doesn't work and I actually need to put it into an iFrame (having its with and height set to 0) to prevent the main page to reload.
$(document).ready(function(){
$("button").click(function(){
$.post(
"http://control.msg91.com/api/sendotp.php?otp_length=4&authkey=xxx&message=Your OTP is ##OTP##&sender=OTPSMS&mobile=xxx&otp_expiry=2"
, function(data){
alert(data);
});
});
});
If you want to use an iframe, then do not use XMLHttpRequest (NB $.post is a jQuery that wraps around XMLHttpRequest).
Create a <form>. Set its action to the URL. It's method to POST and its target to the ID of the <iframe>.
Put the data in that form. Then submit it.
If you want to do this entirely with JavaScript, then you can create the form using DOM and with entirely hidden inputs so that nothing shows up in the existing page. Ensure that you append the form to the document as some browsers will not let you submit forms that aren't part of the document.
That said, since you want an iframe with no dimensions, it seems odd to want to use an iframe at all.
You might be trying to work around CORS limitations, but you should be able to use the code you are using to make a request successfully. You just won't be able to tell if it was successful or not (because the restrictions are on reading the response). If you used an iframe, you would have the same limitations.
If you want to suppress the error message that is shown in the console, you could use fetch with mode: "no-cors". You still wouldn't be able to read the response though.
Make sure you are not hitting an issue with CORS. Unless the resource you are hitting allows exceptions to the cross-origin policy, you will not be able to access it if your webpage is not located on control.msg91.com.

How to wait for an HTML page and get result when page complitely created?

I have a page (page1.html) and I want to send an ajax to page2.html (http://m-kermani.github.io/getapp.html) and page2.html has an iframe that made by javascript
I made it by javaScript because I need to send a parameter to the page3
In page1.html I have:
$.get('https://m-kermani.github.io/getapp.html', function (data) {
alert(data);
});
and I just need the iframe content but beacuse it made by JavaScript I can't get it and that did not created! (This is the way JavaScirpt is)
I need to send ajax request and get the iframe content because I need an https domain for some reasons that GitHub.io is!
No I need to know is there anyway I can get the content of the iframe from GitHub page?
Is there any other way I can direly just have GitHub page and give the parameter to it and can get the content of the page3 (not using server side language)?
And suggestion about what can I do?
Sounds like you're trying to circumcent the same-origin policy. Unless the API you're trying to access specifically supports a way to do it (CORS, JSONP, etc), you can't do it. You should read the documentation of the API you're trying to access to see if they support accessing it from the client side.
An Ajax request is just a request for a resource. It just gets whatever the server is going to send. It doesn't automatically render the HTML and fetch dependant resources.
If you want the content of a frame, then you have to request the URL for the frame instead of the URL for the page with the <iframe> tag in it.
(The Same Origin Policy will still apply).

Send a post request with an Electron webview

I want to send a POST request with an Electron webview from the outer script. At the moment I just set the src attribute to trigger a page load, which sends a GET request:
<webview id="view">
<script>
document.getElementById('view').setAttribute('src', 'http://example.com/?foo=bar');
</script>
Is there any way to navigate the webview to a URL by sending a POST request? Maybe a method of the webview, instead of just hacking with the src?
You can execute arbitrary code from within the webview context with .executeJavaScript.
Moreover your code has access to all browser built-in apis. Easiest would be to use fetch, with method set to post.
In your case (provided the webview has been already loaded; for example its .src has been set):
document.getElementById('view')
.executeJavaScript('fetch("http://example.com/?foo=bar", {method: "post"});');
Some remarks:
The origin of the request is controlled by .src of the webview.
It seems that all default security policy are still used by webview - specifically you cannot make calls to http: from https:.
It is bit painful to pass code as a string.
Now there is a new <webview>.loadURL() method with a postData option in the docs. I haven't used it yet but it looks exactly like what I was looking for in the past.
It seems they added it as a feature in the meantime.
Basically, Webview element does not have a property like "method" of Form so you can not specify a particular HTTP method for its request. I recommend you to use AngularJS or any other JS frameworks to archive your purpose.
I found two workaround since <webview> does not seem to currently have any way to send a POST request.
Maybe the site you're using will let you send the form as a GET by adding any form elements to the URL's query string. It turns out the site I was using did allow this and I wouldn't've guessed had I not actually tried.
You might be able to send a POST manually through AJAX/fetch etc then replace the HTML of the page in the webview with the HTML returned by your manual POST. You can achieve this using .executeJavaScript() and/or Electron's IPC.
Neither workaround will work in every case. It might be worth filing a feature request with the Electron team too...
So I just went ahead and submitted a feature request. You can follow it here: https://discuss.atom.io/t/add-http-post-method-to-webview/29702

How to save an ajax response in firefox

I need to find a way to write ajax responses to a file. The responses are XML strings, which is more than fine by me.
What I would like to do, is click on something in my webpage, and save the XML that is returned to a file.
But since I know, that Javascript can't access local files by itself, it is also possible to just send the data on to another server, where PHP would take care of this.
Now the place where I'm stuck is the javascript and the interception. I know, that some of this can be done using greaseMonkey in Firefox. If so, how? Thanks!
Edit: Some explaining.
The script that creates the output is not written by me.
Yes, I could see the data in Firebug, seeing is one thing. I need to interpret the data
There are a lot of requests going on here. About 1 every 2 seconds, so copying them by hand isn't an option.
Still, help?
You should provide more details, a link to the target page is best.
Is the page using jQuery?, Some other library?, or custom XMLHttpRequest() calls?
Anyway, a simpler approach may work, try it first...
If the AJAX data is being written to the page, attach a DOMSubtreeModified event listener to the container element. Something like:
document.getElementById ("ContainerID").addEventListener ("DOMSubtreeModified", YourFunction, false);
function YourFunction () {
//--- Get the target node's inner HTML and send it to our server.
}
Note that DOMSubtreeModified events work fine in FF and Chrome, the two main browsers for Greasemonkey.
If the data is not being written to the page, then the best way to intercept the AJAX depends on if the target page is using a library like jQuery.
A generic way to intercept AJAX can be seen in this SO question (and others).
As you said, once you have the data, to automatically write it to a file, use GM_xmlhttpRequest() to send it to a server that you control.
Why cannot you do it like this?
Save AJAX response to file on the server side and then provide a link to it, so it can be downloaded.
Firebug will also help, you can view in very convenient way each response in few formats, and eventually copy/save it.
Use a normal (non-AJAX) request and add a Content-Disposition: attachment; filename="foo.xml" header to the response.
If you're just going to save the XML, why are you using AJAX? Just set location.href to the location of a PHP script that sends a "Content-disposition: attachment" header and gives the XML in the response body. AJAX seems totally the wrong tool for the job.

AJAX request status returns 0

when i make a AJAX request with this code, it returns the status as 0. what did i do wrong? Also, this code is only designed to work in Firefox for various reasons.
var ajax;
function connectToOtherServer(server,port,userid,password){
ajax=new XMLHttpRequest();
ajax.onreadystatechange=validateConnection;
params='userid='+encodeURIComponent(userid)+'&password='+encodeURIComponent(password);
alert('http://'+server+':'+port+'/ok.txt');
ajax.open('POST','http://'+server+':'+port+'/ok.txt',true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.setRequestHeader("Content-length",params.length);
ajax.setRequestHeader("Connection","close");
ajax.send(params);
}
function validateConnection(){
if(ajax.readyState===4){
if(ajax.status===200){
alert(ajax.responseText);
}else{
alert(ajax.status);
}
}
}
If you try to connect to another server, the same origin policy will stop you:
The term "origin" is defined using the
domain name, application layer
protocol, and (in most browsers) TCP
port of the HTML document running the
script. Two resources are considered
to be of the same origin if and only
if all these values are exactly the
same.
jquery.com You can only connect to another server if you use JSONP and a callback. The other server will need to support the JSONP/callback mechanism. This method involves creating a new script tag then having the remote server return the callback code into this script tag. Look at the jQuery source code (or simply use it) to see it handles JSONP.
The basic idea is to create a script tag with the source as the remote URL. The remote method returns a "script" containing a function call using the callback and the resultant JSON data.
I've recently run into this issue. I've been using AJAX to submit form results so that page elements can update automatically. My domain calls were correct. SELECT statements on the database would work, but INSERT, UPDATE, and DELETE statements would not.
Alerts showing progress through the javascript indicated that the call was running correctly, but it would never make it to the php portion of the process. The simple answer was that the form's onsubmit element needed to include return false;. After adding that, the things ran smoothly.
<form name="form" action="" method="post" onsubmit="ProcessRequest(this);return false;">
Hope this helps.

Categories