jquery ajax get/post to a javascript file - javascript

Ok, so the following is what I want to achieve:
I want to use jquery to load a file inside my javascript file.
Normaly you can do a $.ajax request with a POST to a .php file. And select something in a database that looks like the POST I sended with. Now I want the same thing, but instead using a .php file, I will use a .js file.
This also works, the code loads the file with the text alert('Hello World!'); and shows the alert. All fine. But what I want when I load that .js file, it needs to send a value with it. So it could be alert(data); and it will say hello world. How can i achieve this without using cookies or something else that stores values.

EDIT: this a GET request, a POST request is not allowed. Unless you're using GET variables to rewrite your javascript file before returning it you can't modify it or make it do anything other than what would happen if you just requested it with the <script> tag with the async attribute. /edit
Well I just learned something new. You can get a javascript file with an ajax call and execute it using eval but I'm almost 100% certain this is not how you should be doing whatever you're trying to do (also - when is JavaScript's eval() not evil)
$.ajax({
url: '/path/to/script',
type: 'GET',
success: function (response) {
eval(response.toString());
};
});
You're calling the server, which then returns the javascript file and you're parsing it as javascript using eval. I never considered doing this but I supposed it's one way to load a javascript file on demand.

Related

PHP to Javascript: dirname and document_root

I got a little problem. I am working on a project and I got my root, then I got 2 folders: website1 and website2.
website1 is the staff panel, where the upload script is on (where this problem is on). website2 is the website the 'customer' will see. Here all the uploaded images, PDFs etc. are uploaded to.
So, I have a few notes before I start:
I cannot use PHP in my Javascript. The Javascript is in .js files and not in my .php file.
I cannot do this at my AJAX request as something client-side has to be done correctly to see the image.
So basically, I am in website1 and when I upload a file (with DropzoneJS (http://www.dropzonejs.com/)) it does a AJAX request. Here it has to upload a file to a directory in website2. In website1 I have to see that image after uploading it in a IMG tag.
So in PHP I got this:
$uploadPath = filter_input(INPUT_POST, 'uploadPath');
$uploadPath = dirname(getenv('DOCUMENT_ROOT')) . '/' . $uploadPath;
This works and the file gets uploaded to that directory. $uploadPath is this (in Javascript, sent as POST parameter in AJAX request):
/SITE2/assets/uploads/
Now I need to translate the dirname and getenv('DOCUMENT_ROOT') into Javascript. I tried document.location.hostname but this does return a different value than getenv('DOCUMENT_ROOT').
document.location.hostname: 127.0.0.1
getenv('DOCUMENT_ROOT'): D:/xampp/htdocs
How can I get the same value as getenv('DOCUMENT_ROOT') in Javascript?
In php file you can create script with JavaScript variable like this:
<script>
var DOCUMENT_ROOT = "<?= getenv('DOCUMENT_ROOT') ?>";
</script>
the other option is to have your JavaScript file as PHP script then you can use PHP code inside.
You have two options, but I caution you sending the actual file path on the server/disk to the client side is a bad idea.
Use Ajax so the client sends a request like $.ajax({url: "getdir.php", success: someJSFuntion } );
Change your JavaScript file to be a ".php" file and then include the code right in there.
There is no spec that says you can't have your JS file be a ".php" file. So you'd link to it like this:
<script type="text/javascript" src="/js/myjs.php"></script>
And that would let you use PHP directly in your JS file.
Check out php.js for a JavaScript port of dirname...
http://phpjs.org/functions/dirname/
As for getenv('DOCUMENT_ROOT'), you can't get this variable value via JavaScript. The reason for this is the client-side "location" of the JavaScript file says nothing about it's actual location on the server. The best you can do is get the parent directory of the file or the domain name.
For example:
http://example.com/path/to/file
The "DOCUMENT_ROOT" as far as JavaScript is concerned is...
/path/to
It seems very improper to even assume the need to have the server-side location of the file available to the JavaScript. I would simply use either a specific URL query that indicates what location to use, or to send the location back with the AJAX response since you can add whatever you need there.
{
"document-root": "/SITE2/assets/uploads/",
"normal-response": {
...
}
}
And then wherever you would normally use what is normally received, this use...
// For example
var response = JSON.parse (request.responseText);
// Normal response
console.log (response['normal-response'][...]);
// Document Root
console.log (response['document-root']);

Load another HTML file inside dialog

I have a index.html and have another html file with a lot of text.
Now I don't want to paste this bunch of codes into my index.html.
I don't want to make it larger, the other file is not always called only if the button is clicked.
How do I get the div area from another_file.html ?
$("#buttonClick").on("click",function(evt) {
$("#load-another-file").dialog({});
Maybe you're looking for jquery.load(), load perform a server call and fetchs the HTML returned in your element.
$("#buttonClick").on("click",function(evt) {
$("#load-another-file").dialog().load("another_file.html");
});
I believe you are looking for jQuery's $.ajax, which is a way of loading data without refreshing the page:
$("#buttonClick").on("click",function(evt) {
$.ajax({
url: 'another_file.html',
success: function(data){ // You received the data
$("#load-another-file").html(data).dialog("open");
}
});
});
Note: for this to work, you might have to put your files on a server (even a local one), because some browsers don't allow Ajax requests on local files for security reasons (e.g. Google Chrome).

Easiest way to load and read a local text file with javascript?

I have a .csv file that I wish to load that contains information that the .HTML page will format itself with. I'm not sure how to do this however,
Here's a simple image of the files: http://i.imgur.com/GHfrgff.png
I have looked into HTML5's FileReader and it seems like it will get the job done but it seems to require usage of input forms. I just want to load the file and be able to access the text inside and manipulate it as I see fit.
This post mentions AJAX, however the thing is that this webpage will only ever be deployed locally, so it's a bit iffy.
How is this usually done?
Since your web page and data file are in the same directory you can use AJAX to read the data file. However I note from the icons in your image that you are using Chrome. By default Chrome prevents just that feature and reports an access violation. To allow the data file to be read you must have invoked Chrome with a command line option --allow-file-access-from-files.
An alternative, which may work for you, is to use drag the file and drop into onto your web page. Refer to your preferred DOM reference for "drag and drop files".
You can totally make an ajax request to a local file, and get its content back.
If you are using jQuery, take a look at the $.get() function that will return the content of your file in a variable. You just to pass the path of your file in parameter, as you would do for querying a "normal" URL.
You cannot make cross domain ajax requests for security purposes. That's the whole point of having apis. However you can make an api out of the $.get request URL.
The solution is to use YQL (Yahoo Query Language) which is a pretty nifty tool for making api calls out of virtually any website. So then you can easily read the contents of the file and use it.
You might want to look at the official documentation and the YQL Console
I also wrote a blog post specifially for using YQL for cross domain ajax requests. Hope it helps
You can try AJAX (if you do not need asynchronous processing set "async" to false. This version below ran in any browser I tried when employed via a local web server (the address contains "localhost") and the text file was indeed in the UTF-8-format. If you want to start the page via the file system (the address starts with "file"), then Chrome (and likely Safari, too, but not Firefox) generates the "Origin null is not allowed by Access-Control-Allow-Origin."-error mentioned above. See the discussion here.
$.ajax({
async: false,
type: "GET",
url: "./testcsv.csv",
dataType: "text",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
//parse the file content here
}
});
The idea to use script-files which contain the settings as variables mentioned by Phrogz might be a viable option in your scenario, though. I was using files in the "Ini"-format to be changed by users.

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).

Script puzzle <script src="ajaxpage.php?emp_id=23" />?

Very simple Ajax request taking employee id and returning the user info as HTML dumb.
Request ajax("employee/info?emp_id=3543")
Response id = 3543name = some name
This is just another simple JS trick to populate the UI. However i do not understand how something like below is equally able to execute correctly and dump the HTML code.
<script type="text/javascript" src="employee/info?emp_id=3543" />
When page encounters following code it executes like the ajax request is executed and dumps code into page. Only difference is its no more asynchronous as in case of Ajax.
Questions :
Is this correct approach ? its +ves and -ves.
Which are the correct scenarious to user it?
Is this also means that any HTML tag taking "src" tag can be used like this?
I have used this kind of javascript loading for cross domain scripting. Where it is very useful. Here is an example to show what I mean.
[Keep in mind, that JS does not allow cross domain calls from javascript; due to inbuilt security restrictions]
On domain www.xyz.com there lies a service that give me a list of users which can be accessed from http://xyz.com/users/list?age=20
It returns a json, with a wrapping method like following
JSON:
{username:"user1", age:21}
If I request this json wrapped in a method like as follows:
callMyMethod({username:"user1", age:21})
Then this is a wrapped json which if loads on my page; will try to invoke a method called callMyMethod. This would be allowed in a <script src="source"> kind of declaration but would not be allowed otherwise.
So what I can do is as follows
<script language="javascript" src="http://xyz.com/users/list?age=20"></script>
<script language="javascript">
function callMyMethod(data)
{
//so something with the passed json as data variable.
}
</script>
This would allow me to stuff with JSON coming from other domain, which I wouldn't have been able to do otherwise. So; you see how I could achieve a cross domain scripting which would have been a tough nut to crack otherwise.
This is just one of the uses.
Other reasons why someone would do that is:
To version their JS files with
releases.
To uncache the js files so that they are loaded on client as soon as some changes happen to js and params being passed to URL will try to fetch the latest JS. This would enable new changes getting reflected on client immediatly.
When you want to generate conditional JS.
The usage you have specified in example wouldn't probably serve much purpose; would probably just delay the loading of page if processing by server takes time and instead a async ajax call would be much preferred.
Is this correct approach ? its +ves
and -ves.
Depends whether you want to use asynchronous (ajax) way or not. Nothing like +ve or -ve.
The later method takes more time though.
Which are the correct scenarious to
user it?
Ajax way is the correct method there in that sense.
Is this also means that any HTML tag
taking "src" tag can be used like
this?
src is used to specify the source path. That is what it is meant to do.

Categories

Resources