Several 'onclick' events for 1 div (change div id) - javascript

I have 2 divs.
Once 1 of the 2 divs has been selected, the 'id' of each will change to either divActive, or divInactive so the active one can be highlighted using css.
Is it possible to do this even though i already have an 'onclick' action associated with each div?
Here are my divs:
<div class="statusOption" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
Here is my current javascript:
<script>
function loadXMLDoc(pageName)
{
var xmlhttp;
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==4 && xmlhttp.status==200)
{
document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
</script>

If you don't want to use jQuery you don't have to. Here is a pure javascript version. Notice it toggles an active class, not an ID.
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var myClasses = everyone.className,
otherClasses = favorites.className;
if (myClasses.contains("active"))
{
everyone.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
else {
everyone.className = 'statusOption active';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var myClasses = favorites.className,
otherClasses = everyone.className;
if (myClasses.contains("active"))
{
favorites.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
else {
favorites.className = 'statusOption active';
}
}
function loadXMLDoc(event) {
var xmlhttp;
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==4 && xmlhttp.status==200)
{
document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}
Edit to accommodate requests in comments: If you always want one to be active it shortens the code a lot. Here is the updated code. Just make sure you give everyone the active class to start in your HTML
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var otherClasses = favorites.className;
if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var otherClasses = everyone.className;
if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
}
function loadXMLDoc(pageName) {
var xmlhttp;
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==4 && xmlhttp.status==200)
{
document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}

Yes, you can have more that one function call in onclick.
However, you should not change the id of the elements, but add or remove a class instead.
Also, you should really consider using something like jQuery, which would make your code much more concise:
<div id="everyone" class="statusOption" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div id="favorites" class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
<script>
$(document).ready(function(){
$('#everyone').on('click', loadXMLDoc, 'indexEveryone');
$('#favorites').on('click', loadXMLDoc, 'indexFav');
$('div.statusOption').on('click', function(){
$('div.statusOption').removeClass('active');
$(this).addClass('active');
});
});
function loadXMLDoc(event)
{
$.ajax({
url: "../home/" + event.data + ".php",
type: "GET",
success: function(result){ $("#centreCont").html(result); }
});
</script>

Related

javascript poll php script every 5 seconds

How do I check a value in a php script for change using javascript?
I would like to do something like:
<script type="text/javascript"><!--
var innitialID = get_file_contents(lastPresentID.php); //get_file_contents(lastPresentID.php);
function myTimeout() {
var freshestID = get_file_contents(lastPresentID.php);
if(freshestID != innitialID) {
location.reload();
}
setTimeout(myTimeout, 5000);
}
window.onload = myTimeout;
</script>
the php script generates a single integer which is the last ID of a table.
Thanks!
<script type="text/javascript">
window.onload = doAjax(true);
setInterval(doAjax, 5000);
var initialID = -1, freshestID;
function doAjax(initial) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(initial) {
initialID = xmlhttp.responseText;
} else {
freshestID = xmlhttp.responseText;
if (initialID != freshestID)
location.reload();
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
</script>
Here we go, updated with ajax calls in there. First sets the initialId variable, then the interval code runs every 5 seconds and update the freshestId variable, and does the comparision.
EDIT: Code is now not duplicated.
The code below on load will assigns oldVal. Then using setInterval will update newVal every 5 secodns and check if newVal != oldVal.
It gets the values from lastPresentID.php using AJAX.
var oldVal = 0;
var newVal = 0;
function loadXMLDoc(old) {
var xmlhttp;
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 == 4 ) {
if(xmlhttp.status == 200){
if(old)
{
oldVal = xmlhttp.responseText;
}
else
{
newVal = xmlhttp.responseText;
if(newVal != oldVal)
alert("test");
}
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert(xmlhttp.status)
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
function timeout() {
loadXMLDoc(false);
}
loadXMLDoc(true);
setInterval(timeout, 5000);

Javascript if statement to determine what url to call on xmlhttp.open GET

Looking for a way to write an if statement based on selection that will determine the url the xmlhttp.open("GET" uses. Example 1,2,3 selected "test2.php?q=" + str, 4 selected "test3.php?q=" + str, 5 selected "test4.php?q=" + str
<form style="width: 210px">
<select name="bookings" onchange="showbookings(this.value)">
<option value="">Select Booking Types To See:</option>
<option value="1">All Booking</option>
<option value="2">Open Bookings</option>
<option value="3">Closed Bookings</option>
<option value="4">Potential Bookings</option>
<option value="5">Create Bookings</option>
</select>
</form>
<div id="txtBookings"></div>
function showbookings(str) {
if (str === "") {
document.getElementById("txtBookings").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 == 4 && xmlhttp.status == 200) {
document.getElementById("txtBookings").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "test2.php?q=" + str, true);
xmlhttp.send();
}
var url = '';
if (str == '5')
url = 'test4.php?q='+str;
else if (str == '4')
url = 'test3.php?q='+str;
else if (str != '')
url = 'test2.php?q='+str;
if (url) {
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
You may try something like this
function showbookings(str) {
if (!str) {
return;
}
var num = str > 3 ? str-1 : 2;
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
// ...
}
xmlhttp.open("GET", "test"+num+".php?q=" + str, true);
xmlhttp.send();
}

Javascript loop to DOM

I'm executing the following code every 5 seconds, but the content appears as a block all at once, ideally it should be writing to the DOM each time it loops? So each value in the array should have its own div?
function newfunction() {
var obj;
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj = JSON.parse(xmlhttp.responseText);
for (var i = 0, n = obj.length; i < n; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
}
}
}
xmlhttp.open("GET","verify.php",true);
xmlhttp.send();
}
window.onload=function() {
newfunction();
setInterval("newfunction()",5000);
}
So on page load it gets some content, then it should be adding more every 5 secs.
Thanks.
I'm not seeing any setTimeout or setInterval, but I would do something like this:
function processIt(obj, i) {
var n = obj.length;
if (i < n) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
setTimeout(function () {
processIt(obj, ++i);
}, 1000);
}
}
var obj = document.getElementsByTagName("div"); // Or whatever "obj" is
processIt(obj, 0);
Updated my answer as you just updated your snippet.. What does your JSON-object from verify.php look like? Is it an object or an array or simple strings?
function retrieveContent() {
var arrayOfElements,
xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
arrayOfElements = JSON.parse(xmlhttp.responseText);
insertElements(arrayOfElements);
setTimeout(retrieveContent, 5 * 1000);
}
};
xmlhttp.open("GET","verify.php",true);
xmlhttp.send();
}
function insertElements(arrayOfElements) {
var divTag,
i,
n;
for (i = 0, n = arrayOfElements.length; i < n; i++) {
divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
}
}
window.onload=retrieveContent;
jsbin snippet

Getting response from server in javascript

How does I get the response from the server in JavaScript? This is my sample code:
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
Try using this block .. the problem with your code is that you missed the quote while creating the open connetion
function get_Image(values){
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest()
} else {
if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("MSXML2.XMLHTTP")
} catch () {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch () {}
}
} else {
return false
}
}
http_request.onreadystatechange = function () {
alert(http_request.status);
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}}
};
http_request.open( "GET", "http://sample_address_for_server", true);
http_request.send(null);
}
you have to attach a function to the object's onreadystatechange event. The way you are doing, you are trying to get the response imediately after you sent the request, you don't have any response yet.
function get_Image(values) {
if (window.XMLHttpRequest) {
var http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var http_request = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http_request.open("GET", "http://sample_address_for_server", true);
http_request.send();
}
alert(http_request.status);
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
xmlDoc = http_request.responseText;
alert(xmlDoc);
}
}
}
}

