How to load a remote content into a dialog box with jquery? - javascript

I'm trying to load a remote content of my site with jquery, but I constantly get an error:
XMLHttpRequest cannot load
'anylink_here'
Origin null is not allowed by
Access-Control-Allow-Origin.
Here is my code:
jQuery(function(){
$('#checkout').submit(function(e){
//prevent default behavior and hide possibly existing pop-up
e.preventDefault();
//process request
var form = this;
var url = form.action;
var dialog = $('<div id="lightbox_dialog"></div>').appendTo('body');
// load remote content
dialog.load(
url,
function (response, status, xhr){
dialog.html(response);
});
dialog.dialog();
//prevent the browser to follow the link
return false;
});
});
And a form code:
<form id="checkout" action='http://me.me/' method='get'>
<input type="image" class="class1" onclick="this.form.action='http://en.wikipedia.org/wiki/Sample'" title="Title" value="" src="http://4cornersautoloan.com/images/SmallButton.gif">
</form>
I also need to do it for the same domain but from http to https.

This is not possible basically because ajax doesn't support cross-domain request and http to https will be regarded as one.

You will need server-side code on your same domain to perform the fetching for you.

How about iframing it in?
<body>
<p id="open">Click to open</p>
<div id="dialog" title="window title">
<p><iframe src="popup.html" ></iframe></p>
</div>
<script>
$('div#dialog').dialog({
autoOpen : false,
show : "scale",
hide : "scale",
});
$('#open').click (function (event)
{
if ($("#dialog").dialog("isOpen"));
else $("#dialog").dialog("open");
});
</script>
</body>
</html>

Related

Express GET request not reloading page

I'm trying to send the client the next HTML page (create.html) as a response to a GET request (fired by button) using fetch. I am purposely trying to avoid using a form due to formatting issues and potential future scaling issues. The code registers that the request is sent, received, and is responded to with the file but it simply does not reload the page with it. *res.redirect does also not work. I've attached my code bellow.
JavaScript:
app.get('/', function(req, res) {
console.log(`[00]: Get request recieved at '/'`);
res.sendFile('public/start.html' , { root : __dirname});
})
app.get('/login', function(req, res) {
console.log(`[01]: Get request recieved at '/login'`);
res.sendFile('public/login.html' , { root : __dirname});
})
app.get('/create', function(req, res) {
console.log(`[02]: Get request recieved at '/create'`);
res.sendFile('public/create.html' , { root : __dirname});
})
HTML:
<html>
<head>
<meta charset="utf-8">
<title>HOME PAGE</title>
</head>
<body>
<h1 id='title'>Welcome User!</h1>
<h2>Select an option bellow!</h2>
<button id="btnToLogin">Login</button>
<button id="btnToCreate">Create Account</button>
<p>-ADMIN PANEL-</p>
<button id="btnDisplay">Display Database</button>
<button id="btnTruncate">Truncate Database</button>
<p id='displayText' >[displayText]: Nothing seems to be here...</p>
<script src="start.js"></script>
</body>
</html>
HTML JavaScript:
// Gets elements from start.html
var btnToLogin = document.getElementById('btnToLogin');
var btnToCreate = document.getElementById('btnToCreate');
var btnDisplay = document.getElementById('btnDisplay');
var btnTruncate = document.getElementById('btnTruncate');
var displayText = document.getElementById('displayText');
btnToLogin.addEventListener('click', function() { fetch('/login', { method: 'GET' }) });
btnToCreate.addEventListener('click', function() { fetch('/create', { method: 'GET'}) });
I've cut out most of my code, just unnecessary for the problem I believe. Everything is required properly and server is set up. And incase it matters i've attached a picture of the file structure. Thanks.
File Structure
Fetch performs and gets the data in background. res.redirect redirects a request. And you are sending the request via fetch. Not address bar. In order to do that, you need to use location.href instead of fetch
btnToLogin.addEventListener('click', function() { location.href = '/login' });
btnToCreate.addEventListener('click', function() { location.href = '/create' });

recaptcha doesn't show up in phantomjs if there is no iframe element with specific content

