$(document).ready function won't fire up - javascript

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

Related

JS, how can i refresh the page or div when json data changed?

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);

PDO and ajax call

I am new to PHP-PDO and need some assistance. My application routes all controllers to the index.php though a routes.php file. For example, when my sign-up form is submitted the form is handled action=index.php?controller=signup&action=createuser. The routes.php computes this creates a new signupcontroller($_POST) object and calls createuser(). Once the user is created a welcome page is required_once, which, with javascript, I build a grid of check-boxes. After the check-boxes are built with jquery onchange that makes a ajax call, or supposed to create an ajax, but does not work.
The url is suppose to send params with it to change the controller and action in order to call an appropriate function, and store the check-box option. However, when I check the box nothing happens.
ajax call:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
var str = $('#interests').serialize();
$.ajax({
type: 'POST',
url: 'index.php?controller=interest&action=set_user_interest',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
});
routes.php
function call($controller, $action){
require_once('controllers/' . $controller . '_controller.php');
// create a new instance of the needed controller
switch($controller) {
case 'interest':
require_once 'models/interest.php';
$controller = new InterestController();
}
// call the action
$controller->{ $action }();
}
// just a list of the controllers we have and their actions
// we consider those "allowed" values
$controllers = array(
'interest'=>['set_user_interest', 'error']
);
// check that the requested controller and action are both allowed
// if someone tries to access something else he will be redirected to the error action of the pages controller
if (array_key_exists($controller, $controllers)) {
if (in_array($action, $controllers[$controller])) {
call($controller, $action);
} else {
call('landing', 'error');
}
} else {
call('landing', 'error');
}
index.php
<?php
session_start();
require_once('greenCupOfWater.inc');
if (isset($_GET['controller']) && isset($_GET['action'])) {
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = 'landing';
$action = 'landing_page';
}
require_once 'views/layout.php';
?>
layout.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1">
<title>Witit</title>
<link rel="icon" type="image/png" sizes="32x32" href="../images/icons/favicon-32x32.png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link href="https://fonts.googleapis.com/css?family=Work+Sans:100" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="stylesheets/master.css">
<link rel="stylesheet" href="stylesheets/welcome.css">
<link rel="stylesheet" href='stylesheets/<?php echo $controller ?>.css'>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<?php include 'routes.php'; ?>
<script src="scripts/main.js" charset="utf-8"></script>
<script src="scripts/modalHelper.js" charset="utf-8"></script>
</body>
</html>
javascript files:
function build_interest(it, src){
var intrst = it;
var htag = it+"-header";
//var chng = 'this.form.submit()';
var ctr = document.createElement('div');
ctr.setAttribute('class', 'interest_container');
var lbl = document.createElement('label');
lbl.setAttribute('for', intrst);
var img = document.createElement('img');
img.setAttribute('src', src);
var title = document.createElement('h2');
title.setAttribute('id', htag);
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', intrst);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', intrst);
inp.setAttribute('name', intrst);
inp.setAttribute('value', 1);
lbl.appendChild(img);
ctr.appendChild(lbl);
ctr.appendChild(inp_f);
ctr.appendChild(inp);
ctr.appendChild(title);
var elem = document.getElementById('interests');
elem.appendChild(ctr);
document.getElementById(htag).innerHTML = it;
}
function myFunc(obj) {
var num = 0;
for (var src in obj) {
if ((obj.hasOwnProperty(src))&&(obj[num].Interests_Pix!==null)) {
build_interest(obj[num].Interests, obj[num].Interests_Pix);
}
++num;
}
}

Ajax call does not work properly and refreshing table data with ajax call

