I login into my website (running on localhost), and store the user id in a session variable
$_SESSION['user_id'] = $user_id;
The main page loads, and all is fine. I show the user id on the main page, so I'm sure of its value. When I load another page, using
php = 'some_php_file.php';
window.open(php,php);
The second page opens ok. But if I try to open the same page again, clicking on the same button on the main page, the system will logout. If I omit the second php in window.open() (using '' instead), I may have multiple copies of the same window (what I don't want), but no problem of automatic logout.
Any idea what may be happening?
EDIT: If I close the second window and repeat the process, I have no logout problem. I can close and reopen the second window as many times as I wish. The problem only happens if I try to open the second window, but it is already open. I can also open different 'second windows' (different php files). I'm only getting logged off if I try to open TWICE the same window.
EDIT 2: Seems I've found it. Before I call window.open(), I'm testing for the existence of the php file, using this function:
function fileExists(url){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
return http.status != 404;
}
If I change the http.open() line to
http.open('HEAD',url,false);
it works! But the manual tells us to use 'true' in the third parameter... What should I do?
It seems to me that your fileExists function simply returns true all the time because it does not wait for the XHR to complete. Except when you specify async = false.
Time to read How to return the response from an asynchronous call? probably.
I have no clue what is the consequence of this always being true, as you do not share exactly what you do with that result.
Now if you want to "stick with the manual" and keep async = true (you should really indeed), then simply wrap your following code in a callback. E.g.:
function fileExistsAsync(url, callback){
var http = new XMLHttpRequest();
http.open('HEAD',url,true);
http.send();
http.onreadystatechange = function () {
if (http.readyState === 4) {
callback(http.status != 404);
}
}
}
fileExistsAsync(url, function (exists) {
console.log("async " + exists);
});
Demo: http://jsfiddle.net/52xqLfow/
Related
I have a Javascript file running on a page and I would like to log certain events as they occur. For example, I have a web store - and when people add an item to their cart, I want to log this event by visiting a page that I built:
function log_event(id) {
window.location.href = 'https://example.com/log/cart.php?id=' + id;
return false;
}
The log/cart.php page doesn't really have anything to display, all it does is insert a record into a database containing the item that was added to the cart, and the date.
The code that calls this function looks like:
document.getElementById('add-to-cart').addEventListener('click', function() {
// Add to the cart
...
// Track the item that was added
let id = document.getElementById('add-to-cart').getAttribute('data-id');
log_event(id);
});
With my current code, the log/cart.php actually replaces the current page. I want the opening of log/cart.php to only happen in the background without the user being interrupted. I don't want it to actually open a browser tab or window and let the user stay in the product page.
You can send an AJAX request to that endpoint:
function log_event(id) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", 'https://example.com/log/cart.php?id=' + id, true);
xhttp.send();
return false;
}
fetch() can also be used, but be aware of its browser support (no IE).
I am designing a HTML page, and I would like to send a simple message (or trigger some action) when the user intentionally request updating (update button on the web browser, pressing F5... or whatever any other manual method that could exist) of the HTML file.
Something like:
window.onmanualupdaterequest = alert("You requested update");
Or whatever the correct procedure could be.
How could I do this?
Further notes:
I have tried the window.onbeforeunload function (example), but it does not exactly solve the problem (I would say it has not the same behavior as user request).
I would like to ignore the autoupdate case (like in setInterval or similar functions or scripts) from the manual update case. This question is about the manual one.
The classical Android swipe-down update method for a web page is considered here as a manual update method.
My idea would be to use the sessionStorage to save the window.location.href on pageload. If the user reloads the page the stored location should match the current url:
window.addEventListener('load', function () {
const lastUrl = sessionStorage.getItem('lastUrl');
if(lastUrl && lastUrl === window.location.href) {
alert("You requested update");
}
sessionStorage.setItem('lastUrl', window.location.href);
});
I am trying to create a temporary image url for a local image and send it to Google to do a Search by Image. I don't want the image url to be permanent so I want to delete it right after I use it. I have the code below:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(); // asynchronous call to server to delete the URL
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ xml.responseText; // the image url
}
}
xml.open("GET", "REST_ENDPOINT", true);
xml.send();
}
The function above calls the server, and when it finishes, will delete the url and redirect the page. The function "deleteImageURL()" is another ajax call done asynchronously. Currently, this loads the google page fine as the image URL is not done deleting the url by the time that the redirect happens.
My question is this: Will deleteImageURL() finish deleting the image URL even after the page redirects or will it stop (and thus, never delete the URL)?
EDIT: So I was thinking about what you guys were saying about race conditions and tried the following code instead:
// Gets a URL that can be used to do a search by image through Google.
function getImageURL() {
var xml = new XMLHttpRequest();
xml.onreadystatechange = function () {
if (xml.readyState == 4 && xml.status == 200) {
deleteImageURL(xml.responseText);
}
}
xml.open("GET", "REST_ENDPOINT"
+ id + "/public_url", true);
xml.send();
}
// Deletes the url for the image.
function deleteImageURL(imageURL) {
var xml = new XMLHttpRequest();
xml.open("GET", "REST_ENDPOINT_FOR_DELETE", true);
xml.send();
window.location.href =
"https://www.google.com/searchbyimage?site=search&sa=X&image_url="
+ imageURL;
}
This code works every time that I run it. I think that there still may be a race condition, but it seems to be working fine so far.
Thanks again.
The "deleteImageURL()" will finish deleting the image URL even after the page redirects..
Refer : Should I wait for ajax to complete to redirect a page?
The server won't stop processing the request (initiated by deleteImageUrl), but you will not be able to handle a callback if the current page unloads in the browser before the operation is completed.
If deleteImageURL(); contains an async call you should do the redirect when the call is completed. Your code will work when the call is synchronious. We don't see the source of deleteImageURL(); and can be more concrete, but you should do the same thing as you've done for getImageURL().
Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;
I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.
I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?
Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?
You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.
If I've understand well your needs, that should be ok for your problem.
var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", 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);
I don't know if POST would work.
You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.
You will have to return JSON style data.
See: http://docs.jquery.com/Ajax/jQuery.getJSON
Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.