Send data to JS when PHP is told to do so - javascript

Here's an example. One user connects to the website and does some stuff. JS sends changes to PHP and it's processed. Say another user that connected at the same time needs to be notified of this change. So PHP somehow tells the second users browser through JS or something to change some HTML to the second user is aware of said changes. Is there a way I can do this? Or is it a no can do?

You need websocket (http://socketo.me/) to do that or use pusher (https://pusher.com/) to push something to client.

that would be done with Ajax or WEbSockets.
WebSocket works by opening a connection channel between the server and users.
you can find some websocket Examples Here:
http://www.websocket.org/demos.html

you can use this
$.ajax({
url: "url",
type: "POST",
data: params,
success: success(){},
error: error()
});

Related

Ajax and page refresh

I am building a web app and one of the functionalities is to trigger an action in the backend which can take up to 5 minutes. This 'action' is a process which will run totally on its own (regardless of the front-end/back-end of my web app).
There is a form on the client-side which I use JavaScript to grab the data, clean it up/validate and send an Ajax call to my backend to start the process (which can take up to 5 minutes).
My question is, what if the user refreshes the page? The backend will still be triggered and run on its on, but I wanted to be able to capture the response back to the browser once the process is done in the back end. Is that viable/possible?
My Ajax is a pretty simple POST request to my backend:
$.ajax({
type: 'POST',
url: '/add-user',
data: {'data': JSON.stringify(data)},
//contentType: 'application/json;charset=UTF-8',
success: function(response){
console.log(response['message'])
}
//timeout: 3000 // sets timeout to 3 seconds
});
Please refer to this question prompt-user-before-browser-close
The only solution is to display a loading bar or spinner on the page while your page is waiting for the server task to finish.
If the user wants to navigate away you can use the confirm prompt.
I highly suggest using a websocket connection and if the user really closes, then inside window.onbeforeunload you should send a message and notify the backend to cancel the request context and stop the task from running. Running something like this without this protection can make your backend easy to get bombed.
PS. If it's a process independent of your backend then you should have scripts in place to kill it if the request context is canceled.

How to run a java program through a JavaScript page?

I have a java program to scan vehicle's number plate and i want to call this program through a JavaScript page i.e. When I click a button on my JavaScript page it should execute my java program . I know there are similar questions on stackoverflow, but none was clear enough for a beginner like me to understand. New to JavaScript, any help would be highly appreciated. Thank you in advance.
While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
You can do it with AJAX.
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.
A simple example would be something like this
$.ajax({
type: 'POST',
url: 'http://localhost:8080/MyMethod',
data: JSON.stringify({"string" : "anything you want to send to your method"}),
contentType: "application/json",
error: function() {
alert("Failed");
},
success: function() {
alert("Success");
}
});
That depends on where you would like to run it on.
1.client side
The only method to get java codes running directly on client side, is to use a java applet. Write an applet,write your html properly, then you are all set.
Or, you may want a wasm/javascript compiler for java.
2.server side
you should setup a mechanism letting your frontend to raise the backend.
for frontend, you should be able to send certain requests. you can choose http request, aka XHR/AJAX, or, you can choose web socket. they are similar things.
For backend, if you let your httpd handle the very request, then you should have your httpd notify your code for that. The solution if different for different httpds.
If you want to handle the request directly, then you can just listen to the very port and do the regular things. You should be responsible for security issues.

how to pull data from browser using ajax and store in my mongoDB

I'm a beginner in coding, and I am making a front and back end prototype website. Written with node/express/javascript
I have a Google Map API, where when I click a button I can console log the location. I am able to retrieve the co-ordinates via the console, but I want to take these coordinates and store them in my mongodb to then post back onto my map api. Any ideas of the best way to do this? Preferably using ajax?
typically you need to have ajax call to your server from javascipt/jquery
<script>
$(function(){
$.ajax({
type: "POST",
URL: [server url],
data: [data to be sent to server]
success: function (response){
//this is your server callback
}
})
});
</script>

MediaWiki: How do I use an AJAX POST in JS to send data to a custom API extension (PHP)?

I've been stumped on this for a while. I've successfully created a MediaWiki API extension from which I'm able to extract data using an API url, but now I want to go the other way. I want to use JS to send a simple bit of data to the server for storage in a session variable (in PHP). I've experimented with something like the following:
$.ajax({
// start POST request
type: "POST",
// url to which the request is sent
url: "/",
// data to the server
data: { myvariable: 0 },
// Type of data
dataType: 'json',
// Funciton to be called if the request succeeds
success: function( data ){
console.log("POST successful with " + data);
}
})
What I don't fundamentally get is how to "pick up" the POSTed data in PHP. In my research, I came upon something saying I should look for $_POST['myvariable'] in PHP. Yet I'm not sure how or where I'd create something that would listen for such a POST from JS. It seems to me the easiest solution to this would be if I could write a method onto my API extension that simply assigns the value of the myvariable that's POSTed to the session variable whenever that thing is POSTed. I've written this method already, in fact, but it's unclear to me how I'd instruct AJAX to invoke it in PHP. I've also read that this type of thing may not be advisable for security reasons.
I've seen advice elsewhere suggesting I should do something in JS like:
var api = new mw.Api();
...and then use the Api object's methods to execute Ajax GET and POST requests. Well, I tried creating an instance of this object, and it throws errors on the console that say it's not a recognized function or something of that nature.
I'm rather new at all this, but I'm at my wit's end trying to figure out something that in theory ought to be very simple. Any suggestions?

How should I handle many AJAX calls?

I am trying to write a plugin which will work a lot with my server. Every page load will invoke an AJAX call to my server for data, the server should return a simple string.
Now I am trying to understand what would be the best aproach for this type of program.
Should I just create an AJAX call every time I need the data or is there some method I could create an open connection (despite the change of webpages) to save on server power?
Should I somehow listen to some port or something of the sort?
Do I have other options or what should I do to do this the most efficient way?
You can use HTML5 websockets (http://www.html5rocks.com/en/tutorials/websockets/basics/)
If you use this approach, then you will need to re-think the way you program your webserver, since websockets don't follow the request-response paradigm AJAX do. Instead they use a connection to stream data so you will need to open a port on your server and listen to it, the way to do it depends on the language or framework you are using. This is fast and responsive but will only work on most modern browsers.
Other approach is using Long Polling (http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery). This is used by some chat clients. It works sending an AJAX request to the server, the server receives it and keeps it waiting until the data is available and then the response is sent. Then the client makes another request, waits and repeats.
Probably you will almost never want to send simple strings to the client. It's almost always better to use XML or JSON to encode the response.
Just create a simple AJAX call and put it on each page, or save it as it's own file and put a server include on each page in the header. Simple as that!
$(document).load(function(){
$.ajax({
type: "POST",
url: "/where_your_string_is.php",
success: function(msg){
$("#stringHolder").html(msg);
}
});
});
Websockets API allows bi-directional communication, but I've just found that there's another option called HTML SSE that might be used if you only need to pull data. So if you've stumbled upon this question, consider this option as well.

Categories