i am planning to implement chat application using ajax, java script in front and java rest api in back . everything is going well, but whenever i try to open multiple chat boxes to chat with multiple user. i am struggling to create different chat boxes associated with different users. my entire front-end code is below . Can somebody please help me? thanks in advance...
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat Application</title>
<style>
.userListDiv{
border:1px solid blue;
overflow: auto;
width:500px;
}
#messageBox{
border:2px solid black;
overflow: auto;
height:auto;
width:300px;
}
#messageInput{
size:100px;
border:1px solid black;
}
</style>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Raleway'
rel='stylesheet' type='text/css'>
<link rel="stylesheet"
href="//cdn.jsdelivr.net/jquery.sidr/2.2.1/stylesheets/jquery.sidr.light.min.css">
</head>
<body>
<button id='myId' value =userId></button>
<div class="userListDiv"></div>
<div class ="chatbox">
<div id ="messageBox">
</div>
</div>
<script>
var baseUrl="http://localhost:8080/sampleHospital/webapi/";
$(document).ready(function(){
$('#myId').hide();
$('.chatbox').hide();
var timeOut = 1000;
$.ajax({
url: baseUrl+"users",
method:"GET",
datatype:"xml",
success:getUsers,
error: function(xhr,ajaxOption,thrownError){
console.log(xhr.status);
console.log(thrownError);
}
}, timeOut);
});
function sendMessage(senderId,recieverId){
var Inputmessage= $('.messageInput').val();
var message = $.parseXML('<message><date></date><id></id><senderID></senderID><recieverID></recieverID><content></content></message>');
var $messageXml = $(message);
$messageXml.find('content').append(Inputmessage);
$messageXml.find('senderID').append(senderId);
$messageXml.find('recieverID').append(recieverId);
console.log(message);
$('.messageInput').val="";
$.ajax({
url: baseUrl+"messages/",
type:"POST",
dataType:'xml',
data:message,
processData:false,
contentType:"application/xml",
success: getMessage,
error: function(xhr){
console.log(xhr.status);
console.log("error!!!");
}
});
}
function requestMessage(senderID, recieverID){
var timeInterval = 1000;
$(".chatbox").fadeIn(500);
$(".chatbox").append("<div id ='chatContainer'></div>");
$('.chatbox').append('<input type="text" class="messageInput" placeHolder="your message here"/><button class="sendMessage" onclick="sendMessage(1,2)">send message</button>');
$.ajax({
url:baseUrl +"messages/"+senderID +"/"+ recieverID,
method:"GET",
datatype:"xml",
success :getMessage,
error: function(xhr ,ajaxOptions,thrownError){
console.log(xhr.status);
console.log(thrownError);
}
}, timeInterval);
}
function getMessage(data,status){
console.log("getting messages");
console.log(data);
var messageBox =$("#messageBox") ;
messageBox.empty();
messageBox.append($('<ul id ="messagesList"></ul>'));
$(data).find('message').each(function(){
var message = $(this).find('content').text();
var date = $(this).find('date').text();
var sender = $(this).find('senderID').text();
var receiver = $(this).find('recieverID').text();
console.log(message);
$("#messagesList").append('<li>'+message+'</li>');
});
}
function getUsers(data,status){
console.log("getting users list");
console.log(data);
var userListBox = $(".userListDiv");
userListBox.empty();
userListBox.append('<ul class="usersList"></ul>');
$(data).find('user').each(function(){
var name = $(this).find('fullName').text();
var otherid = $(this).find('id').text();
var myId =2;
// console.log(name,otherid);
$('.usersList').append('<li class='+name+' onclick="requestMessage(1,2)"><a href="javaScript:void(0)">'+name+'</li>');
});
}
</script>
</body>
</html>
in the request message you are trying to create chatcontainer div. For any user you are using same div id so you wont be able to update the values properly. You should create the id uniquely may be appending with receiver id. More over if div with that id is there then you should not create it again. you should use the existing div and update the messages.
Related
I am trying to publish my vector layers in geoserver as WFS using the Leaflet library and I get the error like in the picture. How can I fix this error and is there any other way to publish WFS with leaflet?
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src=" https://unpkg.com/leaflet#1.2.0/dist/leaflet.js "></script>
<link rel="stylesheet" href=" https://unpkg.com/leaflet#1.2.0/dist/leaflet.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js" ></script>
<style>
#map {
width: 100%;
height: 600px;
box-shadow: 5px 5px 5px #888;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map = L.map('map').setView([0, 0], 2);
var owsrootUrl = 'http://localhost:8080/geoserver/ows?';
var defaultParameters = {
service: 'WFS',
version: '1.1.0',
request: 'GetFeature',
typeName: 'webalani:il',
outputFormat: 'application/json',
};
var parameters = L.Util.extend(defaultParameters);
var URL = owsrootUrl + L.Util.getParamString(parameters);
$.ajax({
url: URL,
success: function (data) {
var geojson = new L.geoJson(data, {
style: {"color":"#2ECCFA","weight":2},
}
).addTo(map);
}
});
</script>
</body>
</html>
You are attempting to run your leaflet file directly by double clicking on the file location on your disk. This will not work as the AJAX methods you are using require a web server to be used instead.
Make sure you are looking at http://localhost.... not file://..... in your browser bar and all will be well.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I have a html form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=1.0, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form id="formGIT">
<input type="text" name="GitHubUsername" id="GitHubUsername">
<input type="submit" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
In scripts/app.js what I want is to get the github-api data in a variable using jQuery. For that, I have tried,
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
$('#formGIT').on('submit', function(e){
var githubusername = $('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
});
alert(githubAPIMainStream);
});
});
But, what I am getting in the githubAPIMainStream variable is a null. It would be helpful, If someone tell me what is going wrong.
$.getJSON retrieves data from a URL, and then passes it into a callback function as 'data', within the function you then need to use it. Where you're declaring githubAPIMainStream = data, you then need to alert it afterwards.
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
$('#formGIT').on('submit', function(e){
var githubusername = $('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
alert(githubAPIMainStream);
});
});
});
EDIT Working snippet without the form submit
var githubAPIMainStream = null;
var url = null;
$(document).ready(function(){
//$('#formGIT').on('submit', function(e){
var githubusername = "shunjid"; //$('#GitHubUsername').val();
url = 'https://api.github.com/users/'+githubusername;
$.getJSON(url, function(data) {
githubAPIMainStream = data;
console.log(githubAPIMainStream);
});
//});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
I'm building a project made of several jquery mobile pages, each has a navbar.
when I view each page the $(document).ready function fires up well, but when I go to the page through the navbar it won't fire up.. also in the chrome debugger I see only one html page (the one I'm currently viewing) in the source folder.
when I refresh the page the function works ok
tried to replace the "$(document).ready(function () {" with:
"$("div[data-role*='page']").live('pageshow', function(event, ui) {" as someone suggested
but that doesn't work as well.
that's the first page I load:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table class='CSSTableGenerator'>";
$.each(parsedData, function () {
tableStr += "<tr><td>" + this.fName + "</td><td>" + this.lName + "</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
<body>
<div id="page1" data-role="page" data-theme="a">
<div data-role="header" data-theme="a">
<h1>חברי העמותה</h1>
</div>
<div data-role="navbar">
<ul>
<li>חברי העמותה</li>
<li>בניית צוות</li>
<li> בדיקה</li>
</ul>
</div>
<div data-role="content">
<div id="tableDiv"></div>
</div>
<div data-role="footer">
<h1>footer area</h1>
</div>
</div>
</body>
</html>
And below are the second and third page's head:
build.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function save_crew()
{
p_num = new Object();
p_num.p1 = p1.value;
p_num.p2 = p2.value;
p_num.p3 = p3.value;
p_num.p4 = p4.value;
l_num = new Object();
l_num.l1 = l1.value;
l_num.l2 = l2.value;
l_num.l3 = l3.value;
s_num = new Object();
s_num.s1 = s1.value;
s_num.s2 = s2.value;
s_num.s3 = s3.value;
var photo = { 'p1': p_num.p1, 'p2': p_num.p2, 'p3': p_num.p3, 'p4': p_num.p4 };
var light = { 'l1': l_num.l1, 'l2': l_num.l2, 'l3': l_num.l3, 'l4': l_num.l4 };
var sound = { 's1': s_num.s1, 's2': s_num.s2, 's3': s_num.s3, 's4': s_num.s4 };
// Put the object into storage
localStorage.setItem('photo', JSON.stringify(photo));
localStorage.setItem('light', JSON.stringify(light));
localStorage.setItem('sound', JSON.stringify(sound));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('sound');
var ro = JSON.parse(retrievedObject);
alert(ro.s2);
window.location.href="test.htm";
}
</script>
</head>
test.htm:
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/jquery.mobile-1.2.0.min.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.2.0.min.js" type="text/javascript"></script>
<link href="css/TableCSSCode.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
var sound_RO = localStorage.getItem('sound');
var photo_RO = localStorage.getItem('photo');
var light_RO = localStorage.getItem('light');
sound_RO = JSON.parse(sound_RO);
photo_RO = JSON.parse(photo_RO);
light_RO = JSON.parse(light_RO);
$.each(sound_RO, function (index, value) {
alert(value);
});
$.ajax({
type: "POST",
url: "getdata.aspx/return_prof",
data: "{prof:'צלם'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
var parsedData = JSON.parse(res.d);
$('[data-role="content"]').append('<div id="collapsible-set" data-role="collapsible-set"></div>');
$("#collapsible-set").append('<div id="collapsible" data-role="collapsible"></div>');
$("#collapsible").append('<h3>צלמים </h3>');
for (i = 0; parsedData[i] != null; i++) {
$("#collapsible").append('<p>' + parsedData[i].fName + ' ' + parsedData[i].lName + '</p>');
}
$('[data-role="content"]').trigger('create');
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
</script>
</head>
Reason
When jQuery Mobile loads pages after the initial one (with ajax), it will only load its BODY content, which means any js or css file initialized in HEAD (and if it is not initialized in first loaded HTML) will be disregarded. So all your custom js code will never be executed.
Solution
Move all of your js code into the first HTML file
You should create a new js file, name it whatever you want. Put all of your js code (from every page) into it. Then initialize it in the first HTML file to load.
Move your js code into the page BODY
Simply open every page and move its javascript code from HEAD to the BODY. Because of this, javascript code will be loaded into the DOM and executed when page is shown.
Final thoughts
All of this is described in more details + examples in my other answer/article: Why I have to put all the script to index.html in jquery mobile
You should also think about switching to the jQuery Mobile page events instead of document ready. Document ready usually works correctly but sometimes it will trigger before page is loaded into the DOM. That why jQM page events must be used instead. They will make sure page content is triggered only after page is safely loaded into the DOM. To find out more take a look at this answer/article: jQuery Mobile: document ready vs page events
I am loading a HTML file file from server inside UIWebView. In HTML file, we have external links to open and a Javascript function is written to handle that events.I want to open that hyperlinks inside a seperate new webview within the app.
Is there any way that server side javascript method notify to objective-C or any callback function which will call in objective-C and then i can do someting in my code? i have seen the example of WEBViewJavaScriptBridge to communicate between javascript and objective C. but they are using the local HTML file to load and communicate.Bt my HTML file is on server side.It would be great if anyone can help on this.
I am puuting a sample HTML file here. We have two hypelinks "Open" and "Close" on taping on open button a function is called that show alert. so instead of alert i want to pass the retuen callback to objective-C code.
Here it is:-
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width = device-width, initial-scale = 1.0, maximum-scale = 1.0, minimum-scale = 1.0, user-scalable=no"/>
<meta name="HandheldFriendly" content="True"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>Test HTML</title>
<script type="text/javascript">
function open(url, offset){
alert("Open Webview with url:"+ url + " & Offset: " + offset);
}
function close(url, offset){
alert("close webview");
}
</script>
</head>
<body>
Open<br>
Close
</body>
</html>
I used webviewjavascriptbridge to communicate javascript and objective C code.
In this example code, note the global variable of bridge.
<!doctype html>
<html><head>
<style type='text/css'>
html { font-family:Helvetica; color:#222; }
h1 { color:steelblue; font-size:24px; margin-top:24px; }
button { margin:0 3px 10px; font-size:12px; }
.logLine { border-bottom:1px solid #ccc; padding:4px 2px; font-family:courier; font-size:11px; }
</style>
</head><body>
<h1>WebViewJavascriptBridge Demo</h1>
<script>
window.onerror = function(err) {
alert('window.onerror: ' + err)
}
var bridge;
document.addEventListener('WebViewJavascriptBridgeReady', onBridgeReady, false)
function onBridgeReady(event){
alert("Onbridge ready call");
bridge = event.bridge
var uniqueId = 1
function log(message, data) {
var log = document.getElementById('log')
var el = document.createElement('div')
el.className = 'logLine'
el.innerHTML = uniqueId++ + '. ' + message + (data ? ': ' + JSON.stringify(data) : '')
if (log.children.length) { log.insertBefore(el, log.children[0]) }
else { log.appendChild(el) }
}
bridge.init(function(message) {
log('JS got a message', message)
})
bridge.registerHandler('open', function(data, response) {
log('JS handler testJavascriptHandler was called', data)
response.respondWith({ 'Javascript Says':'open open open!' })
})
bridge.registerHandler('testJavascriptHandler', function(data, response) {
log('JS handler testJavascriptHandler was called', data)
response.respondWith({ 'Javascript Says':'Right back atcha!' })
})
var button = document.getElementById('buttons').appendChild(document.createElement('button'))
button.innerHTML = 'Send message to ObjC'
button.ontouchstart = function(e) {
e.preventDefault()
bridge.send('Hello from JS button')
}
document.body.appendChild(document.createElement('br'))
var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'))
callbackButton.innerHTML = 'Fire testObjcCallback'
callbackButton.ontouchstart = function(e) {
e.preventDefault()
log("Calling handler testObjcCallback")
bridge.callHandler('testObjcCallback', {'foo': 'bar'}, function(response) {
log('Got response from testObjcCallback', response)
})
}
}
function open(url, offset,e)
{
alert(bridge);
//alert("Open Webview with url:Yes Got it");
// alert(document.getElementById(offset).href);
// var bridge = event.bridge;
// alert(bridge);
window.location = url+'?offset='+offset//'myapp:myaction:url:offset'
//requestFromObjc("buttonColor&someParam=1");
}
function close()
{
alert("Open Webview with url:"+ url + " & Offset: " + offset);
}
function requestFromObjc(functionName, objcResult, callback)
{
if (!objcResult)
{
window.location = 'myapp:myaction:param1:param2'
// window.location = "myapp://objcRequest?function=" + functionName + "&callback=" + arguments.callee.name + "&callbackFunc=" + arguments.callee.caller.name;
}
else
{
window[callback](objcResult);
}
}
</script>
<div id='buttons'></div> <div id='log'></div>
<body>
<a id="55" href="javascript:open('http://www.tcm.com', '55',this)">Open</a><br>
Close
</body>
</body></html>
Reference: https://github.com/marcuswestin/WebViewJavascriptBridge
You can communicate with your HTML from objective c with the following webView delagate methods...
- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
Please go through the usage of these methods...
I hope this may help you