Is it possible? Now, I have done live chat, where with jquery's help I connect to .php file and check last modified time and if it is not as before, I retrieve messages. If it were possible in javascript I probably would save a lot of resources.
Thanks.
It's definitely possible if the server is sending an accurate Last-Modified header for that particular file:
var getMTime = function(url, callback) {
var xhr = XMLHttpRequest();
xhr.open('HEAD', url, true); // use HEAD - we only need the headers
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var mtime = new Date(xhr.getResponseHeader('Last-Modified'));
if (mtime.toString() === 'Invalid Date') {
callback(); // dont want to return a bad date
} else {
callback(mtime);
}
}
}
xhr.send();
};
getMTime('url here', function(mtime) {
if (mtime) console.log('the mtime is:' + mtime.toISOString());
});
Short answer: there's no way but AJAX + a server-side script (in your case, jQuery + php)
Being a client-side script, javascript gets run on the client's computer, so if the file whose m-time you want to check is on the server, then you are correct to use AJAX and a server-side script. No other way will work.
If the file whose m-time you want to check is on the client's computer, then you're out of luck. Javascript is intentionally designed to be prevented from accessing the client's files. (It can only access cookies, which are on the client's computer, however, because the browser (not any javascript) loads those into its work environment.)
Maybe HTTP ETag headers could be used to check if the page has changed. The first response contains ETag and your client uses that for the following request. Your PHP server side code would then send 304 if the page has not been modified.
http://en.wikipedia.org/wiki/HTTP_ETag
Related
I want to make an upload page for my site so that documents get uploaded asynchronously, I tried using AJAX, but AJAX has a limited access to the users filesystem, and when the information is sent to the server only the file name appears without the directory, I would like suggestion on how to do this easily without using JQuery, and also I would like to know if there is a way to monitor the progress of a file upload, so that I could add a progress bar to my site.
function createXMLHttpRequestObject(){
var xmlHttp = 3;
if(window.ActiveXObject){
try{
//test for new version of internet Explorer
xmlHttp = new ActiveXObject("Msxml.XMLHTTP");
}
catch(e){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
xmlHttp = 2;
}
}
}
else{
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
xmlHttp = 1;
}
}
if(!xmlHttp){
alert("Error creating Objece");
}
else{
var xHttpArr = new Array();
xHttpArr.push(xmlHttp);
var i = xHttpArr.length - 1;
return xHttpArr[i];
}
}
function process(xmlHttp, i){
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
//value = encodeURIComponent( objRef.value );
xmlHttp.open("GET", "php/AjaxBody.php?value="+i, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else{
alert("Hold on");
}
}
function handleServerResponse(){
if(test.readyState == 1 || test.readyState == 2 || test.readyState == 3){
}
if (test.readyState == 4){
if(test.status == 200){
txtResponse = test.responseText;
bodyDiv = document.getElementById("body");
bodyDiv.innerHTML = txtResponse;
}
else{
alert("Error with the xmlHttp status");
}
}
/*
else{
alert("Error with the xmlHttp readystate: " + x.status);
} */
}
Above is the code that creates the Object
button.onclick = function() {
send = createXMLHttpRequestObject();
frmUpload = document.getElementById("frmUpload");
file = document.getElementById("fileUpload");
processSending(send, frmUpload);
}
Above when the process method is called to send the file,
on the server I try to echo the file path, only the the name appears, like this
<?php
echo $_GET['value'];
?>
First of all you are doing your file upload wrong. File uploads require you to do a proper POST request using forms as it requires the enctype form attribute to be multipart/form-data. Why? The browser sends the binary file data through the POST request and does the hard work of encoding the data correctly through the POST request to be read on the server. Any other way and you will just be getting the file name at the server (you can verify this with a tool like Fiddler).
Alright, then how do you do a file upload using AJAX? AFAIK it's not possible to read the user's file system directly (I think FileReader only allows reading through the sandboxed file system through the browser but I may be wrong here), so IMO there are 2 ways to go here:
Using a hidden iframe approach for the file upload. Google it you will find lots of info it.
Use a Flash based uploader. More on this at the end.
As far as getting the location of the file on the users file system using Javascript goes, forget about it. It's considered a security concern and many browsers only return the file name on reading the element value when using the HTML input file tag. (Unless you are thinking of using a flash component. More on that in the last point.)
Now coming to the progress bar issue. When your PHP script is actually run the entire file has already been uploaded to the server. So how to show a progress bar? A few (hackish) ways:
An old school approach is to create a CGI script on the server to handle the upload. The advantage? CGI scripts can be run during the upload allowing you to retrieve the actual byte level progress of the upload. But this also requires you to update the progress at some place on the server which you can poll (with a separate AJAX request) and show in the browser to the user.
Another most commonly used approach is using a flash based uploader (please don't kill me StackOverflow community). Yes it's still used by big names (I am looking at you Facebook). The advantage you will have is that you don't need any special scripts on the server. The Flash based client is fully aware of the number of bytes uploaded. Also you may have access to the actual file path string (note the use of may and string) which is not so openly possible with plain JS and HTML.
You could use a FileReader and read the file into an ArrayBuffer or a BinaryString and then use multiple requests to send for example 1 mb sized packages. The receiving php script would then have to 'rebuild' the file by appending each received part to it. This would also solve the problem of echoing the file path on the server as you can (and have to) decide where to save it before writing to it.
It may sound odd, but I've been programming games in PHP. The main problem I've found was that the only way to update PHP is to load a page. That makes real-time slow. Javascript can interact with a page without reloading it. Is it possible to load PHP pages on a page using Javascript? So that it would allow PHP to be loaded over and over without reloading.
I've seen it done with Chat rooms but not sure how it works.
We mostly use Ajax, which consists in a client-side Javascript code that calls a server-side page, with out leaving the page.
Here's an example that will get the displayed content of a page, using the GET method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('GET','myPHPPage.php?foo=foo&bar=bar',true);
xhr.send();
And here using the POST method (JSFiddle):
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
var data = 'foo=foo&bar=bar';
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && ((xhr.status>=200 && xhr.status<300) || xhr.status==304)){//Checks if the content was loaded
console.log(this.responseText);
}
}
xhr.open('POST','myPHPPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.setRequestHeader('Content-length',data.length);
xhr.send(data);
Note that here we use the setRequestHeader method to change the headers of this HTTP request and, in this case, to change the Content-type and the Content-length (this header has a default value of 4096 bytes). Also, the setRequestHeader method must be called after the open method.
These links should help you:
https://developer.mozilla.org/en/Ajax
http://code.google.com/intl/pt-BR/edu/ajax/tutorials/ajax-tutorial.html
Yes it's incredibly common.
Read up on Ajax.
We call that AJAX!!!
Just Read The documentation on internet about ajax
i want to pass a javascript string to php ... WHICH is RIGHT after the code .. in the script.
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
this does not work.
What should i do ?
When someone visits a website, this is generally what happens:
Their browser sends a request to the server.
The server evaluates that request.
The server realizes, "Egad, the page they're requesting has PHP!"
The server evaluates the PHP, and only sends the results to the browser.
The browser parses the content that it receives.
The browser realizes, "Egad, the page I received has JavaScript!"
The browser evaluates the JavaScript, entirely on the client's machine.
So PHP and JavaScript are basically at different ends of the process. Only the server handles PHP, and only the client handles JavaScript.
To "give" a string to PHP, you'd have to make a request of the PHP page, sending that string as a GET variable:
http://www.yourdomain.com/some_php_page.php?myvar=mytext
There are a few ways to do this with JavaScript.
If you only care about making that request on the PHP page, and you don't need to worry about receiving any information back, you can just create an image and use the URL as the source:
var fakeImg = new Image();
fakeImg.src = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext';
Even though you're requesting an image, the server doesn't know that, and will process your request by calling the PHP evaluating it, etc.
You can make an actual AJAX request. Start by creating an XMLHttpRequest object:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
There are some issues in IE with cached responses on AJAX requests, so make the url unique:
var url = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext&unique=whatever';
Tell your XHR where you want it to go, and how you want it to get there:
xhr.open('GET', url, true);
// The "true" parameter tells it that we want this to be asynchronous
Set up a method that will check for when a response is received:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status < 400) {
success(xhr.responseText);
}
};
And finally, send the request:
xhr.send(null);
// We set "null" because some browsers are pissy
Some notes to keep in mind:
You have to build the success function yourself, to handle the string that your PHP page will return.
You can pass that function xhr.responseXML if you want, but that's usually just a hassle for me.
Using onreadystatechange the way I have will (I believe) introduce memory leaks in some versions of IE
PHP is executed server side while javascript is client side, so that means that the PHP is already executed when you're sending your javascript code.
You might want to look into AJAX instead.
You should get the difference between client side and server side code clear. The variable you are introducing in the php code isn't assigned before because that variable is set at the client. So your code example is in essence wrong. If you want a value that is present at the client (javascript) to be available at the server (php), you need to do something with the xmlhttprequest object of javascript (also know as ajax).
You can do the other way around though...print a php value in javascript. This is because the script is than created server side and send to the client before it is being processed by the browser.
Not sure what you are trying to reach but maybe this helps a bit.
Your example is somewhat confusing:
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
Because if I do this:
<script type="text/javascript">
<?php $myvar = "mytext"; ?>
var myvar = "<?php echo $myvar; ?>" ;
</script>
Then it sets the JavaScript value of myvar to the PHP value of $myvar so they both stay the same. If you're trying to do something else you need to expand your example.
I'm trying to do my own bookmarklet and I already tried to read some response in SO but nothing to answer the weird reaction I got from my script.
I'm doing an AJAX call from my bookmarklet, so I do the little trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/urlToMyJS.js";
document.body.appendChild(newScript);
void(0);
And the urlToMyJS.js is like this :
var u = 'http://example.com/scriptToCall.php';
var request = new XMLHttpRequest();
request.open("GET", u, true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
The weird part is :
The javascript is always launched and scriptToCall.php is always called too (it logs every hit)
The alert shows the responseText when I click on the bookmarklet on example.com
Sometimes, on other sites, the alert shows nothing (but still appears)
Some other times, the alert doesn't even show... (but I still have the log hit...)
Do you have any idea why it does that? And if yes, do you have any idea how I could make it always show the responseText?
status won't be ok unless you are testing the bookmarklet on your own site (example.com).
When you run the bookmarklet on a different site to example.com (which is after all the whole point of having a bookmarklet), it will be doing a cross-origin XMLHttpRequest to example.com. Depending on what browser you're using, that might do the request, but you won't be able to read the response due to the Same Origin Policy. It's an essential security feature that you can't make user-impersonating XMLHttpRequests to other servers.
If you want to make an XMLHttpRequest back to your server, you must do it from a document on your server, typically by having the bookmarklet create an <iframe> pointing to example.com.
Alternatively, use JSONP (<script> inclusion) to call scriptToCall.php.
Well, finally, I used another trick :
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.src = "http://example.com/scriptToCall.php";
document.body.appendChild(newScript);
void(0);
This way (the PHP is sending a javascript header), no more AJAX. It was nonsense in my case since both file were in the same server/folder, 1 movement instead of 2!
Anyway, thanks bobince for all the details I might use in the future !
So right now, I'm just using a basic form to check a password. I want it to check the password and basically remain on page.html so I can use JavaScript to alert incorrect password or something. I'm not really sure how to do that. It seems it would bring me to check.php. I'm not too sure on the whole process, any help appreciated! Thanks!
Page.html
<form action="check.php" method="post">
<input type="password" name="password" />
<input type="submit" value="Submit" />
</form>
check.php
<?php
$password = $_POST['password'];
if ( $password != "testing" ) {
die();
}
?>
PHP runs at the webserver which usually runs at a physically different machine (the server side) than where the webbrowser runs (the client side). The machines are usually connected by a network. HTTP is a network protocol. The webbrowser sends a HTTP request. The webserver retrieves a HTTP request whose URL indicates that it should be forwarded to PHP for further processing. PHP retrieves the HTTP request and does the processing and returns a HTTP response. Usually in flavor of a plain vanilla HTML page. The webserver sends HTTP response back to the webbrowser.
JavaScript runs at the webbrowser and knows nothing about PHP since it runs at the webserver. PHP in turn also knows nothing about JavaScript (although it can produce some JS code which is in turn to be sent to the webbrowser over HTTP). The only way to communicate between JS and PHP is HTTP. One of the ways to let JS fire a HTTP request and retrieve a HTTP response is using XMLHttpRequest. This is the core technique behind Ajax.
I see in your question history that you're already familiar with jQuery. It's a JS library with a lot of convenient functions to fire ajaxical requests. In this specific case you would like to use $.post. E.g.
$('#formId').submit(function() {
$.post('check.php', $(this).serialize(), function(valid) {
if (valid) {
alert('Valid!');
} else {
alert('Invalid!');
}
});
return false; // Important! This blocks form's default action.
});
With in check.php:
<?php
echo $_POST['password'] != "testing";
?>
This is however not unobtrusive. If the user has JS disabled, then all will fail. Your best bet is to check in PHP if an ajaxical request is been fired by jQuery or not and handle accordingly:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
// Ajax.
} else {
// No ajax.
}
Alternatively you can let jQuery also reach a different URL or append an extra parameter.
Update: here is how the JavaScript would look like when not using jQuery:
document.getElementById('formId').onsubmit = function() {
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
alert('Valid!');
} else {
alert('Invalid!');
}
}
}
xhr.open('POST', 'check.php', true);
xhr.send(serialize(this));
return false; // Important! This blocks form's default action.
}
function serialize(form) {
var query = '';
for(var i = 0; i < form.elements.length; i++) {
var e = form.elements[i];
if (!e.disabled && e.name
&& ((e.type != 'checkbox' && e.type != 'radio') || e.checked)
&& (e.type != 'submit' || e == document.lastClicked))
{
if (query.length) query += '&';
query += e.name + '=' + encodeURIComponent(e.value);
}
}
return query;
}
document.onclick = function(e) {
e = e || event;
document.lastClicked = e.target || e.srcElement;
}
Bloated and verbose, yes ;)
You'll have to use ajax if you want to remain on the same page. I recommend using jquery and jquery's post function.
Basically you create a javascript function that gets called when the login button is clicked. The function will send a request to check.php. Check.php will output a status message (maybe 1 for succes, 0 for fail) that will be returned to the original script. From there you can output a message saying invalid password, or set a cookie if it was correct.
The simple solution to what you're trying to do (essentially AJAX) is:
Modify your php script to output something unique on success or failure.
Use JavaScript to submit the data to the php script, instead of the normal form POST.
Have the JavaScript alert the user if the password is invalid, or direct to an appropriate page if the password is valid.
Of course those are the broad strokes. In reality you'll need your php script to give one kind of response when an AJAX request (a request made by JavaScript) is made, and another response when the page is requested by a regular form POST - you do want it to work without JavaScript - right? You'll probably want the JavaScript to update the page contents instead of an alert box. You'll want your php script to set session variables so the next page they access knows they are logged in.
Broad strokes.
Reading the jQuery AJAX documentation may help.
When designing a web site, always add JavaScript after everything works fine without it. The reason for this is twofold. For one, some people browse without it turned on. The other reason is that JavaScript is always viewable and editable by the crackers out there.
This approach requires that you have a separate PHP file that validates the success of the password. Everything on the original page (HTML and JS) should only send the password and perhaps wait for the request. To keep things on the same page, you can use AJAX to send the input password and print out the response that it receives. jQuery makes AJAX easy if you don't want mind the overhead.
Using POST over HTTPS is better than using GET and HTTP. Of course, keep track of session variables and you might also want to limit the amount of time from when one first receives the form and when they actually submit it.