Secure AJAX div update - javascript

I'm pretty new to AJAX so forgive me if this is a dumb question:
I would like to update a div with the content of a php-file which lies within a protected folder so it only can be included within a php-file but not adressed from the browser.
Since JavaScript is client-side this would mean I couldn't call it, right?
For example I got my index.php with the following code (jQuery included):
<script>
$("#content").load("includes/login.php");
</script>
Where #content refers to a div. This works fine but as includes should not be accessible it becomes problematic.
Then I thought I could put something like a "wrapper.php" in the accessible area which then includes the specific php-files depending on which variables you give it.
Is this the correct way to approach this or am I doing it wrong?

I think the idea of a "wrapper.php" is right. If you want to use it for many files you could do something like this, checking if it is an AJAX call to prevent direct load of the file:
// wrapper.php
<?php
// Check if it is AJAX
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
$filename = $_GET['f'];
include 'includes/'.$filename.'.php';
}
And then:
$("#content").load("wrapper.php?f=login");
But be carefull with this, because it may be insecure.

If you want to be lazy, you could just load the entire page via load and parse the content to fetch #content
jQuery will split the argument by the space and use the second element as a selector for the entire page content.
$("#content").load("full/path/to/login #content");
No haters, I said it's a lazy method.

Related

Not able to move my inline JavaScript to an external file

I finished developing and testing my HTML intake form and it is working nicely with ajax, json, and validation, and mailing. To finalize the form for production, I attempted to move the JavaScript from the HTML page to an external file and provide a link to the file in the HTML page. The js file is called formjs.js, and the link to it was placed at the bottom of the HTML page as <script src="../js/formjs.js"></script>.
The way I moved the JavaScript is cutting the scripts and pasting to the new js page and same the page and linked to it in the HTML page as mentioned above.
Upon doing so, I received tons of error messages on the js page because many of the functions are looking for information that exists on the HTML and had no idea how to get it. For example, a document. For example, this following script:
var Server_response_value_failure = document.getElementById("server_response_value_failure");
gets the following error:this variable is assigned and value but was never used.
Another example:
end of function};
at the end of each function get the error message that unnecessary semicolon.
I am not sure how to link the formjs.js file back to the HTML. Otherwise, the form works perfectly fine if I leave the script on the HTML page.
its fine, its just eslint that gives these warnings. for example, it will complain if you declare a variable and assign a value but you dont use the variable later on.
or if you call a function that you declare "later down" in the file.
I don't know if this will help, but sometimes you want to put the entire body of your javascript file in round parenthesis like this
(function(...) {
...
})();
in the end, you put another round parenthesis. This basically acts like $.ready() in jQuery.
I don't know if this will help you. You might want to rewrite your code.

What is the best practice for the multiple use of the same link?

I'm trying to rationalize a website, and I have many links on it to the same document, so I want to create a JavaScript that return the URL of this document. This way, i could update the document and only have to change the URL in the function, not in all the occurrences of the link (it's a professional and internal website, with many links to official documents, that get updated often, out of my control, and each time i get to update links, i realize a while after that i forgot some, even by searching in all html files. the site is messy, was poorly written by many people, and that's why i'm trying to simplify)
My first idea was to use link, but everyone says it's a bad practice. i still don't see why, and I don't like to use the onclick as it doesn't work with middle click, and i want to let users decide how they open the doc.
Also, I want to use link to redirect to a specific page.
on top of this, what i tried so far is not working like I intend, so i would need some help, whether to come up with a better solution, or to make this work!
here is my js, with different versions:
function F_link_PDF() {
// i was pretty sure this would work
return "http://www.example.com/presentation.pdf" ;
}
function F_link_PDF_2() {
document.write("http://www.example.com/presentation.pdf");
}
function F_link_PDF_3() {
// i don't like this solution, as it doesn't open as user intended to
location.href = "http://www.example.com/presentation.pdf" ;
}
this example is for a pdf document, but i could also need this for html, doc, ppt...
and finally, i started with js because i'm used to, but I could also use other languages, php, asp, if someone says it's a better option
thanks in advance!
The hack way: Go about using JavaScript, however you run into potential issues with browsers not running it.
The better way: Use mod_rewrite / .htaccess to redirect previous (expired) requests to the new location of the resource. You could also use FallbackResource and provide a .php file that could provide the new resource based on criteria (you now have the power of PHP to decide where the Location header should go).
The best way1: Place those document references in a database table somewhere and reference them in the page using the table's current value. This creates a single place of "truth" and allows you to update the site from a global perspective. You could also, at a later date, provide search, tag, display a list, etc.
1 Not implying it's the abosolute best, but it is certainly a better way than updating hard-coded references.
A server side programming language like php is a better option.
Here's example code that helps:
<?php
$link="http://www.example.com/files/document.pdf";
if ($_GET['PAGE'] == "downloads")
{
?>
This is a download page where you can download our flyer.
<?php
echo "Download PDF";
}
if ($_GET['PAGE'] == "specials")
{
?>
This is our store specials page. check them out. a link to the flyer is below.
<?php
echo "Download PDF";
}
?>
The code isn't 100% perfect since some text needs adjusting but what it does is it takes a parameter PAGE and sees that it is "downloads" or "specials" and if it is, it loads the appropriate page and adds the link to the download file. If you try both pages, the link to the download is exactly the same.
If the above php script is saved as index.php, then you can call each page with:
index.php?PAGE=specials for the specials page
index.php?PAGE=downloads for the download page
Once that works, then you can add another "if" section for another page to create but the most important line in each section is the last line of...
echo "Download PDF";
...because it's taking a variable thats usable in every case in the script.
An advantage with using server side method is that people can view the site even with javascript disabled.

