javascript notification checker script Uncaught Reference Error - javascript

I have this notification checker and i don't know whats wrong with this js code, i have errors on checkMessage() : Uncaught Reference Error: checkMessage is not defined
the js code:
function checkMessage(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() //when the request is submitted...
{
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
if(xmlhttp.responseText>0){ // if the response text is greater than 0
document.title="("+xmlhttp.responseText+")"+"My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="<b>" + xmlhttp.responseText+" Notifications</b>";
}
else
document.title="My Social Network - Welcome";
document.getElementById('checkMsg').innerHTML="No notifications";
}
}
xmlhttp.open("GET","checkMessage.php?user_id="+"1",true);
xmlhttp.send();
}
the checkmessage.php code:
<?php
include 'dbm.php'; //database settings from an external file
$user = $_SESSION['user'];
$get_count_messages = mysql_query("SELECT message FROM notifications ");
$row = mysql_num_rows($get_count_messages); // count how many rows the query returned
echo "$row"; //return the value
?>
The html code:
<html>
<head>
<script type="text/javascript" src="notifications.js"></script>
<script type="text/javascript">
setInterval("checkMessage()", 1000);
</script>
</head>
<body>
<div id="checkMsg"></div>
</body>
</html>

It's just a simple example to make a difference betwen the number of notifications
if (xmlhttp.readyState==4 && xmlhttp.status==200 //...and everything is ok...
{
var title = "";
var message;
if(xmlhttp.responseText > 0)
{
title += "(" + xmlhttp.responseText + ")";
if(xmlhttp.responseText > 1)
message = "<b>" + xmlhttp.responseText + " Notifications</b>";
else
message = "<b>" + xmlhttp.responseText + " Notification</b>";
}
else
message = "No notifications";
title += "My Social Network - Welcome";
document.title = title;
document.getElementById('checkMsg').innerHTML= message;
}

I think your setInterval function should look like:
setInterval(checkMessage, 1000);
Because setInterval expect a function as parameter.

Related

Why won't this javascript code work in Wordpress post?

I have xml file test.xml with the content
<?xml version= "1.0" encoding= "UTF-8" ?>
<LIST><script />
<ONEP>
<LINK>/wordpress/new_1.html</LINK>
<CHAPTER >One 1</CHAPTER>
</ONEP>
<ONEP>
<LINK>/wordpress/new_2.html</LINK>
<CHAPTER>One 2</CHAPTER>
</ONEP>
</LIST>
I want to load this content into my Wordpress page so I insert the code which is given below into my Wordpress page directly.
<div id="demo">
</div>
<script type="text/javascript">
window.onload = function() {
loadXMLDoc();
};
function loadXMLDoc( ) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "../wordpress/test.xml", true);
xmlhttp.send( );
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<strong>Chapter</strong>";
var x = xmlDoc.getElementsByTagName("ONEP");
for (i = 0; i <x.length; i++) {
table += "<br/><a href=\".." +
x[i].getElementsByTagName("LINK")[0].childNodes[0].nodeValue +
"\">" +
x[i].getElementsByTagName("CHAPTER")[0].childNodes[0].nodeValue +
"</a>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
Now I preview the page.Nothing is found in the page.
I even tried the code using the plugin "Jquery in posts and page" but still the code does not work.I am completely lost.Note the code works perfectly fine in normal html file.It is not working only in Wordpress page and posts.Any help please.
Thank you in advance.
Try Below code to get data from xml file into PHP:
if (file_exists('path to test.xml')) {
$xml = simplexml_load_file('path to test.xml');
echo '<pre>';
print_r($xml);
} else {
exit('Failed to open test.xml.');
}
you will get multidimensional array with all tags and inner content into PHP.

Lag for just part of AJAX response

I made a simple chat. It's working properly, but not behaving as expected. When a user submits a message, the user's name, time and message are supposed to display.
It so happens that the username and response appear first and the time seems to be inserting itself after a slight delay (that's the lag). I can't figure out why, especially since the response is (or at least seems to be) sent as a whole and nothing is being inserting once the response is sent from the server...
Here's the link to the chat. You can input dummy username and dummy messages.
And here are the important pieces of code:
PHP
while ($row = $result->fetch_assoc()) {
$time = date('g:ia', $row['time']);
echo "<p class=\"message\"><i>{$row['username']}</i> ($time): {$row['content']}</p>";
}
JavaScript
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
document.getElementById('messagesArea').innerHTML = ajax.responseText;
}
};
Your culprit is this section of the script:
var content = document.getElementById('messageBox').value;
if ( content === '') {
return;
} else {
var ajax = new XMLHttpRequest();
var username = document.getElementById('signedin').innerHTML;
document.getElementById('messageBox').value = '';
ajax.open('POST', 'postmessage.php', true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.onreadystatechange = function () {
if (ajax.status === 200 && ajax.readyState === 4) {
// if there are errors echoed from the PHP file
if (ajax.responseText != "") {
document.getElementById('mysqliError').innerHTML = ajax.responseText;
return;
}
document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
}
};
ajax.send('username=' + username + '&content=' + content);
}
Notice this line: document.getElementById('messagesArea').insertAdjacentHTML('beforeend', '<p class="message"><i>' + username + '</i>: ' + content + '</p>');
You are inserting the message, without the time, into #messagesArea. Then, in getRecentMessages later, it is set to fetch the entire chat log from displaymessages.php and overwrite #messagesArea with the content of the output, which does have the time.

XMLHttpRequest with php will not work

I've been trying to get this solved for 2 weeks now and still have no success.
JavaScript:
var quotenum = 0;
var xmlhttp = null;
var rt = "";
function ChangeQuote() {
quotenum++;
xmlhttp = null;
//alert("quotenum= "+quotenum);
if (quotenum === 0) {
document.getElementById("quote").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
rt = xmlhttp.responseText;
//alert("quote= "+rt);
alert("request number= " + xmlhttp.length);
document.getElementById("quote").innerHTML = rt;
}
};
xmlhttp.open("Get", "getquote.php?q=" + quotenum, false);
//xmlhttp.open("GET", "getquote.php?XDEBUG_SESSION_START=netbeans-xdebug&q=" + quotenum, false);
xmlhttp.send();
//var thediv = document.getElementById("quote");
return false;
}
PHP:
error_reporting(E_ERROR | E_PARSE);
$q="";
$q = intval($_GET['q']);
$link=mysqli_connect("localhost","root","sequence","babylon");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query="SELECT quotetext FROM quote where quotenum='".$q."'";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo $row["quotetext"];
}
Can anyone see anything wrong with this?
Using WAMP I can see the correct result when I run the PHP file in a browser.
I also try to use Jquery instead.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var quotenum = 0;
// var xmlhttp = null;
// var rt = "";
function ChangeQuote() {
quotenum++;
$.ajax({
url: "getquote.php?q="+quotenum,
method: "get",
data: {
q: quotenum
}
}).done(function (data) {
alert(data);
document.getElementById("quote").innerHTML = data.quotetext;
});
return false;
}
</script>
The only noticable error I see is you inlining your js with the script tag that has a src attribute.
HTML 4.01 Specification:
The script may be defined within the
contents of the SCRIPT element or in
an external file. If the src attribute
is not set, user agents must interpret
the contents of the element as the
script. If the src has a URI value,
user agents must ignore the element's
contents and retrieve the script via
the URI.

