Let's say we have a web app that only has one element, for example an image IMG1 and if an user clicks on it, it will change to another image IMG2 (this change should be visible only to the users that clicked and triggered the event).
Then, I have another event that triggers when a total of 100 users clicked on the image (or any other back-end related event), and this time I want to dynamically change the image to IMG1 (but now I want the change to happen and be visible to all the users of the website).
The confusion starts when I realise that for both events the function would be the same (changing the src of that HTML img element) yet I want it to have a different effect:
on the event of a user click change it for that user only.
on an outside event that doesn't involve a specific user, change it for all the users to see the same image.
How does this work? what is the thing that makes the difference between a HTML change that only affects the users locally (on their actions) and a change that has a global effect (to all the users).
UPDATE !!!
I should have been more specific with what I don't know.
I'm familiar with AJAX request and I already have the backend sorted.
In the frontend script I have an event listener for the event from the backend, and all my questions are actually about 'what and how to do it' after the event listener is triggered.
Now, what I want to do when this happens is to make some changes, the main one being to change that image IMG1 to IMG2 for all the users (as it would be a dynamic update to the website) but also:
I need that change to be permanent, so in a case of users reloading the page or new users coming in, they all should still see IMG2. (And the only time the image would change would be when the event listener on the frontend script will trigger again on the same backend event to change the image again (to IMG3) for example. And yes, in this example there is NO 'on click' request for the users to change the image, so ignore my example previous to the update.
Now to address your answers, I checked the web sockets stuff and it seems to be doing what I need if I run that 'on event' change of image to all sockets. Which only leaves me with 2 questions now:
1) Will this change that occurs on all sockets to change the image be permanent, so in a case of users reloading the page or new users coming in, they will all see the new image (IMG2) as a permanent change to the webpage ?
2) Regarding these type of permanent changes, isn't reactJs a way of doing such changes dynamically?
What would actually happen if on that event listener (for the backend event) I simply ignore all the web sockets stuff and run the same code of changing the src of the image ?
2.5) Because from how I see it, that event in the backend fires without any specific user input, thus is not linked with any user. So if I simply run the code on that event without websockets It should either do absolutely nothing (so no change for anyone) OR do the change for all the users (acting simply as a dynamic update to the webpage). How does this work?
I'm looking forward for your answers, and thank you all in advance!!!
The click event needs to be handled by an AJAX request, sending a message to the server and the server will handle that and respond. Upon the response, the first type of event is executed for the user.
On server-side you will need to have an event queue somewhere, maybe in the database. If you are using WebSockets, then you will have to execute the second type of event for all users if the request is met via WebSocket channels. If you are not using WebSockets, you will need to do polling from the browser. Anyway, you will need a counter on the server-side to be able to determine when the second type of event is met.
EDIT
Yes, WebSockets are the way to go unless there is a strong reason not to do so, like a boss saying he or she does not want the server to use WebSockets. With WebSockets you have a live channel between the server and the client browsers. You can use this channel to send the URL change to the client. On the other hand, the client will have to handle the change with Javascript, gathering the tags where the src is to be changed and change them. If you happen to have a class of changable for all such tags, then executing the change can be done with a function like this:
function changeSources(newSrc) {
var items = document.getElementsByClassName("changable");
for (var index = 0; index < items.length; index++)
items[index].src = newSrc;
}
However, this change will be effectuated only for the loaded page which was initially loaded and upon new loads, this, by itself will not use the new src. So you will have to solve that problem as well. A neat way to do it is to store the new src on the server before you send it out to the client via WebSocket and use this stored src as the src of those tags when the client requests for the HTML. So, your problem has two parts, the first is changing the src on already loaded pages and the second is making the change permanent.
ReactJS is a Framework. At this point we need to define the technical background, since ReactJS will use a possible solution from these.
WebSocket
https://www.npmjs.com/package/react-websocket
This is a WebSocket implementation. The best technical background here is to use WebSockets unless there is a very good reason not to do so.
Server notification system
https://www.npmjs.com/package/react-notifications
Server notification systems in general are one-way ticket roads. The server may send a notification, but the client has no such possibility.
Polling
The browser may periodically send HTTP requests to the server and this way it can receive the src change response. This is a good solution if WebSockets and server notification systems are not an option.
Forever frame
You can use an invisible iframe to be loaded forever, which will provide you with the possibility of sending real-time messages from the server to the client, but this is very hacky.
The difference may be between a front end, running in the browser, or the mobile app, of each user, which is local, and the back end, where you can share data between all users.
This can be implemented by, for example, firebase. Here is an example: Firebase - Multiple users simultaneously updating same object using its old value
This does not mean, obviously, that back end data is always shared... In many cases each user accesses his own copy of back end data that is stored in a database.
Related
This question already has an answer here:
Firing SQL query on click of button?
(1 answer)
Closed 5 years ago.
I have a page where photos are uploaded, when you see the photos there is a button to give you points to the photo.
To the button I gave an onclick with a javascript function that has this php code
function puntos(){
<?php
mysql_query("UPDATE 'fotos' SET 'relevancia=relevancia+1' WHERE 'id = $id'");
?>
}
This is in photo.view.php in photo.php I have this code that retrieves the id of the selected photo
$id = isset($_GET['id']) ? (int)$_GET['id'] : false;
what am I doing wrong?
You're far from home.
Back to basics first:
Server vs. client
mysql and PHP run on the server
JavaScript runs on the client in their browser.
This means javascript cannot access your database directly, you need to do a lot of work before you get there.
Detecting and reacting on a click is something JavaScript can do (and is quite adept at doing).
Communication
Normally when a page downloads it and the components it refers are sent from the server to the client over HTTP.
Once in the browser, to get something back from the client to the server the only way is to send another query or open up some network connection somehow from the client to the server which then transfers that content, or indicates somehow what happened on the client.
Traditionally this meant a form and a click resulting in a GET or POST HTTP request and a reload of the page in the browser.
That's till we got:
AJAX
Essentially the connection from the client to the server can also be initiated by JavaScript itself and it can talk to a server component (just like the browser can) without having to reload a page or having to submit a form or so). This allows one to create things where a click or even a move of the mouse (or anything else JavaScript can detect -it can detect a lot-) can result into data being sent to the server and answers collected by that JavaScript. If it updates the page (aka DOM) is up to the script to chose.
Server Side
Now having JavaScript on the client communicating with the server still isn't going to let said JavaScript update a database. So you need a sever side component that does stringent validations (the code you have above is a horror story from the security side should that ever get to work) and updates a database behind it as needed.
TL;DR
Suggest you read up more on how to do simple AJAX
Some starting points:
https://www.w3schools.com/xml/ajax_intro.asp
https://www.owasp.org/index.php/AJAX_Security_Cheat_Sheet
But there's much more out there for sure.
I'll be as direct and as specific as possible.
I'm trying to create Greasemonkey addon that would create graph of winnings/loses on: dead link
As you can see, site has front page which dinamicly shows results of wins / loses and how much did which user win/loose. What I'm trying to do is catch every new entry so I can draw some grapsh and or statistics for user / users.
When I access div/span that should have data, it turns out to be empty. I know that reason behind this is that all divs with data relevant to me are empty on load and that they get populated later on.
What I don't know is how to access that data. I can see (using firebug console) that there are GET requests executed all the time and that in those get requests is data that I need.
Can someone tell me or at least point me into right direction, how to access that data every time it gets refreshed / inserted?
You can try using the $.ajaxSuccess function to specify a function in your script to be called everytime an ajax request completes in the main page. This'll be fired for every successful ajax request, whether it pertains to the data you're talking about or not, but should allow you to re-scrape that section of the document to grab any and all data in it after every successful request. You may want to wrap your callback function in a setTimeout of some kind to make sure their own callbacks have a chance to fire and inject/modify the content before you scrape it. It should still seem instantaneous to the user if you set a timeout of, say, 1-10ms.
http://api.jquery.com/ajaxSuccess/
Can any one please tell to how to make a desktop client.
I mean i have a frame in which it has a text field and a button.
when i clicked the button i want my text which i have placed in the text field to get placed in the text field of a website and should get processed in a website by a button in the website just like we place our id and password and click sign and the dynamic text produced by the website based on our input should be displayed on my frame.
That means i am operating a website indirectly from the desktop through a java frame.
so i want to know what kind of things i should do in the action listener code of the button.
I know jsps and servlets even but unable link the things to make this application.
Any please do help i m new to development.
I think all you want to do is to make a HTTP request from your application, by passing the value as parameters.
May be a possible duplicate of How to send HTTP request in java?
Go through the link, it may be useful.
Get value from the textField, make HTTP request along with the parameters(obtained from the textField), and you are done.
If you want to open the web browser while requesting, you can make use of Desktop.browse()
You are going to have to use ProcessBuilder (or alternatively Runtime.exec() to execute explorer.exe explicitly with the options you want.
Process p = new ProcessBuilder("explorer.exe", "http://yourpage.com/Myjsp.jsp").start();
You can send the value you want to autopopulate as a pat pf URL parameter like
Process p = new ProcessBuilder("explorer.exe", "http://yourpage.com/Myjsp.jsp?myvar="+my value).start();//where myvalue is String variable where you have the value from Frame.
I think you can use below code...
if(java.awt.Desktop.isDesktopSupported()){ // Desktop Not supported on all Platforms.
Desktop desktop=Desktop. getDesktop();
desktop.browse(new java.net.URI("http://yourpage.com/Myjsp.jsp?myvar="+myvalue));
}else{
Process p = new ProcessBuilder("explorer.exe", "http://yourpage.com/Myjsp.jsp?myvar="+my value).start();
}
This question probably doesn't have an answer. But, I thought I'd give it a shot.
I wrote a great one-page application. When the application starts up, the open tab "registers" itself with the server, which stores is as an "active" tab.
If user A changes XYZ in the workspace, every tab opened on that workspace, by any user, receives a notification that XYZ was changed. That triggers a reload in the clients, which will magically be updated. At the moment, I am doing this by polling. However, when it all works I can use things like WS or Socket.io to make things even faster.
PROBLEM: every tab receives the notification. Even the tab that instigated it in the first place! (as a result, an already-updated screen gets updated)
I somehow need the server to know the tab ID of the tab making the request. Remember that a user might have 5 tabs open: if they change XYZ, all tabs should receive the notification, EXCEPT the one that actually triggered it!
At the moment, I am passing the workspace ID for every Ajax request ( a user might be logged in, and have access to several workspace at the same time).
Solution 1: append both workspace ID and tab ID for every request
Solution 2: only use the tab ID for every request. The app will work out the workspace ID from the tabID (which knows which workspace it belongs to)
Solution 3: ????? (Something that I am missing?)
Any ideas?
Instead of having the server worry about which tabs to send change notifications to you could have the tab that initiated the changes ignore the notification.
Two ways to do this come to mind:
After changing the content a tab will ingore all notifications for a brief period of time. (This will work fine unless changes on multiple tabs happen in a short amount of time.)
Have the tab create a "change id" that it sends to the server with the changes to xyz. The broadcast change notification contains this id and the sending tab recognizes it as the one it sent and ignores it.
You could experiment with HTML5 Visibility API with a fallback to window.onfocus & window.onblur events and suppress updating the page if it's currently visible/active.
I am attempting to track events when links are clicked on my site in a method similar to the following.
Example
<script type="text/javascript">
jQuery(function($) {
// track clicks on all anchor tags that require it
$('a.track').live('click', function(e) {
// send an AJAX request to our event tracking URL for the server to track it
$.get('/events/track', {
url: $(this).attr('href'),
text: $(this).text()
});
});
});
</script>
The problem that I'm having is that a new page load interrupts the AJAX request, and so sometimes these events aren't being tracked. I know Google Analytics has a _trackPageview function that can be attached to onclick events though, and this doesn't seem to be an issue for that. I'm wondering what's different about their call vs. mine that I'm seeing this race condition, and GA isn't. e.g.:
Example
Note that I'm not worried about the result of the AJAX request...I simply want it to ping the server with the fact that an event happened.
(Also, I expect I'll get at least one answer that says to simply track the new page load from the server side, not the client side. This is not an acceptable answer for this question. I'm looking for something like how Google Analytics' trackPageview function works on the click event of anchor tags regardless of a new page being loaded.)
Running Google's trackPageview method through a proxy like Charles shows that calls to trackPageview( ) request a pixel from Google's servers with various parameters set, which is how most analytics packages wind up implementing such pieces of functionality (Omniture does the same).
Basically, to get around ansynchronous requests not completing, they have the client request an image and crunch the parameters passed in those requests on the server side.
For your end, you'd need to implement the same thing: write a utility method that requests an image from your server, passing along the information you're interested in via URL parameters (something like /track.gif?page=foo.html&link=Click%20Me&bar=baz); the server would then log those parameters in the database and send back the gif.
After that, it's merely slicing and dicing the data you've collected to generate reports.
Matt,
If you just want to make sure that the tracking pixel request is made and you don't depend upon response then just doing document.write for the tracking pixel image will do the work.
And you can do the document.write in your onclick handler.
AFA race condition between href and onclick handler of anchor element is concerned the order is well defined.
the event handler script is executed first
the default action takes place afterwards (in this case the default handler is href)
(Source : Href and onclick issue in anchor link)
But yes, if you depend upon the response of the tracking request to the server then you will have to make it synchronous.
Suggested option would be to call some javascript function to wrap the already defined onclick handlers and then in the order make the calls. Make sure that your tracking request is not asynchronous.
Though it is suggested that you should not be dependent upon the response of the tracking pixel request.