using AJAX to fetch scripts WITHIN my domain

I have an ajax script which references something in the same domain. I want to pass some HTML and then javascript associated with it. I figured that since it is not X-domain, It might let me do that. My goal is that I am taking a webservice and then returning a string which will be put into a div... when the javascript is inserted it would be fired, which allows a bunch of good stuff to happen.
I was wondering if there is anything special i need to do to pass javascript from the server across this request. My current AJAX request seems to sanitize and remove the scripts. THoughts? How would i go about this?
If you want script to be included in the AJAX response and executed by the browser, you will first need to do something similar to the article posted as a potential duplicate, excepting that you have HTML to be injected as well. Proceed injecting it as normal, but after you set the content, try something such as:
$(responseText).find("script").each(function(index, element){
var script = $(element).text();
eval(script);
}
Untested
However, I would try to find a way to avoid doing the above. JQuery provides ways to handle classes of elements added dynamically to the DOM. See: http://api.jquery.com/on/

Javascript redirect to dynamically created HTML

I have a javascript routine that dynamically creates an HTML page, complete with it's own head and script tags.
If I take the contents of the string and save it to a file, and view the file in a browser, all is well, but if I try document.write(newHTML), it doesn't behave the same. The javascript in the header of the dynamic newHTML is quite complicated, and I cannot include it here... But please believe me that it works great if I save it to a file, but not if I try to replace the current page with it using document.write. What possible pitfalls could be contributing to this that I'm not considering? Do I possibly need to delete the existing script tags in the existing header first? Do I need to manually re-call onLoad??
Again, it works great when the string is saved to, for example, 'sample.html' and browsed to, but if I set var Samp="[REAL HTML HERE]"; and then say document.write(Samp); document.close(); the javascript routines are not executing correctly.
Any hints as to what I could be missing?
Is there another/better way to dynamically replace the content of the page, other than document.write?
Could I somehow redirect to the new page despite the fact that doesn't exist on disk or on a server, but is only in a string in memory? I would hate to have to upload the entire file to my server simply to re-download again it to view it.
How can I, using javascript, replace the current content of the current page with entirely new content including complex client-side javascripting, dynamically, and always get exactly the same result as if I saved the string to the server as an html file and redirected to it?
How can I 'redirect' to an HTML file that only exists as a client-side string?
You can do this:
var win=window.open("") //open new window and write to it
var html = generate_html();
win.document.write(html)
win.document.close();
Maybe eval() function would help here? It's hard to give ansver without seeing the code.
Never tried this, but i think it should be possible. Some thoughts on what might make it work:
Make sure the document containing your js is sent with the correct headers / mimetype / doctype
Serve the javascript in a valid way, for example by sending a w3c valid page containing the script tag.
Maybe then it works. If not, try to erase the current html before writing the new one.
Also, it might be helpful to look how others managed to accomplish this task. If i remind it correctly, the google page is also essentially a short html page with a bunch of js.

Load JSON at runtime rather than dynamically via AJAX

I don't think this can be done "cleanly", but I'll ask anyway.
I have a system which needs to get a JSON resource via a REST GET call in order to initialize. At the moment the system waits until the onLoad event and fires an ajax request to retrieve the resource, which I don't think is the best way to do it, as the resource is needed a run time.
What I would love to do is somehow load the resource at runtime inside an HTML tag then eval the contents. But what I'm working on is an API to be used by others, so I would like to achieve this in a logical and standards based way.
So is there any tag which fits the bill? A tag which can be placed in the doc head, that I will be able to read and eval the contents of at runtime?
Regards,
Chris
Maybe I'm not understanding but couldn't you just:
<?php
$json_data = json_encode($your_data);
?>
<script>
var data = <?= $json_data ?>;
</script>
Is lack of CDN caching (Akamai etc) going to be a problem for you? If not, you could drop a script tag on the page, point the src attribute to a server side script which returns content with a javascript mime-type and contains the JS object you requested. It would be just like including an external script, only dynamically generated.
Ex:
In the head, have something like:
<script src="/js/loadjs.php?id=123"></script>
And have loadjs.php return something like:
var MyApp.initData = { id: 123, setting1: "xyz" };
Downside is that you would be unable to cache it via a CDN. I think browser caching would still work if you needed.
I was thinking of putting it in an iframe but then I realized that you have a problem with that the content-type is application/json. When I tested FF, IE and Chrome was trying to download the file and asked the user where to store it (Opera displayed the file)
Putting it in a LINK will not help you since the browser will not try to fetch the document (it only fetches for known resources like style-sheet)
To me it looks like you have to use AJAX. Can you elaborate on why that's a problem?
JSON on its own does nothing; you can't just use <script> to include it because it'll create an object that gets assigned to... nowhere. You'll have to modify it - either put it in a JS string to parse or stick a "var foo =" in front of it.
Do you have control of any server? Because if yes, you could use your server to proxy the service and wrap the JSON response with the appropriate "var" statement.
Alternatively, I believe this would work (I haven't tested it, and I always miscapitalize "innerHtml"), although IMO it's not terribly clean:
<script id="data" src="http://someotherserver.com/json.js"></script>
<script type="text/javascript">
var dataElem = document.getElementById("data");
if (dataElem)
{
var myData = eval(dataElem.innerHtml);
}
</script>
Surgeon General's warning: eval-ing results from a server that you don't control is a bad idea.

Categories