How to use iframe to (cross-domain) post request ? - javascript

I want to do a post cross-domain request , I use a form which targeted a iframe to submit the request.
var iframe = document.createElement("iframe");
var uniqueString = "CHANGE_THIS_TO_SOME_UNIQUE_STRING";
document.body.appendChild(iframe);
iframe.style.display = "none";
iframe.contentWindow.name = uniqueString;
var form = document.createElement("form");
form.target = uniqueString;
form.action = myUrl;
form.method = "POST";
// repeat for each parameter
var input = document.createElement("input");
input.type = "hidden";
input.name = "setting";
input.value = params;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
iframe.onload = iframe.onreadystatechange = function(){
if(this.readyState && this.readyState!="complete") return ;
else{
alert("haha");
}
};
The Chrome shows iframe has receive the returned data from remote url, but i cannot get the iframe content using Javascript ? Do you guys have any advices or solutions ?

You should add a parameter to the form with a GUID. There server should save in the session the GUID with the specific answers.
After that you send the form you call the server via JSONP with the GUID that you used in the server and the server should return the asnwers that it saved in the session.

Related

How to redirect to another page through JS (sending parameters)

I'm trying to redirect to another page through JS(sending parameters)
I made the following code to that purpose, it does redirect and the requested page loads up 'ok'
window.location.replace(`http://10.0.30.11:3000/ProteseWEB/pages/detail/${path}?id=${param}`)
The problem is: When the requested page opens, it display an 404 not found on the network tab.
I don't understand why this is occuring, since the page I want is loaded 'perfectly'
The error on the network tab:
Edit(1)
#jlemley and #James Thank you for your answer!!!
Indeed the 404 request and the URL that I requested were different. So I changed the function a little bit.
Here's the code:
openPageDetail = function (path, params, method = 'POST') {
let iplocal = 'http://10.0.30.11:3000/ProteseWEB/pages/detalhe/'
const form = document.createElement('form');
form.method = method;
form.action = iplocal + path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
I tried to make it as a form submit, still, the error occurs
In addition, there's how I call for this function.
I have a DataTable and when the user double click a row, it opens up a detail page for the desired record.
$('.table').on('dblclick', function(e) {
if ((!(e.target.classList.contains('sorting_asc'))) && (!(e.target.classList.contains('sorting_desc')))) {
openPageDetail('contas-a-pagar', {
id: e.target.parentElement.id
});
}
});

JS: submitting POST raw data (not KVP) into a new tab

I'm looking for a way to submit raw data, in POST, to a new tab.
Something to the extent of:
var form = document.createElement('form');
form.target = '_blank';
form.method = 'post';
form.action = 'https://example.com';
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'data'; // without this part*
input.value = 'some data';
form.appendChild(input);
form.submit();
only without the KVP format.
i.e. when calling fopen('php://input', 'rb'); I want to get
'some data'
and not
'data="some data"'
Most importantly, I want to pass the data to a new tab and not get the response in AJAX

Attempting to Post String to PHP dynamically

Using JavaScript only I want to POST a string to php file and redirect to it at the same time, however, my php file is not picking up the information.
JavaScript:
var data = "&id=" + obj.id;
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
form.value = data;
document.body.appendChild(form);
form.submit();
};
redirect("summary.php","POST");
And the PHP code is simply (NO ERROR HERE, JUST FOR CONVENIENCE):
$id = $_POST['id'];
EDIT:
The problem is that the PHP file is not picking up the name "id". There is no problem in the php file or how I structure my data.
You made a small typo. ALthough it is a huge problem. In PHP you create variables using the $ sign.
var data = "id=" + obj.id;//you don't necessarilly need the & as you are only passing one item(value)
var redirect = function(url, method) {
var form = document.createElement('form');
form.method = method;
form.action = url;
//form.value = data;//this won't work. form does not have value attribute:
//create input element
var i = document.createElement("input");
i.type = "text";//set type.
i.name = "id";//set name of the input
i.id = "id";
i.value = obj.id;//set value of input
form.appendChild(i);//add this input to the form
document.body.appendChild(form);//add the form to the body
form.submit();//dynamically submit
};
redirect("summary.php","POST");
In your php script, access it like
<?php
error_reporting(E_ALL);//show all errors and notices
$id = $_POST['id'];//you forgot the $ sign
//for debugging, check the post array
print_r($_POST);
?>
EDIT:
Make sure the obj.id is not null
That's not how you pass the data. value is a property of a form's input element, not the form itself.
So remove the line form.value = data; and replace with
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'id';
input.value = obj.id;
form.appendChild(input);
Now you should be able to get $_POST['id'].