XMLHttpRequest not working - no errors

I am trying to get this simple request working but I am not having much luck.
I have the "test.txt" file in the server folder as my html file containing the script provided below.
I viewed the file in Chrome, Firefox and IE11 with the same result. I can only see the "Initial text in the html page.." text from the html page. No errors and the text from my test.txt file is not getting displayed.
Could anyone please point me what the issue with my code is?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp:
}
function process(){
if(xmlHttp){
try{
xmlHttp.open("GET","test.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse(){
output = document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML += "Status 1: server connection established <br />"
}
else if(xmlHttp.readyState==2){
output.innerHTML += "Status 2: request received <br />"
}
else if(xmlHttp.readyState==3){
output.innerHTML += "Status 3: server processing <br />"
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
try{
text = xmlHttp.responseText;
output.innerHTML += "Status 4: request is finished and response is ready<br />"
output.innerHTML += text;
}
catch(e){
alert( e.toString() );
}
}
else{
alert( xmlHttp.statusText );
}
}
}
</script>
</head>
<body onload="process()">
Initial text in the html page..<br>
<br>
<div id="output">
</div>
</body>
</html>
Ok, I figured it out....
it was one typo and one ommision
return xmlHttp: -> should be ; instead
and forgot "else"
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){

First small foodstore-project with ajax - does not execute

I have just started to learn Ajax and have watched a tutorial on how to write a small input that checks whether a foodstore has something in stock or whether it hasn't.
I have double-checked the code several times but it still does not execute anything. I would be glad if anyone could help me here.
The code is basically three files:
Index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Food Store</h3>
<p>Enter the food you would like to have:</p>
<input type="text" id="userInput">
<div id="underInput"/>
</body>
</html>
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'ham');
if(in_array($food,$foodArray)) {
echo 'We do have '.$food'!';
echo '</response>';
}
}
?>
and finally the foodstore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
} catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Cant create that object!");
else {
return xmlHttp;
}
}
// This is now the communication part!
function process() {
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElmentById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse() {
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span styel="color:blue">' + message + '</span>';
setTimeout('process()',1000);
}else{
alter('Something went wrong!');
}
}
}
I would really appreciate some help. I also read in the youtube-comments that jQuery would rather be easier to use as far as the js part goes. Is that true?
Many thanks!
In the foodstore.js you have a litlle problem you have writed document.getElmentById("userInput").value and it must be
document.getElementById("userInput").value

Categories