AJAX issue, works in all browsers except IE

This code works in Chrome and Firefox, but not IE (which is to be expected). Does anyone see anything wrong with this code that would render it useless in IE?
var waittime=400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus()
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout("ajax_read()", waittime);
}
}
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send(null);
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp3) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout("user_read()", 10000);
}
}
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send(null);
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
}
}
}
if(!xmlhttp2) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send(null);
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) submit_msg();
}
var intUpdate = setTimeout("ajax_read()", waittime);
var intUpdate = setTimeout("user_read()", 0);
I'm going to avoid the question slightly and suggest you use jQuery =P. 90% of your code would evaporate. For example, your user_read function would become:
function user_read() {
$.ajax({
type: "GET",
url: "methods.php",
data: {method: "u", room: room}
dataType: "html"
success: function (data, status, xhr) {
$("#userwindow").html(data);
setTimeout(user_read, 10000);
}
});
}
Furthermore, jQuery is also designed to work on all browsers, so you shouldn't have IE problems any more.
Try run on IE some example using jQuery library - just for partial test that browser is 'ok' and code have bug.
jQuery would be best for multiple ajax requests. Else, there are quite a few problems that more advanced browsers automatically fix, while IE may fail on. A few missing semicolons.
You also have 2 intUpdate declarations for 2 different intervals at the end. I've also noticed that "xmlhttp2" has no onreadystatechange function.
Using a checker like JSLint will help alot.
I did my best with your code. Try this, it should result in no errors:
var waittime = 400;
chatmsg = document.getElementById("chatmsg");
room = document.getElementById("roomid").value;
sessid = document.getElementById("sessid").value;
chatmsg.focus();
document.getElementById("chatwindow").innerHTML = "loading...";
document.getElementById("userwindow").innerHTML = "Loading User List...";
var xmlhttp = false;
var xmlhttp2 = false;
var xmlhttp3 = false;
function ajax_read() {
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
if(xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
document.getElementById("chatwindow").innerHTML = xmlhttp.responseText;
setTimeout(function(){ajax_read();}, waittime);
}
};
xmlhttp.open('GET','methods.php?method=r&room=' + room +'',true);
xmlhttp.send();
}
function user_read() {
if(window.XMLHttpRequest){
xmlhttp3=new XMLHttpRequest();
if(xmlhttp3.overrideMimeType){
xmlhttp3.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp3=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp3=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp3.onreadystatechange = function() {
if (xmlhttp3.readyState==4) {
document.getElementById("userwindow").innerHTML = xmlhttp3.responseText;
setTimeout(function(){user_read();}, 10000);
}
};
xmlhttp3.open('GET','methods.php?method=u&room=' + room +'',true);
xmlhttp3.send();
}
function ajax_write(url){
if(window.XMLHttpRequest){
xmlhttp2=new XMLHttpRequest();
if(xmlhttp2.overrideMimeType){
xmlhttp2.overrideMimeType('text/xml');
}
} else if(window.ActiveXObject){
try{
xmlhttp2=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try{
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e){
alert('Giving up :( Cannot create an XMLHTTP instance');
}
}
}
xmlhttp2.open('GET',url,true);
xmlhttp2.send();
}
function submit_msg(){
nick = document.getElementById("chatnick").value;
msg = document.getElementById("chatmsg").value;
document.getElementById("chatmsg").value = "";
ajax_write("methods.php?method=w&m=" + msg + "&n=" + nick + "&room=" + room + "&sessid=" + sessid + "");
}
function keyup(arg1) {
if (arg1 == 13) {submit_msg();}
}
var intUpdate = setTimeout(function(){ajax_read();}, waittime);
user_read();

Categories