I'm trying to scrape a page with recaptcha widget using phantomjs but when I get the page it has no captcha image.
If I add an iframe element to the page, the image shows. The weirdest thing is that the image only appears if you make an iframe with specific content.
Here is the html code that I used to test (it's the normal code from recaptcha docs with the iframe element)
<form action="" method="post">
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6LfUUtMSAAAAAOBuPTWtMAnAu3l9AS-iHZb6iFpp&error=">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=6LfUUtMSAAAAAOBuPTWtMAnAu3l9AS-iHZb6iFpp&error=" height="300" width="500" frameborder="0"></iframe>
<br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge">
</noscript>
</form>
<iframe src="frame.html"></iframe>
The iframe refers to the page frame.html and here is the "specific code" of it
<a><img src='http://c'></a>
If you tried to change the content of the frame.html a little bit you'll probably not get the captcha image.
The PhantomJS script that I used is this:
var url = 'http://127.0.0.1/php_api/recaptcha.html';
var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0';
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var p = page.evaluate(function () {
return document.getElementById("recaptcha_challenge_image").src;
});
console.log(p);
}
phantom.exit();
});
This is the first time I use PhantomJS so is there something I'm missing?
This has nothing to do with the additional iframe that you have on your page. The recaptcha script isn't loaded when the page.open callback is called. It hasn't created the reCaptcha table and hasn't loaded the captcha image. This is a timing issue.
You can wait a static amount of time with setTimeout or use waitFor to wait until the image is present.
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
setTimeout(function(){
var p = page.evaluate(function () {
return document.getElementById("recaptcha_challenge_image").src;
});
console.log(p);
phantom.exit();
}, 5000);
}
});
Don't forget that phantom.exit should also be called after the timeout otherwise you just exit prematurely.

Paypal lightbox: does not permit cross-origin framing

I have attempted to go about the use of Paypal Lightbox a bit differently.
I have used a button to trigger an ajax call which then generates the PayKey and if all goes well then triggers the form (from the documentation) to be created and submitted.
When i click the button the lightbox html is created but the content is not loaded into it. Instead i get the error:
Load denied by X-Frame-Options: https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_dispatch-failed does not permit cross-origin framing.
My Code:
<head>
<script src="https://www.paypalobjects.com/js/external/dg.js" type="text/javascript"></script>
</head>
External Script:
$("#checkout").click(function() {
var id = $(this).data("id");
if(id) { pay(id); }
});
function pay(id) {
$.ajax({
url : 'paypal/Pay-Chained.php',
type : 'POST',
data : "id="+id,
success : function (data) {
var info = (JSON.parse(data));
if (info['Type'] == 'Success') {
var output = info['URL'].substr(0, 64) + "expType=light&" + info['URL'].substr(64);
$("body").append('<form action="'+output+'" target="PPDGFrame" class="standard"><input type="submit" id="submitBtn"></form>');
$("#submitBtn").click();
} else {
alert("Error: Please try again or contact support.");
}
},
error : function () {
alert("Error: Please try again.");
}
});
}
At the bottom of the buttons page:
<script type="text/javascript" charset="utf-8">
var embeddedPPFlow = new PAYPAL.apps.DGFlow({trigger: 'checkout'});
</script>
I am thinking maybe it has to do with the order things are executed but can't seem to figure it out. Any help would be great!
EDIT: I just created a blank page and copied the script from the documentation exactly. I still get the same error. Might it have something to do with server settings? I am running a WampServer with an address like 192.168.1.1/mysite/index.html.

Google Chrome Extension POST VS GET

This is my code
chrome.windows.create({'url': "http://example.com/upload/upload.php?pictureID="+ theResponse + "&userID=" + localStorage["id"]+"&username="+ localStorage["mainLogin"]}, function(tab) {
// open window
});
this constructs a URL that looks like:
http://example.com/upload/upload.php?pictureID=123&userID=1&username=jack
I would call this method GET -- like how forms GET or POST
How can I open a window with POST data rather than GET data?
I think you have to write a HTML page that creates a form containing your POST data and target URL and submit the form.
Here's a simple example:
<html>
<head>
<script>
document.addEventListener('DOMContentLoaded', function()
{
location.search.substr(1).split('&').forEach(function(item)
{
var input = document.createElement('input');
input.type = 'hidden';
input.name = item.substr(0, item.indexOf('='));
input.value = item.substr(item.indexOf('=') + 1);
document.getElementById('postform').appendChild(input);
});
document.getElementById('postform').submit();
});
</script>
</head>
<body>
<form action="http://example.com/upload/upload.php" method="post" id="postform">
</form>
</body>
</html>
Say that's test.html in your extension's root directory. Call
chrome.windows.create({'url': "test.html?pictureID="+ theResponse + "&userID=" + localStorage["id"]+"&username="+ localStorage["mainLogin"]}, function(tab) {
// open window
});
will open the website with POST method.

How to send web browser a loading page, then some time later a results page

