Loading external content into server on localhost - javascript

I am trying to create a web application that loads content dynamically. When I do this, of course I want to do the development locally, i.e. localhost. Some of the "functionality" is a form and when posting that form an e-mail is sent from the server. Because I want to access the servers e-mail functionality, I am linking that specific page to the server. But the problem is that it is not loaded.
In my script below it works, but if I change the comments so I am pointing to iandapp.com, than I just get empty string. It's exactly the same page, just copied it to the server.
$("#support").click(function () {
if(support_page==null){
//$("#section2").load("http://www.iandapp.com/smic/subscription_2.php", function(data) {
$("#section2").load("subscription_2.php", function(data) {
support_page = data;
});
}
The script is located inte the main page (index.html) and content should be loaded into a div with id="section2".
I know that (support_page==null) is true because I have a break point inside where it stops.
Please let me know what the probelm is and how I can fix it. I have been going on for hours trying to get this working.
Thanks in advance!

google about
cross domain ajax requests
. This is disabled in the browser level. There are ways to circumvent this, both client side and server side.

It probably has something to do with it being a cross-domain request. You could use what I consider to be a "hack", http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/, but I.M.O. it's not worth it.
Have you considered sending through an SMTP server instead? If so, you'd have no problem with the file (sending the mail) being local.

And what about adding proper headers on server's http response to allow crossdomain ?
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Origin: *

Use .getJSON() instead of .load(), this method supports cross-domain requests. You'll need to make sure your PHP script does something like the following:
echo $_GET['callback'] . '(' . json_encode($results) . ')';
jQuery will append something like ?callback=callback0234 to the request url because it wants you to 'call' the callback function when your script returns. So the output of your script may look something like:
callback0234('mydata': '<p>This is my data</p>')

Related

Redirect a specific url that is not found with javascript in header

I moved my website and I have a QR code (which is printed in public and can't be easily replaced) that points to a specific file on my old website that has now been moved. Currently, the URL just points to a "Not found" page on my new website. I try to use javascript in the header to catch the URL and forward it to the right URL as following:
<script type="text/javascript">
if(window.location.href === "https://www.website.com/multimedia/hoerproben/1.mp3")
{
window.location.href = "https://www.webseite.com/app/download/10079133850/1.mp3";
}
</script>
But it doesn't work. Any hints what I am doing wrong?
when you open an url, the browser makes an http request to your server for that particular resource (in your example, an mp3 file).
JavaScript is not involved at all (actually, there are so called "service workers", but they are not what you're looking for, they are meant to do caching, not redirecting). The browser does not know that your JavaScript code exists and would not execute it.
What you should do is route redirecting from server, so when the browser asks from /oldlocation/file.mp3, instead the server answers with /newlocation/file.mp3
This could be in some different way according to your server. If you have no control on how your server works, what you're asking is simply not possibile.
It won't work unless you place that code in the "Not found" page that gets served. If your URL pointed to an HTML file, you could have just placed one to do the redirect. For media files you would have to configure your server to serve an HTML file instead. Don't worry about the extension, it's the Content-Type header that determines the type of the file served. Doing this, however, is not good practice because your server would still be returning a 200 response code.
It's good practice to return 301 Moved Permanently as 101arrowz pointed out in the comments. How that can be accomplished will depend on what server you're using.
Here's how that would have been accomplished with express.js:
app.get('/multimedia/hoerproben/1.mp3', function(req, res) {
res.redirect('/app/download/10079133850/1.mp3');
});

block direct access to file but allow access through jquerys load function

I'm using jQuery to display a certain page to a user through it's .load() function. I am doing this to allow user customization to the website, allowing them to fit it to their needs.
At the moment, I am trying to display the file feed.php inside of a container within main.php;
I have come across a problem where I would like to prevent direct access to the file (i.e: going directly to the path of it (./feed.php)), but still allowing it to be served through the .load() function.
If I use the .htaccess deny from all method for this, I get a 403 on that specific part of the page. I can't find any other solution to this problem; disallowing me to achieve what I want.
This is my current (simplified) script and html:
<script type="text/javascript">
$("#dock-left-container").load("feed.php"); // load feed.php into the dock-left-container div
</script>
<div class="dock-leftside" id="dock-left-container"></div> // dock-left-container div
If anyone could suggest a solution through .htaccess, php, or even a completely different way to do this, I'd be very grateful!
Thanks in advance.
Please follow below steps to achieve:
In the .load function of jquery post a security code.
In the Feed.php page place a PHP condition if the posted security_code params found and match with security_code passed in the .load then only allow to access the page otherwise restrict.
Please follow below changes in your existing code to achieve it.
JS
<?php
$_SESSION['security_code'] = randomCode();
?>
<script type="text/javascript">
$("#dock-left-container").load("feed.php", {
security_code: '<?= $_SESSION['security_code']; ?>'
}); // load feed.php into the dock-left-container div
</script>
PHP
Place php condition in the top of feed.php
if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
//Feed.php page's all the stuff will go here
}else{
echo "No direct access of this page will be allowed.";
}
feed.php:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
readfile('myfeed.xml');
} else {
header('HTTP/1.0 403 Forbidden');
}
jQuery sends a HTTP_X_REQUESTED_WITH header by default. This is not, by far, anything remotely secure since HTTP headers are easily sent/spoofed. But it will stop the occasional user trying to access the feed directly.
You can, additionaly, check the $_SERVER['HTTP_REFERER'] header (but, again, this is easily spoofed) and, ofcourse, use your normal session logic to make sure the user is logged on if that's a requirement to access the feed.
Either way: there's no way to make this 'water tight'. If your browser can (should be able to) access the feed in some way then it's simply a matter of opening the debugger, having a look at the actual request sent in the network tab and sending the exact same headers/request to get to the file from, say, Curl. Actually, you will see the response of the request (i.e. the actual feed) in the debugger as well.
Repeat after me: if my (or a user's) browser can access the feed 'from jQuery' (via an AJAX request or whatever) then the feed is accessible to that user if he's even just a little bit more persistent than giving up immediately. Only using a session will keep out 'unauthorized' users because it relies on being logged in. After having logged in the request is visible no matter what and that request can be 'forged' to be sent from any other application no matter what.

Java script redirect with header

Let me try and explain as best as I can,
I have the following code in my login.php:
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
This ensures that if a user has logged in successfully, the url will always display mysite.com/home.php on all pages, this works fine for all php redirects using href="another_page".
However this does not work for javascript redirects using window.top.location.href="another_page", this instead redirects with the full url name (eg: mysite.com/java_redirected_page) instead of mysite.com/home.php. How can I get javascript redirects to work with headers as well, just like php does.
use this - window.location.href = 'home.php'; rather than window.top.location.href = 'home.php';
JavaScript is client side interpreter, it can't change headers from your server, while PHP generates responses from your web server, like Apache or nginx.
So the answer is that you can't change the way javascript redirects.
It looks like you want to have a nice result with your url, the only thing i can think of is MVC.
Never heard of it? Read this link http://code.tutsplus.com/tutorials/mvc-for-noobs--net-10488
Its just a nice way to seperate your Backend from your Frontend and with that your redirects would work nicely.
Sad part about is, you would have to rethink yoru whole page, which is pretty timeconsuming because you would have to restructre everything.
Hope it helps

How to parse html content using javascript or jQuery

Is there a way to parse html content using javascript?
I have a requirement to display only a div from some other site into my site. Is that possible? For example consider I want to show only div#leftcolumn of w3schools.com in my site. Is this even possible?
How can I do the same using javascript or jQuery?
Thanks.
You need to have a look at Same Origin Policy:
In computing, the same origin policy
is an important security concept for a
number of browser-side programming
languages, such as JavaScript. The
policy permits scripts running on
pages originating from the same site
to access each other's methods and
properties with no specific
restrictions, but prevents access to
most methods and properties across
pages on different sites.
For you to be able to get data, it has to be:
Same protocol and host
You need to implement JSONP to workaround it.
Though on same protocol and host, jQuery has load() function which you would use like this:
$('#foo').load('somepage.html div#leftcolumn', function(){
// loaded
});
Another possible solution (untested) would be to use server-side language and you don't need jsonp. Here is an example with PHP.
1) Create a php page named ajax.php and put following code in it:
<?php
$content = file_get_contents("http://w3schools.com");
echo $content ? $content : '0';
?>
2) On some page, put this code:
$('#yourDiv').load('ajax.php div#leftcolumn', function(data){
if (data !== '0') { /* loaded */ }
});
Make sure that:
you specify correct path to ajax.php file
you have allow_url_fopen turned on from php.ini.
your replace yourDiv with id of element you want to put the received content in
You will need to grab the HTML content with an HTTPRequest, then you can scrape the contents of the HTML you wish to show in your page. You would need to know some sort of server side language for this, unfortunately Ajax/jQuery will not work for this due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
what i can think of:
<div style="hidden" id="container"></div>
and then do sth like (shortcut # https://stackoverflow.com/a/11333936/57508)
var $container = $('#container');
$container.load('someurl-on-your-domain');
var $leftcolumn = $('div#leftcolumn', $container);
$leftcolumn.appendTo($sthother);
according to a comment: yes it is true, there's a same-origin policy (http://api.jquery.com/load/):
Due to browser security restrictions, most "Ajax" requests are subject
to the same origin policy; the request can not successfully retrieve
data from a different domain, subdomain, or protocol.
So why not create a proxy which is in your domain and then use the output of the proxy?! Hey, it's long-winded - true ... but it works :)
You would need to make a webservice to pull the code in. This is because you cannot pull the data in via JavaScript due to security restrictions. This is known as same origin policy and is linked elsewhere in this page.
You could use HtmlAgilityPack to parse it on the server side if you're working with asp.net technologies.
How to use HTML Agility pack
You would then be able to call the data from jQuery using .load():
http://api.jquery.com/load/
The idea being you load it into a hidden div such as:
$("#result").load("/webservice/pulldata.ashx");
and query it like you would any normal jquery element.
If you want to bypass XSS protection you can write your own server request and get info from it.
Example (php):
getContent.php
<? $fileContent = file_get_content("http://w3schools.com");
echo $fileContent; ?>
Then you can use whatever you want to modify this content (even before echo).
sample client script:
<div id="resultHtml"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#resultHtml").load("getFilecontent.php");
});

