broadcast message to all online users jsp ajax - java

I am trying to broadcast a message entered by an admin to be visible to online users as a pop up. i am using ajax to make a call to database with a time interval like the code below. This code runs for each and every online users and returns message if the message_Flag is 1 in the database
setInterval( function()
{
getChatText();
}, 5000);}
function getChatText() {
$.ajax({
type : "POST",
url : "/easyoffice/commonAjax.do",
data : "method=" + "getMessages",
success : function(responseText) {
if (responseText.trim() != ''){
$("#dialog-message").html(responseText);
$("#dialog-message").dialog({
modal: true,
draggable: false,
resizable: false,
position: ['center'],
show: 'blind',
hide: 'blind',
width: 400,
dialogClass: 'ui-dialog-osx',
buttons: {
"I've read and understand this": function() {
$(this).dialog("close");
}
}
});
}
},
error : function(e) {
alert('Error: ' + e);
}
});
}
This is working correctly , but being a webapp with a lot of users , this causes a performance drop. I've heard websockets doesn't support Broadcasting. Is there any alternative .?? Thanks in advance

Related

rest controller works but ajax post method return an error

I'm making a post method using $.ajax which is this
$(function(){
$("#postMembers").click(function(){
let member ={
firstName: "khookina",
lastName : "khooak",
age:1,
sex:"female",
duty:"undefined",
dailyJeton:2
}
$.ajax({
type: "post",
url: "http://localhost:8080/RCP2/members",
data: member,
dataType: "application/json",
success: function (response) {
alert("success");
},
error: function(error){
alert("error");
}
});
});
and my rest controller is this
#PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String createMembers(Member member) {
if (member.hasError()) {
throw new CreatePersonException("All the fields must be filled properly in order to create a new member.");
}
if (personDao.createMember(member)) {
return "Member: " + member.getFirstName() + " " + member.getLastName() + " successfully created.";
}
return "couldn't create member, please try again later.";
}
I have a create member button in the webpage that executes this ajax post method, when I press it, everything works fine, the member information gets sent to the rest controller, It gets created (100% working) and returns {"readyState":4 status":200, "statusText":"parsererror"} and error: function(error) of ajax post method gets called
What's the problem?
it's the first day I'm working with ajax and javascript, I don't really understand what's happening.
Thanks in advance
P.S I've tried changing data-type text json, json and some others that been suggested in similar questions, but they didn't work for me, so i decided to make a question myself.
Try changing
data: JSON.stringify(member) and you will have your response in your success in the result/
Remove data type from ajax request and it works.
Remove this.
dataType: "application/json"
For details refer this

Open app when clicking push notification

I have an Ionic app which receives push notifications via FCM. The problem is that when the app is not in the foreground and I click on the notification on the status bar, the app won't open (although the action from on('notification') is executed). This is my mobile app code:
this.pushNotifications.on('notification').subscribe((data: any) => {
if (data.additionalData.foreground) {
alert('Ai primit un mesaj nou');
}
this.events.publish("gotMessage");
});
Notice that this.events.publish("gotMessage"); is executed.
And this is how I send the notification through Java:
Map body = DataMap.map(
"registration_ids", tokens,
"data", DataMap.map(
"content-available", "1",
"title", "Fmcg Reporter",
"body", "Ai primit un mesaj nou",
"sound", "default"
),
"collapse_key", "FmcgReporter"
);
Map headers = DataMap.map(
"Authorization", "key=" + key,
"Content-Type", "application/json"
);
Strings.readMethodURL("POST", "https://fcm.googleapis.com/fcm/send", headers, Strings.toJSON(body));
Make sure when you send push notification using your server you specify "click_action". Below is a working example from my node.js server:
// method: "POST",
//url: "https://fcm.googleapis.com/fcm/send",
// get the key from Firebase console
headers: { Authorization: `key=${fcmServerKey}` },
json: {
"notification": {
"title": "Message title",
"body": "Message body",
"click_action": "URL to your app?"
},
// userData is where your client stored the FCM token for the given user
// it should be read from the database
"to": userData.fcmRegistrationKey
}

Javascript: Disable button based on server status

I'm very new to Javascript and I have a button that need to be constantly checked against whether a server is active or not.
I'm using the Play framework based in Java. I already have a class ServerStatus that returns whether a service is healthy or not but I am not sure how to link this into my page which contains the button.
Basically, what I want is that if the server goes down then I want the button disabled so that the user cannot use it while the server is unavailable.
I looked a bit at Websockets and that looks really complex. I wasn't sure if there is a simpler way.
EDIT
Using Websockets: I had a read around and it seems I need to use the onmessage event. I found some sample code but I am not sure how to put this into my (document).ready function.
Below I have some code:
$(document).ready(function(){
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
var chatSocket = new WS("routes");//This does not seem to accept any #routes
var lastState = 'unknown';
chatSocket.onmessage = function(e){
var server_message = e.data;
//do something here about enabling and disabling
console.log(server_message);
}
});
function disable()
{
//disable all buttons
}
function enable()
{
//enable all buttons
}
I am lost as to how to add the websocket here.
I am borrowing heavy from this similar question and answer
The basic code is here:
var isNotWorking = false;
var myFunc = function(){
$.ajax({url: "YOUR_URL_HERE",
type: "HEAD",
timeout:1000,
statusCode: {
200: function (response) {
//alert('Working!');
isNotWorking =false;
},
400: function (response) {
//alert('Not working!');
isNotWorking = true;
},
0: function (response) {
//alert('Not working!');
isNotWorking = true;
}
}
});
$('#mybutton').prop('disabled', isNotWorking);
doSetTimeOut();
}
var doSetTimeOut = function(){
setTimeout(function(){
myFunc();
}, 1000);
}
doSetTimeOut();
See a working JS fiddle here

How to Handle Popup Window in Spring?

In my Spring Application have Display some Existing Users in Database In Jsp
<a id="details" href="#"class="copyright-text read_link" title="FAQs" onclick="sendForm()";>
<label for="subject">${user.name}</label>
</a>
When we Click above Hyper link one Popup will open and show his Details
And my Controller class i'm mapping action to hyperlink click event.
#RequestMapping(value = "search", method = RequestMethod.POST)
public String header(SearchForm form, BindingResult result,
Model model) throws Exception {
-----
-----
model.addAttribute("SEARCH_RESULT", form);
return "search";
}
So this search.jsp should display on above popup window.
In this Purpose i'm doing like this..
Prepare ajax form submitting , i'm writing success event so popup.
function ajaxFormSubmit(options) {
$.ajax({
url : options.action,
success : function(data, textStatus, jqXHR) {
$('#' + options.successElem).html(data);
}
},
error : function(jqXHR, textStatus, errorThrown) {
apprise(textStatus +" " + errorThrown);
}
});
}
But this is not working. so is this procedure correct or not ?
Other wise tell me how to Open popup window in Spring ?
According to your code, HTTP method is specified as POST in the #RequestMapping, while GET method is used for sending the ajax request. Is this the cause of your problem?

facebook login Server-side Apps with javascript sdk

I have searched stackoverflow for an full example or some blog that explains how to make facebook login Server-side Apps with javascript sdk
but didn't find anything.
I have searched developer.facebook.com site and the only thing i have got was a php example https://developers.facebook.com/docs/howtos/login/server-side-login/.
The problem is that i must use JavaScript.
Why should i want to do that?
The reason is that i want to upload files to the server(google-app-engine(Java Sdk)) and save them on the db with the facebook user id and retrieve them by his user id.
another question is, how can i debug my javascript code if he uploaded dynamically?what about code assist?
Well I can help you with this issue. If you need to use the JS SDK of FB, then you have to do everything on the client side or on browser, because Facebook doesn't have any support for Java on Server Side.
So I suggest you that you can authenticate user on client, define your scopes for accessing user profile, once authenticated by user you will get response as JSON Object which you can send using ajax to AppEngine Backend.
I am sharing my link where I used FB Login and accessing User's Profile Information along with his photos in albums and videos.
http://demositeunicfyp.appspot.com/fb-pictures.html
http://demositeunicfyp.appspot.com/facebook.html
You can Debug the JS Code in your browser to see what kind of response object you are getting back from Facebook APIs.
$(document).ready(function() {
// Initializing the Facebook SDK
FB.init({
appId : 'XXXXXXXXXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
// Method to check if a user is looged in to FB or Not
FB.getLoginStatus(updateButton);
$("#logout").live("click", function(event) {
event.preventDefault();
// FB.getLoginStatus(updateButton);
FB.logout(function(response) {
$("#loginDiv").show();
$("#logoutDiv").hide();
});
});
$("#fbLoginButton").live("click", function(event) {
//event.preventDefault();
FB.getLoginStatus(updateButton);
});
function updateButton(response) {
var button = document.getElementById("fbLoginButton");
if (response.authResponse) {
// user is already logged in and connected
// button.innerHTML = 'Facebook Logout';
//$("#loginDiv").hide();
//$("#logoutDiv").show();
//window.location = '/confirm';
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
// user is not connected to your app or logged out
// button.innerHTML = 'Facebook Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
// button.innerHTML = 'Facebook Logout';
$("#loginDiv").hide();
$("#logoutDiv").show();
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
//user cancelled login or did not grant authorization hence do nothing
}
}, {
scope : 'email,publish_actions'
});
}
}
}
});
Taken from JS.php in SDK download
<?php
require '../folderTo/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('me?fields=photos'); } catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Working example here: http://slicethegreen.com/examples/js.php

Categories