I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.
Related
This is wat needs to happen:
I need to get user information out a MySql database.
But i don't want to insert the password of my database in the php file. Because that file won't be hosted on my own server. Nobody must see that password when they access the server by ftp and edit the php file.
My first solution that didn't work was opening a php file from my own host and reading the output (i made a script that connects to the database and outputs a long string) and converted the output to an array by splitting the values.
This did not work because of security reasons in php.
I can't create a extra account for my database that has read-only access because my host won't allow me. (hostinger.co.uk)
I also thought about using a iFrame and load the file on my host. And read it using javascript to read it. But again, security won't allow me to edit it.
Does someone know a way to fix this?
OPTION 1:
Since you want to make sure your buddies server doesn't have access to the MySQL server info (username, password, etc), your safest bet is to connect to the database from your server, and just communicate between the two servers what needs to be retrieved.
As Darren mentioned in the comments, an API would do this just fine. Since there are a lot of open source libraries out there that can get the job done, I will recommend you one: pheanstalk
pheanstalk is a php client that works on top of the beanstalk library, which is basically a queue.
You could set up a queue on each server, and configure the communication to happen between the 2 servers. Then you would have worker.php scripts running every second (or 10 seconds or however so often you like) looking for commands being sent from 1 server, taking those commands in, processing them, and sending back the information to the main computer.
OPTION 2:
Instead of accessing your database, you can create a copy of yours, and have his server contain a copy.
Key points of option 2:
If his server isn't capable of carrying a full fledged MySQL database, there is MySQLi, which is very similar, but the only difference is that it is basically a file that you keep in your server. That is the benefit since it is LIGHT (hence the "i" from MySQLi). The downside is that the database isn't as "powerful", some operations might be limited, though that is to be expected, but good none the less.
If your friend has a database however, then better yet since it will have all the capabilities.
Now since I am assuming you would need to keep their copy of your database up-to-date, you can create a function that would send a request to your buddies server on what was updated. This is an API since it is intercommunication between processes behind the scenes, but probably wouldn't need any root access as some other API's might require.
Though the hastle here is that you would literally have to call that function every time you do any updates... :(
Edited:
OPTION 3
After talking a bit with the OP in the comments, another possibility came up. In his particular case, he might be willing to have a file in a public directory available for his buddies user to read. For example, lets say his file was located in:
http://www.example.com/hiddenfiles/dfjios4wr238##.txt
To access what is inside that file, you would have to know the name (and the name was specifically designed to work as a password, hence even though the information isn't sensative for the OP's specific situation, it's always best practice to stay consistent and think safe xD).
To access the file, the following could be done:
$path = 'http://www.example.com/hiddenfiles/dfjios4wr238##.txt';
$fileHandle = fopen($path, "r");
while ($line = fgets($fileHandle))
{
echo "--> {$line}";
}
fclose();
So i have a canvas on which the user signs, now instead of converting it to a base 64 string i simply want to save it as an image itslef. whats the easiest way to do it html5??
You can easily do that this way (specifying the format as png in this case):
var img = canvas.toDataURL("image/png");
You can specify different image formats.
Take a look at this answer.
I've answered a similar question here:
Simulating user event
Assuming you are saving locally
You can go the route of creating an image from a Data URL, but then saving it is the trickier part that currently isn't very nice using HTML5. It's hopefully going to get better soon, if browsers incorporate the download attribute of the a tag.
Obviously if you have higher permissions than a standard webpage... i.e. you are designing a browser plugin - then there are other options...
If I were to implement something like this myself, at the moment, I would conceed to using a flash plugin to handle the save to the local computer.
Assuming you are saving remotely
By the sounds of it you aren't saving to a server, but if so this is quite easy by just POSTing the base64 information to a script written in a server-side scripting language (i.e. like PHP) and getting that to write the data directly as binary to a file. Obviously you have to make certain you do this securely however, you don't want just any binary data written to your server's filesystem.
Best of both worlds
If you've got the development time, the best method to get a canvas image saved locally - without Flash - is to create a server-side script that instead of saving the data to your server actually writes the Base64 information you send it directly back as a realised binary image file. That way you can create a form that posts your Base64 data to a new tab, this request is evaluated by the server-side, and the binary image is returned... at which point the browser asks the user where they wish to save their image.
You'll need to define the correct headers to force an image to download (rather than display in-browser). A simple change to force this is to set the server-side script's Content-type header to 'image/octect-stream'... there are other header options to set which would be best researched (i.e. headers that control the filename and so forth).
reflect.php
<?php
/// a simple example..
if ( array_key_exists('data', $_POST) && ($data = $_POST['data']) ) {
header('Content-type: image/octet-stream');
echo base64_decode( $data );
exit;
}
and the form...
<form action="reflect.php" method="post" target="_blank">
<input name="data" type="hidden" value=" ... Base64 put here with JS ... ">
</form>
(The whole form should be created dynamically and submitted automatically with JavaScript)
Improving the user experience
There are ways to avoid a new tab being created, but you'd have to research to make sure these other methods don't cause cross-browser problems... for example you could post your form data as part of an iframe (which would keep the process hidden), or just post the data directly on the current window (..and hope that all the browsers receive the correct request and open a download rather than replace your page content - most modern browsers should handle this).
Improving security
With regards to a PHP script that automatically returns binary data, you should keep the access to this script secured by one time use key / authentication token or something similar, and keep a limit on how much Base64 data you are willing to accept. It might not seem like it poses a secutiry risk - as you are not modifying your server in any way with what the user sends - but the dodgy people of this world could take your script and use it to send download request to other users... which if downloaded (and turned out to be unwanted trojans or viruses) would make your server implicit in providing the dodgy file.
All in all
Due to the effort required to get a simple thing like an image saved to the desktop, I wouldn't blame you for doing the following:
Embed the image in the page (after taking your snapshot from canvas) and ask the user to right click and Save as...
Hopefully future things will make this situation better...
I am testing out some tracking pixel functionality in an ASP.Net 4 MVC architecture.
This article gives a nice way of setting a tracking pixel (image) that you can use to read a visitor's environment parameters and do some logging on the server side before completing the response.
What I would like to do is inject some Javascript, based on the account ID that the pixel came from. In the example above, the ID would be set by setting some query string parameters.
By the looks of that code, it can only be used to log data, as the response type is of type image.
Is it possible to accomplish this using the method shown above? If not, can I get some recommendations/sources on how to accomplish this using Javascript and tying this back into my .Net architecture where based on some logic, I can add some additional Javascript to the response?
If I have no other choice to go the JS route, I'm guessing it would be something along the lines of the Google Analytics tracking script that includes some parameters sent back through JS.
Thanks.
If the client is requesting an image and expecting an image, then that is what you need to return. Look at this type of HTML that would generate an image request:
<img src="test.jpg">
Clearing the client is expecting image bits to come back and anything besides that is going to mess up the display of that image.
If you want to put server-supplied javascript into the page, then simply have the client request some javascript like this:
<script src="test.js"></script>
Your server can then do it's logging upon that request and return whatever javascript it wants to from that request. If you want to return different javascript for every request, then you will need to defeat caching in the browser (there are a number of was to do that) so that the javascript is always requested from the server.
In general, I'm guessing that you don't need to return different javascript for every request. But rather, you can put a common block of javascript in the client page and that javascript can examine the environment and branch based upon what it finds. That's how Google Analytics works. One common piece of javascript is served to the client, that code examines the environment and then makes an ajax request with different parameters set that causes the right information to be recorded on the server.
It seems like this question is asked periodically and the common response is "You shouldn't do that with AJAX anyway. Just set the window location to the file."
But I'm trying to request a file that doesn't actually exist out on the server anywhere. It's dynamically generated (by a Django view) given the GET/POST context parameters. The file I want to retrieve via AJAX, and then save to the client machine, is a text file (csv).
I can currently get the text to the client machine (and can verify this by seeing it in logging or an alert) but cannot then figure out how to save this text to a file inside of the AJAX success callback fn.
Essentially, is this possible, is it something JS can do? That is, to open file save dialogs for "files" that are actually AJAX response text?
From the browser's point of view, it doesn't matter if the file exists or not, it's just a resource on a server that it's requesting. I think you're going to need to do some version of "Just set the window location to the file". If you set the content type in the header to something that the browser doesn't recognize, I believe it will ask the user if they want to save it.
As others mentioned, you can't do it only with JavaScript.
IMO the best option would be the Flash 10+ FileReference API.
There are some good JavaScript wrapper libraries like Downloadify that provide a JavaScript API to access those methods.
Give a look to this demo.
This isn't something JavaScript (and therefore jQuery or anything other JS framework) is allowed to do, for security reasons. You may be able to do what you want to flash or another route, but not JavaScript. Bear in mind Flash has it's own slew of security restrictions for this as well.
(Yes, IE can do this via an ActiveX object, but I'm not counting that as a "solution" here)
Basically, no. Javascript cant save anything to the local machine due to security restrictions. Your best bet may be to have a signed applet that the user can trust to write the file, or put it in a textarea that they can then easily copy and paste into a new file.
Could you not use the PHP rename() function for this, instead of just Javascript? Call to a PHP file and pass the name of the file you want to copy along with where as parameters?
I have the same problem. You can try this
<button id="Save">Save</button>
<img src="MakeThumbnail.ashx?Image=1.jpg" id="imgCrop">
$("#Save").click(function (e) {
url = $("#imgCrop").attr("src")+"&Action=Save"
e.preventDefault(); //stop the browser from following
window.location.href = url;
});
Did not have luck with these examples:
Javascript File remove
Javascript FSO DeleteFile Method
Deleting a File
There are no special permissions on the file.
Is there a way to do this in JQuery?
The requirement is - a certain file must be deleted from the web directory when another page is loaded. There is no security issue as this is on a closed network.
Any help is appreciated.
Thanks.
With pure JavaScript, it can't be done. Using an AJAX call to a server side script that deletes the file would work though.
Javascript cannot delete files, it is prevented as it would lead to HUGE security vulnerabilities. THose links are for ActiveX controls that are handled through JS. Use a server side language.
You can't delete files over HTTP (well in theory you can, but it's not implemented.)
The easiest way is to set up a tiny server side script (e.g. in ASP or PHP) and to call that from JavaScript. The server side script needs the proper permissions to do the deletion, but otherwise there is no problem.
In PHP the start would look like this: (Not expanding solution to a fully secure one because you're not saying what platform you are on)
<?
// STILL INSECURE!!!!
// Do not use in any public place without authentication.
// Allows deletion of any file within /my/files
// Usage: filename.php?file=filename
$basedir = "/my/files";
$file_to_delete = $_REQUEST["file"];
$path = realpath($basedir."/".$file_to_delete);
if (substr($path, 0, strlen($basedir)) != $basedir)
die ("Access denied");
unlink($path);
?>
you would call the script like this:
http://yourserver/directory/delete_file.php?file=directory/filename
You cannot delete a file on a remote server using only JavaScript running in a visitor's browser. This must be done with a server-side script.
If you are doing this in a RESTFUL way, you would send an HTTP DELETE request.
jQuery's ajax method states that you can use the method parameter to specify 'DELETE' but notes that some browsers may not support it.
Obviously you will need a webserver which will accept a DELETE request, and apply some sort of authentication/authorization so that joe random visitor can't delete your files. I believe Apache's mod_dav will get you started here.
Javascript is a client side language. So you are not able to delete file on server directly. All examples that you provide may be used only for deleting files on your local machine but not into server.
But you may call some server page function that will delete file.
You can't delete files with JavaScript as it is run locally. So, it doesn't even touch external files.
You need to use a server side language that has access to editing the files such as PHP, RoR, or ASP.
You can however use jQuery to call the server side code via AJAX such as $.get or $.post and then the server side code deletes it and it would seem as though JS is deleting the files.