I've wasted at least a half day of my company's time searching the Internet for an answer and I'm getting wrapped around the axle here. I can't figure out the difference between all the different technology choices (long polling, ajax streaming, comet, XMPP, etc.) and I can't get a simple hello world example working on my PC.
I am running Apache 2.2 and ActivePerl 5.10.0. JavaScript is completely acceptable for this solution. All I want to do is write a simple Perl CGI script that when accessed, it immediately returns some HTML that tells the user to wait or maybe sends an animated GIF. Then without any user intervention (no mouse clicks or anything) I want the CGI script to at some time later replace the wait message or the animated GIF with the actual results from their query.
I know this is simple stuff and websites do it all the time using JavaScript, but I can't find a single working example that I can cut and paste onto my machine that will work in Perl.
Here is my simple Hello World example that I've compiled from various Internet sources, but it doesn't seem to work. When I refresh this Perl CGI script in my web browser it prints nothing for 5 seconds, then it prints the PLEASE BE PATIENT web page, but not the results web page. So the Ajax XMLHttpRequest stuff obviously isn't working right. What am I doing wrong?
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub Create_HTML {
my $html = <<EOHTML;
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />
<script type="text/javascript" >
var xmlhttp=false;
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
</script>
<title>Ajax Streaming Connection Demo</title>
</head>
<body>
Some header text.
<p>
<div id="response">PLEASE BE PATIENT</div>
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
print Create_HTML();
sleep(5);
print "<script type=\"text/javascript\">\n";
print "\$('response').innerHTML = 'Here are your results!';\n";
print "</script>\n";
If your process relies on query-string parameters, a simple meta-refresh would suffice. E.g. if they load http://yoursite.com/message?foo=1, then that can output a meta tag like:
<meta http-equiv="refresh" content="0; http://yoursite.com/realquery?foo=1" />
And some HTML that has your "please wait" message. The realquery script would actually execute the query and the HTML output by message will remain on the screen until realquery provides some output.
If the query relies on POST data, then it gets a little more complicated, because you can't redirect a POST. You can, however, output a form with some hidden fields and use Javascript to submit it. For example:
<script type="text/javascript">
window.onload = function() {
document.getElementById( 'form_with_hidden_fields' ).submit();
}
</script>
<form method="POST" action="realquery" id="form_with_hidden_fields">
<input type="hidden" name="foo" value="1" />
...
</form>
Please wait while your query is processed...
If you're interested in an AJAX solution, here's an example using jQuery:
$( '#submit-button' ).click( function() {
// show a "please wait" image
$( '#status-div' ).html( '<img src="please_wait.gif" />' ); // animated gif
// get form values
var formdata = { foo: $( 'input#foo' ).val(),
...
};
// submit form via ajax:
$.ajax( { type: "POST", url: "/realquery", data: formdata, success: function() {
$( '#status-div' ).html( '<img src="success.gif" />' );
} );
} );
And you could attach that to a form like:
<form>
<input type="text" name="foo" id="foo" />
<input type="submit" id="submit-button" />
<div id="status-div"> </div>
</form>
The empty status-div div will receive an image tag that points to a "please wait" image (this can be an animated gif). When the Ajax query finishes, it's replaced by a "success" image.
See Watching long processes through CGI by Randal Schwartz.
Here is a complete working example using friedo's HTTP meta refresh solution. This is not my personal first choice solution because it modifies the URL in the browser and it also refreshes the whole web page.
#!C:\Perl\bin\perl.exe
use CGI;
use CGI::Carp qw/fatalsToBrowser warningsToBrowser/;
sub html_page {
my ( $meta_string, $results_string ) = #_;
my $html = <<EOHTML;
<html>
<head>
$meta_string
<title>Two Stage Web Page Demo</title>
</head>
<body>
Some header text.
<p>
$results_string
<p>
Some footer text.
</body>
</html>
EOHTML
return $html;
}
my $cgi = new CGI;
print $cgi->header;
if ($cgi->param()) {
if ($cgi->param('doResults') eq "true") {
sleep(5);
print html_page('', 'Here are your results!');
}
}
else {
my $meta_refresh = '<meta http-equiv="refresh" content="0; /cgi-bin/twoStageScript.pl?doResults=true" />';
print html_page($meta_refresh, 'PLEASE BE PATIENT');
}
exit;
Finally got an Ajax version working. The slow.pl file is the file that takes a while to return.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Two Stage web page demo using Ajax</title>
</head>
<body>
<h1>Two Stage web page demo using Ajax</h1>
<div id="result">
Users input form goes here.
<p>
<input type="submit" value="Here is your submit button" id="load_basic" />
</div>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
var ajax_load = "Please be patient, this could take a while. <p> <img src='img/load.gif'/>";
// load() function
$("#load_basic").click(function(){
$("#result").html(ajax_load).load("/cgi-bin/slow.pl");
});
</script>
</body>
</html>

Categories