I'm currently have an issue creating a webapp. All of the pages that we are creating can be viewed through a function that gets the post data and displays it onto the page. The issue I'm having is that when loading the content, the corresponding JS for sockets does not execute.
I believe this is because we're using:
socket.on("connect")
and the connect event would only fire once, but I'm unsure about how to fix this.
An example of the JS I'm currently using can be seen below.
function runJs(){
var url = document.location.pathname.toLowerCase();
if(url == '/account/create'){
var socket = io();
//once the socket connects, make calls
socket.on("connect", function(){=
socket.on("accountCreated", function(data){
if(typeof data.data.error !== "undefined"){
jQuery("#error").text(data.data.error);
}
else{
//account creation was successful and we're logged in.
//redirect to the home page
window.location.href = "/";
}
});
});
}
When executing another function (not posted here, as it's not important), it updates the pages HTML and runs the runJs() function seen above. I have confirmed through console.log that the function is indeed being called, but the code within the socket.on does not execute unless the page is reloaded.
Does anyone have any ideas about how I could fix this?
Related
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'm trying to create a cron file in PHP. The application I've created has around 30 active users. I want each user to run a JavaScript web-worker periodically in the background which invokes a PHP file (via ajax/xmlhttprequest) that calls a PHP file to run.
Do JavaScript Web-Workers, when calling a PHP file via the Worker, block the main PHP requests from being executed, since they come from the same browser?
To do that you'll need to put an state to close the execution while a file is executing. Use callbacks on Workers to filter execution by status (can be HTTPs status) and close the socket listener while some callback isn't triggered or some state (some storage or variable) isn't filled by certain value.
Take the example from MDN page about Web Workers:
example.html: (the main page):
var myWorker = new Worker('my_task.js');
myWorker.onmessage = function(oEvent) {
//take current status from the worker from oEvent
status = oEvent.status;
console.log('Worker said : ' + oEvent.status);
};
//if ok, send an order to continue receiving php calls
if (status == 200)
//or other function
myWorker.postMessage('someorder');
my_task.js (the worker):
postMessage("Worker listening");
onmessage = function(oEvent) {
//if status is not ok, worker is busy and can't do anything
if (status != 200)
postMessage('Hi ' + oEvent.data);
};
You were so general that it's the only thing that came within my mind to solve your problem.
okay, so I have a file 'xyz.txt' in my server folder and i need to push it thru a websocket continuously so that whenever xyz.txt is updated on the server, the webpage automatically displays the updated content of the .txt file.
I was thinking of moving the txt data to a variable that can be sent over the ws.send().. but i havent been able to get the txt data into the var either.
also, i dont want to use AJAX as the txt file in practice will be updated in a few milliseconds.
Any help on this will be great!! thank you! :)
Start a webocket connection in the web page. When a message arrives the onmessage event fires which writes the data to the div displaying the text. (simplified hack of functioning code - untested):
var socket;
function pxstart() {
document.addEventListener('DOMContentLoaded', function wsinit() {
if (!("WebSocket" in window)) {
alert("Your browser doesn't support latest Websockets");
return;
}
var wsUrl = 'ws://127.0.0.1:8001/';
var protocol = 'Px';
socket = new WebSocket(wsUrl, protocol);
socket.onmessage = function (evt) {
var js = JSON.parse(evt.data);
$(DIVNAME).html(js.data);
};
}
An app on the server monitors the txt file. When it detects a change in the text file it sends the text to the websocket server Send method, which immediately sends it to the connected browser via the websocket protocol.
Re the app: If you want to use js maybe someone with more experience in that language can step in and suggest code for that part. Suggest start with a very simple test string and build from that.
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/
I am trying to match a token (string token) in the RSS feed using casperjs waitFor() but it does not seem to work. There are other ways (not using polling) to get around but I need to poll for it. Here is the code snippet:
casper.then(function() {
this.waitFor(function matchToken() {
return this.evaluate(function() {
if(!this.resourceExists(token)) {
this.reload();
return false;
}
return true;
});
});
});
The updates to rss url are not dynamic and hence, a refresh would be needed to check for the token. But it seems (from the access log) that I am not getting any hits (reload not working) on the rss url. Ideally, I would want to refresh the page if it doesn't see the token and then check for the token again & it should keep doing that until the waitFor times out.
I also tried using assertTextExists() instead of resourceExists() but even that did not work.
I am using PhantomJS (1.9.7) & the url is: https://secure.hyper-reach.com:488/rss/323708
The token I am looking for is --> item/272935. If you look at the url I have mentioned above, you will find this in a each guid tag. The reason why I am including "item/" also as a part of my token is so that it doesn't match any other numbers incorrectly.
evaluate() is the sandboxed page context. Anything inside of it doesn't have access to variables defined outside and this refers to window of the page and not casper. You don't need the evaluate() function here, since you don't access the page context.
The other thing is that casper.resourceExists() works on the resource meta data such as URL and request headers. It seems that you want to check the content of the resource. If you used casper.thenOpen() or casper.open() to open the RSS feed, then you can check with casper.getPageContent(), if the text exists.
The actual problem with your code is that you mix synchronous and asynchronous code in a way that won't work. waitFor() is the wrong tool for the job, because you need to reload in the middle of its execution, but the check function is called so fast that there probably won't be a complete page load to actually test it.
You need to recursively check whether the document is changed to your liking.
var tokenTrials = 0,
tokenFound = false;
function matchToken(){
if (this.getPageContent().indexOf(token) === -1) {
// token was not found
tokenTrials++;
if (tokenTrials < 50) {
this.reload().wait(1000).then(matchToken);
}
} else {
tokenFound = true;
}
}
casper.then(matchToken).then(function(){
test.assertTrue(tokenFound, "Token was found after " + tokenTrials + " trials");
});