Form submission in new window using Javascript not working in Firefox

I've an internet firewall login and to prevent login timeout and keep logged in I want to send POST login request using JavaScript in a new Window every 30 seconds or so.
The following function is working in Chrome but not in Firefox. What could be the reason?
function callback(data) //this keeps getting called every 30 secs from Ajax response
{
if (data && data.login && data.passwd)
{
w = w || window.open('', 'formresult', 'scrollbars=no,menubar=no,height=100,width=100,resizable=yes,toolbar=no,status=yes');
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", 'http://firewall:8090/login.xml');
form.setAttribute("target", "formresult");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "password");
hiddenField.setAttribute("value", data.passwd);
form.appendChild(hiddenField);
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "username");
hiddenField.setAttribute("value", data.login);
form.appendChild(hiddenField);
w.document.body.appendChild(form);
form.submit();
}
}
if I change
w.document.body.appendChild(form);
to
document.body.appendChild(form);
then Firefox is appending the form in the main window and not in the opened one.
EDIT: I see "Error: Permission denied to access property 'document'" in the Firefox console
This is an old question, but the question "Form submission in new window using Javascript not working in Firefox" still has relevance. In order for the form submit to work properly and open in a new window, you need to do the following:
attach the form to the DOM (document.body)
set the target attribute on the form to '_blank'
var form = document.createElement('form');
var input = document.createElement('input');
form.target = '_blank';
form.action = data.websiteUrl;
form.method = 'post';
input.name = 'username';
input.value = 'myUserName';
document.body.appendChild(form);
form.appendChild(input);
form.submit();
As to pinging the server every 30 seconds.. there has to be a better way to achieve what you are trying to do instead of doing a form post.

POST Request (Javascript)

How do you make a simple POST request in Javascript without using a forms and without posting back?
Though I am taking the code sample from #sundeep answer, but posting the code here for completeness
var url = "sample-url.php";
var params = "lorem=ipsum&name=alpha";
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
You can do this using AJAX calls (XMLHttpRequest object)
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
I have made a function that send a request without refresh the page, without open a page and without AJAX. The proccess is invisible to the user. I use a false iframe to send a request:
/**
* Make a request without ajax and without refresh the page
* Invisible for the user
* #param url string
* #param params object
* #param method string get or post
**/
function requestWithoutAjax( url, params, method ){
params = params || {};
method = method || "post";
// function to remove the iframe
var removeIframe = function( iframe ){
iframe.parentElement.removeChild(iframe);
};
// make a iframe...
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function(){
var iframeDoc = this.contentWindow.document;
// Make a invisible form
var form = iframeDoc.createElement('form');
form.method = method;
form.action = url;
iframeDoc.body.appendChild(form);
// pass the parameters
for( var name in params ){
var input = iframeDoc.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
}
form.submit();
// remove the iframe
setTimeout( function(){
removeIframe(iframe);
}, 500);
};
document.body.appendChild(iframe);
}
Now you can do it:
requestWithoutAjax('url/to', { id: 2, price: 2.5, lastname: 'Gamez'});
See how works!: http://jsfiddle.net/b87pzbye/10/.

Categories