Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps
Related
I am currently writing some poll software and, even though it works fine, I am having difficulties getting some of my javascript to work. I have a button labelled "Add New Option" which, when clicked, will call the following javascript function:
function newoption()
{
var option = "";
while((option.length < 1)||(option.length > 150))
{
var option = prompt("Please enter the option value... ").trim();
}
var add = confirm("You entered " + option + ", are you sure?");
if(add==1)
{
var code = window.location.href.length;
var poll = prompt("Which poll are you adding this to?", window.location.href.substring(code - 5, code));
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{this.responsetext = option;}};
xhttp.open("POST", "../special/new.php", true);
xhttp.send("poll=" + poll + "&opt=" + option);
}
else
{
alert("OK... try again");
}
}
The page it posts to simply has a function to add the option to the poll which the user supplies the code for (it automatically gets this from the end of the URL) but the problem is that, when I refresh the page, the list of options is not updated which makes me think it isn't being added to the database but the function to add new options works on when the poll is created. Is there something I'm doing wrong?
The code for new.php is:
<?php require("internal/index.php");
$option = string_format($conection, $_POST["opt"], 1)
$poll =(int) $_POST["poll"];
if($poll&&$option)
{
new_poll_option($connection, $poll, $option);
}
?>
From what you wrote I understand that the code works until you refresh the page. That means that you don't check the Ajax response and just insert some HTML which will last until you refresh the page.
You need to look in your database if the items was created. If it is created then maybe you need to delete the browser cache (you can do that from the Network tab in DevTools in Chrome).
If the items was not insert in the database then you need to debug or just echo the message from the insert function that you used.
You can also use a form and not use Ajax if you will refresh the page anyway in a few moments.
For an assignment, I am making a request to the Github Gist API and then appending the response to an HTML page. I am then supposed to allow the user to "favorite" one of the GISTS and then that GIST is to appear in a separate favorites section (favorited GISTS are to be stored in local storage). I am able to make the request, append the information and make the favorited GISTs appear in another section HOWEVER, the lists only appear for a moment and then disappear after I click on the favorite button. I can see the list flash and then go away. All of the other (non-favorite) GIST info also disappears even though it's not supposed. Can anyone please point me in the right direction? I'm not allowed to use any JQuery. Full code here: http://pastebin.com/ic0juq9n
Critical code below:
var getData = function(url)
{
if(!req)
{
throw 'Unable to create HttpRequest.';
}
req.onreadystatechange = function()
{
if(this.readyState === 4)
{
if (req.status === 200)
{
console.log("It worked!!");
var info = JSON.parse(req.responseText);
for(var key in info)
{
GistList.push(info[key]);
}
}
else
{
console.log("It messed up again");
}
}
for (i = 0; i < GistList.length; i++)
{
generateGistList(GistList[i]);
}
}
req.open('GET', url);
req.send();
};
function generateGistList(Gist) {
var itemList = document.createElement('li');
var holdURL = document.createElement('div');
var holdID = document.createElement('div');
var description = document.createElement('div');
if (Gist.description === null)
{
description.innerHTML = "No description found";
}
else
{
description.innerHTML = "Description: " + Gist.description;
}
holdURL.innerHTML = "URL: " + Gist.url;
holdID.innerHTML = "ID: " + Gist.id;
itemList.appendChild(holdID);
itemList.appendChild(holdURL);
itemList.appendChild(description);
ul.appendChild(itemList);
list.appendChild(ul);
var favorite = document.createElement("button");
favorite.innerHTML = "+";
favorite.setAttribute("gistId", Gist.id);
itemList.appendChild(favorite);
favorite.onclick = function()
{
var gistId = this.getAttribute("gistId"); //saved
var toBeFavoredGist = findById(gistId);
//here you add the gist to your favorite list in the localStorage
and remove it from the gist list and add it to favorite list
addFavorite(toBeFavoredGist);
DisplayFavs();
//removeGist(toBeFavoredGist);
}
}
Make sure if you're using forms that the form tag has an action attribute!
Trying to put data into an XML through javascripts open() function.
but The website does not get past readyState 1,
Below is the the Javascript code
function addItem()
{
var name = document.getElementById('Iname').value;
var price = document.getElementById('Iprice').value;
var quantity = document.getElementById('Iquantity').value;
var description = document.getElementById('Idescription').value;
xHRObject.open("GET", "listing.php", true);
xHRObject.onreadystatechange = function() {
if (xHRObject.readyState == 4 && xHRObject.status == 200)
{
document.getElementById('Information').innerHTML = xHRObject.responseText;
xHRObject.send(null);
}
}
}
I do not know if it is an error with the PHP, but its quite large so i will only post it in if required.
This was an error with the browser functionality, worked fine in firefox.
I have a slickgrid screen (on regular Domino form) wherein user can select and update some documents. I needed to show a pop-up displaying status of every selected document so I created an XPage. In my XPage I am looping through selected documents array (json) and call an RPC method for every document. Code to call RPC method is in a button which is clicked on onClientLoad event of XPAGE. RPC is working fine because documents are being updated as desired. Earlier I had RPC return HTML code for row () which was being appended to HTML table. It works in Firefox but not in IE. Now I am trying to append rows using Dojo but that’s not working either.
Here is my Javascript code on button click.
var reassign = window.opener.document.getElementById("ResUsera").innerHTML;
var arr = new Array();
var grid = window.opener.gGrid;
var selRows = grid.getSelectedRows();
for (k=0;k<selRows.length;k++)
{
arr.push(grid.getDataItem(selRows[k]));
}
var tab = dojo.byId("view:_id1:resTable");
while (arr.length > 0)
{
var fldList = new Array();
var ukey;
var db;
var reqStatusArr = new Array();
var docType;
var docno;
ukey = arr[0].ukey;
db = arr[0].docdb;
docType = arr[0].doctypeonly;
docno = arr[0].docnum;
fldList.push(arr[0].fldIndex);
reqStatusArr.push(arr[0].reqstatusonly);
arr.splice(0,1)
for (i=0;i < arr.length && arr.length>0;i++)
{
if ((ukey == arr[i].ukey) && (db == arr[i].docdb))
{
fldList.push(arr[i].fldIndex);
reqStatusArr.push(arr[i].reqstatusonly);
arr.splice(i,1);
i--;
}
}
console.log(ukey+" - "+db+" - "+docno+" - "+docType);
var rmcall = faUpdate.updateAssignments(db,ukey,fldList,reassign);
rmcall.addCallback(function(response)
{
require(["dojo/html","dojo/dom","dojo/domReady!"],function(html,dom)
{
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
html.set(tbdy,
tbdy.innerHTML+"<tr>"+
"<td>"+docType+"</td>"+
"<td>"+docno+"</td>"+
"<td>"+reqStatusArr.join("</br>")+"</td>"+
"<td>"+response+"</td></tr>"
);
});
});
}
dojo.byId("view:_id1:resTable").style.display="inline";
dojo.byId("idLoad").style.display="none";
RPC Service Code
<xe:jsonRpcService
id="jsonRpcService2"
serviceName="faUpdate">
<xe:this.methods>
<xe:remoteMethod name="updateAssignments">
<xe:this.arguments>
<xe:remoteMethodArg
name="dbPth"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="uniquekey"
type="string">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="fieldList"
type="list">
</xe:remoteMethodArg>
<xe:remoteMethodArg
name="reassignee"
type="string">
</xe:remoteMethodArg>
</xe:this.arguments>
<xe:this.script><![CDATA[print ("starting update assignments from future assignments page");
var db:NotesDatabase = null;
var vw:NotesView = null;
var doc:NotesDocument = null;
try{
db=session.getDatabase("",dbPth);
if (null!= db){
print(db.getFileName());
vw = db.getView("DocUniqueKey");
if (null!=vw){
print ("got the view");
doc = vw.getDocumentByKey(uniquekey);
if (null!=doc)
{
//check if the document is not locked
if (doc.getItemValueString("DocLockUser")=="")
{
print ("Got the document");
for (i=0;i<fieldList.length;i++)
{
print (fieldList[i]);
doc.replaceItemValue(fieldList[i],reassignee);
}
doc.save(true);
return "SUCCESS";
}
else
{
return "FAIL - document locked by "+session.createName(doc.getItemValueString("DocLockUser")).getCommon();
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 0";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 1";
}
}
else
{
return "FAIL - Contact IT Deptt - Code: 2";
}
}
catch(e){
print ("Exception occured --> "+ e.toString());
return "FAIL - Contact IT Deptt - Code: 3";
}
finally{
if (null!=doc){
doc.recycle();
vw.recycle();
db.recycle();
}
}]]></xe:this.script>
</xe:remoteMethod>
</xe:this.methods>
</xe:jsonRpcService>
Thanks in advance
I have resolved this issue. First, CSJS variables were not reliably set in callback function so I made RPC return the HTML string I wanted. Second was my mistake in CSJS. I was trying to fetch tbody from table using
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName("tbody");
where as it returns an array so it should have been
var tbdy = dom.byId("view:_id1:resTable").getElementsByTagName**("tbody")[0]**;
also I moved tbody above while loop. I can post entire code if anyone is interested!!
I have some issues retrieving info from python and try to show the data in a html page
I get the date from a python script (data.py)
import cx_Oracle
import json
lst_proveedores=[{}]
conn_str = 'user/pass#database'
conn = cx_Oracle.connect(conn_str)
c = conn.cursor()
c.execute('select id, name from provider')
for row in c:
record1 = {"id":row[0], "name":row[1]}
lst_proveedores.append(record1)
json_string = json.dumps(lst_proveedores)
print json_string
conn.close()
I try to parse the info with AJAX in a html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function ajax_get_json(){
var results = document.getElementById("results");
var hr = new XMLHttpRequest();
hr.open("GET", "prov1.py", true);
hr.responseType = "JSON";
hr.setRequestHeader("Content-Type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
results.innerHTML = "";
for(var obj in data){
results.innerHTML += data[obj].id+" is "+data[obj].nombre+"<hr />";
}
}
}
hr.send(null);
results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
but doesn't work
I setup apache to execute python scripts and work with very simple scripts, but doesn't work when I retrieve data from the database
How can I show the data in a html page?
Or what language or framework may I can use to show the data
Any advice
I am desperate
Thanks in advance
First of all, you should try visit your python files in browser. If you can't see json print on page, there're problems in your server or python code.
If it works, that may be something wrong in your Ajax request.
You can use jQuery or zepto.js to help. They contain a method of Ajax: $.ajax.
You can visit: http://zeptojs.com
And search "$.ajax" on the page for help; )
===============================================================
try this:
//var data = JSON.parse(hr.responseText);
var data = JSON.parse(hr.response);
===============================================================
and this is my onreadystatechange function code, use it if it helps:
ajaxObject.onreadystatechange = function(){
//console.info('[Ajax request process] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (ajaxObject.readyState == 4 && ((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
var result = null;
switch (dataType){
case 'text':
result = ajaxObject.responseText;
break;
case 'xml':
result = ajaxObject.responseXML;
break;
case 'json':
default:
result = ajaxObject.response ? JSON.parse(ajaxObject.response) : null;
break;
}
if (typeof(success) == 'function'){
success(result,url);
}
}else if (ajaxObject.readyState > 1 && !((ajaxObject.status >= 200 && ajaxObject.status < 300) || ajaxObject.status == 304)){
console.warn('[Ajax request fail] url:' + url +'; readyState:' + ajaxObject.readyState + '; status:' + ajaxObject.status);
if (typeof(error) === 'function' && errorCallbackCount == 0){error(url);errorCallbackCount++;}
return false;
}
}