AJAX: problem with redirect

This is the first time ever I'm using AJAX, and I want to do the following on an otherwise static page www.xyz.org/some_site.html:
Send a GET request to another url "www.xyz.org/testscript"
if response has either status code != 200 or content != 'ok': do nothing
else: include sth on the website (i.e. set style="display:block" on an element that previously had "display:none")
I've implemented that successfully using basic AJAX. But:
There is an Apache redirect installed pointing from www.xyz.org/testscript to subdomain.xyz.org/testscript, the URL where the actual testscript lives (as AJAX doesn't support cross-domain calls even to subdomains afaik).
When I call www.xyz.org/testscript I get a 302 status code, and the content says "The document has moved here: subdomain.xyz.org/testscript".
How can I grab the 'final' return value?
I guess/hope any AJAX expert can give me a one-liner to solve that ...
AJAX (or XMLHttpRequest to be acurate) won't be tricked by a redirect. To be able to get content from another domain you need to use a proxy on the server. The following is a simple PHP proxy:
if(strpos($_GET['q'], "http://") === 0){
echo file_get_contents($_GET['q']);
}
use it like this:
xhr.open(GET, "www.xyz.org/proxy.php?q=subdomain.xyz.org/testscript", true);
The answer is, according to the comments above:
It's not possible to achieve what I want to do, as AJAX can't be tricked into following a redirect.
EDIT: I tried to solve it by adding another javascript file at subdomain.xyz.org/another.js and throwing all AJAX code from my static html site into it.
Then, on the static html site, I included this script with an ordinary
<script src="subdomain.xyz.org/another.js">
tag. But that wouldn't work either ... cheated myself: Including the javascript on my static page results in the original problem again (cross-domain calls forbidden).

Categories

Resources