I am currently developing a web app. What i need, first of all, is when my html page loads, to invoke an ajax call to my servlet, which will search a database and return as response all the entries of a table as an html table. Whatever i have tried this does not seem to work, although i am using a ready function in which i do the ajax call.
Secondly when my html table is created, a verify button is added to unverified entries. What i need is when i press the verify button to call my servlet, update my database and then refresh my html table.
adminPage (servlet)
public class AdminPage extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String result = "";
System.out.print("in get");
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "Sk1994!!");
PreparedStatement ps = con.prepareStatement("select * from user");
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int accepted = 0;
result = "<table class='table table-striped'><thead><tr>";
for (int i = 1; i <= numberOfColumns; i++) {
String name = rsmd.getColumnLabel(i);
System.out.println("h sthlh legetai: |" + name + "|");
if (name.equals("accepted"))
accepted = i;
result += "<th>" + name + "</th>";
}
System.out.println("column is: " + accepted);
result += "<th>Verification</th></tr></thead><tbody>";
while (rs.next()) {
boolean verified = true;
result += "<tr>";
for (int i = 1; i <= numberOfColumns; i++) {
result += "<td>" + rs.getString(i) + "</td>";
if (accepted == i)
if (rs.getString(i).equals("0"))
verified = false;
}
if (verified)
result += "<td></td></tr>";
else
result += "<td><button onclick='runPop(this);'>Validate</button></td></tr>";
}
result += "</tbody></table>";
con.close();
} catch (Exception e) {
e.printStackTrace();
}
out.println(result);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.print("in post");
String uname = request.getParameter("uname");
System.out.println("Arxise");
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "Sk1994!!");
PreparedStatement ps = con.prepareStatement("update user set accepted=? where username=?");
String newValue ="1";
ps.setString(1, newValue);
ps.setString(2, uname);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using bootstrap and angular in my html page, i have removed most the included things
Js and ajax calls
function myFunction() {
$.ajax({
type: 'GET',
url: '../adminPage',
success: function(data) {
$("#result").html(data);
}
});
}
$(document).ready(function() {
myFunction();
});
function runPop(el) {
var report = el.parentNode.parentNode.cells[1].innerHTML;
$.ajax({
type: 'POST',
url: '../adminPage',
data: {
"uname": report
},
success: function(data) {
$.ajax({
type: 'GET',
url: '../adminPage',
success: function(data) {
$("#result").html(data);
}
});
}
});
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>Tempting EveryDay</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">-->
<link href="../css/jquery.datetimepicker.min.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'>
<!-- Theme CSS -->
<link href="../css/agency.min.css" rel="stylesheet">
<link href="../css/mycss.css" rel="stylesheet">
<link href="../css/agency.css" rel="stylesheet">
</head>
<body>
<div id="result"></div>
<button type="submit" onclick="myFunction();">press me</button>
<!-- jQuery -->
<script src="vendor/jquery/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<!-- Contact Form JavaScript -->
<script src="../js/jqBootstrapValidation.js"></script>
<script src="../js/contact_me.js"></script>
<!-- Theme JavaScript -->
<script src="../js/agency.min.js"></script>
<!-- Angular js -->
<script type="text/javascript" src="../js/angular.min.js"></script>
<script type="text/javascript" src="../js/app.js"></script>
</body>
</html>
The output i want is this:
wanted output
i ve managed to show it by adding a button to do the ajax call manually, but even then, when i press the validate button, ajax post is not done and servlet is not called.
Also even if i update the database manually, when i refresh the page the html table does not update.
I am asking too much but every single clue could help me a lot. Thanks

Ajax - Return html page - on load function of that page not executing

I have one ajax call which return entire html page.
Now that html page have one function which execute on page load event.
But when i am calling it via ajax it is not executing but when I call it via browser it is executing.
For example ,
In browser www.abc.com/test/test1 (Load jquery function on load)
In ajax call www.abc.com/test/test1 (Not load jquery function)
I want to execute that function via ajax call.
Ajax call
function test(str)
{
var $ajaxJQuery = jQuery.noConflict();
console.log("insidee test");
console.log(str);
var $ajaxJQuery = jQuery.noConflict();
$ajaxJQuery.ajax({
type:'GET',
url: "http://www.test.com/test/test-1",
success: function(data){
console.log(data);
//$ajaxJQuery("#Micrositecontainer").html(data);
$ajaxJQuery('body').html(data);
//window.location = str;
},
error: function (xhr, ajaxOptions, thrownError) {
alert("err");
top.location = '${appBaseUrl}/'+responseUrl;
}
});
}
Following is html page :=
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="shortcut icon" href="images/general/favicon.ico" type="image/x-icon">
<title>Test 1</title>
<script>
var $j = jQuery.noConflict();
var locationDialogOpenFirstTime = true;
var isTextChange = false;
var inValidResult = 0;
function getAllComponent(){
// getCKHeaderdata();
var hideLocSession=''
if(hideLocSession=='Edit')
{
if(document.getElementById('hideLocation')!= null)
document.getElementById('hideLocation').className='usernameActive';
}
else if(hideLocSession=='Hide'){
if(document.getElementById('hideLocation')!= null)
document.getElementById('hideLocation').className='';
}
if(hideLocSession != null && hideLocSession!='' && hideLocSession != ' ' && hideLocSession != 'null' )
{
if(hideLocSession=='Edit')
{
$j("#showhideheader").toggle();
$j("#showhideTopNav").toggle();
$j("#showhideleft").toggle();
$j("#showhideRight").toggle();
$j("#hideshowMiddle").toggle();
$j("#showhideFooter").toggle();
$j("#sortIcon").toggle();
}
}
drawTreexmlTreeFoldersObj('&frmLeftTree=1');
drawTreexmlTreeOrphanObj();
getCommentOnload();
}
</script>
</head>
<body class="bodyimage bodyimage3 systemheaderBody" onload="getAllComponent()">
// some content is here
</body>
</html>
Now getAllComponent() is not loading when i call this page via ajax but execute when i opened this page via browser

handling multiple chat boxes in ajax jquery

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.

Categories