i added this JS code:
<script language="JavaScript" type="text/JavaScript">
var receiveReq = getXmlHttpRequestObject();
var mTimer;
var url = "www-rainbowcode-net/apps_dev.php/messagebox/list";
function getXmlHttpRequestObject()
{
alert("in gethttprequest");
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
//document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.';
}
}
function getNewMessage()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
alert("state is" + receiveReq.readyState);
//var params = "name" + name + "&" + "comment=" + comment;
receiveReq.open("POST", url, true);
receiveReq.onreadystatechange = processReqChange;
receiveReq.send(null);
}
}
function processReqChange()
{
// only if req shows "loaded"
if (receiveReq.status == 200)
{
alert("processed" + receiveReq.responseText);
document.getElementById("message_area").innerHTML = receiveReq.responseText;
}
else
{
alert("There was a problem retrieving the XML data:\n" +
receiveReq.statusText);
}
mTimer = setTimeout('getNewMessage();',2000);
}
</script>
then i have my html mixed with php:
<body onload = "return getNewMessage();">
<table width='96%' border='0'>
<?php
$cursor = $pager->getFirstIndice();
foreach ($pager->getResults() as $msg)
{
$has_freechat = false;
//changed id to withid here
$freechat_req_link="profiles/confirmfreechat?withid=".$msg->getRcProfileTableRelatedByProfileIdFrom()->getId();
$freechat_req_link=link_to('Freechat',$freechat_req_link,'class=link_small_dark');
$cc = sizeof ($fc_records);
for($i = 0; $i < $cc; $i++)
{
if($fc_records[$i]->getProfileIdWith() == $msg->getProfileIdFrom())
{
$has_freechat = true;
break;
}
}
$unique_code_from = $msg->getRcProfileTableRelatedByProfileIdFrom()->getUniqueCode();
$block_url = link_to('Block User',"blocklist/block?unqiue_code=$unique_code_from",'class=link_medium_blue');
echo "<div id = 'message_area'>";
echo "<tr>";
$date = add_date($msg->getCreatedAt(),$hr=2);
echo "<td class='td_show_contact_item' align='left'>".$date."</td>";
$opened_once = $msg->getOpenedOnce();
if($opened_once >= 1)
{
echo "<td class='td_show_contact_item' align='left'>".link_to($msg->getSubject(), 'messagebox/read?cursor='.$cursor,'class=link_medium_blue')."</td>";
}
else
{ ?>
<td align='left'>
<a href="<?php echo url_for('messagebox/read?cursor=').$cursor ?>" style='color:#ff0000 !important' class='spn_small_red_rbc'><?php echo $msg->getSubject();?> </a>
</td>
<?php
}
echo "<td class='td_show_contact_item' align='left'>".$unique_code_from." ( $block_url )</td>";
echo "</tr>";
echo "</div>";
++$cursor;
}
</table>
can anybody tell me why my alerts in the 2nd and 3rd function dont execute? the one in the 1st executes
thanks
in getNewMessage you miss () for processReqChange
update:
function getNewMessage()
{
if (receiveReq.readyState == 4 || receiveReq.readyState == 0)
{
alert("state is" + receiveReq.readyState);
//var params = "name" + name + "&" + "comment=" + comment;
receiveReq.open("POST", url, true);
receiveReq.onreadystatechange = processReqChange;
receiveReq.send(null);
}
mTimer = setTimeout("getNewMessage()", 5000);
}
Related
How do I use the value of variable $dd i.e 10 or 100000 outside the if condition?
I want to show that status(available/not available) and the $dd value in separate locations.
ajax success
success: function (response) {
$("#uname_response").html(response);
}
if(isset($_POST['applied_promocode'])){
$applied_promocode = $_POST['applied_promocode'];
$dd = 0;
// Check applied_promocode
$stmt = $dbh->prepare("SELECT count(*) as cntUser FROM coupon WHERE applied_promocode=:applied_promocode");
$stmt->bindValue(':applied_promocode', $applied_promocode, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->fetchColumn();
//Availability message
if($count > 0){
$response = "<span style='color: red;'>Not Available.</span>";
$dd = 10;
} else {
$response = "<span style='color: green;'>Available.</span>";
$dd = 100000;
}
echo $dd;
echo $response;
exit;
}
$discount_price = $dd * 100;
You can choose to send back data in JSON format if you want to be able to pass complex data (i.e. non-string value). The way to do that would be as follows:
Untested code
if($count > 0){
$response = "Not Available";
$dd = 10;
} else {
$response = "Available";
$dd = 100000;
}
$discount_price = $dd * 100;
$json_data = array('response'=>$response, 'dd' => $discount_price);
echo json_encode($json_data);
Then on the client side, you can use something like this:
success: function (response) {
var json_data = JSON.parse(response);
var color = "red";
if(json_data.response == 'Available')
{
color = "green";
}
var html = "<span style='color: "+color+";'>"+json_data.response+".</span><p>"Discounted price = "+json_data.dd+"</p>";
$("#uname_response").html(html);
}
Or if you do not like concatenation, use the traditional approach to manipulate the DOM
success: function (response) {
var json_data = JSON.parse(response);
if(json_data && json_data.response)
{
var color = "red";
if(json_data.response == 'Available')
{
color = "green";
}
var span = document.createElement('span');
span.style.color = color;
span.innerHTML = json_data.response;
var p = document.createElement('p');
p.innerHTML = "Discounted price is "+json_data.dd;
var div = document.createElement('div');
div.appendChild(span);
div.appendChild(p);
$("#uname_response").html(div);
}
else
{
alert("Invalid data returned from server");
}
}
What I am currently trying to achieve is an auto icon updater. So far I only have it working for 1 icon, but I have 9. Now I have tried to repeat the same code 9 times, try to get it to work from the same file, ect... but to no success. Each icon has a separate timer which will show a different image. (Same image lower opacity)
I want a something which will check the database for the time and see if the time is up, show image 1 if not show image 2.
This is the code I have so far:
function runme() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo$id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo$id;?>";
var strhehess = "&username=<?echo$name;?>";
ajaxRequest.open("GET", "auto.php?&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById("icon_messaging").innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout("runme()", 6000);
}
setTimeout("runme()", 5000);
Here is auto.php:
//AUTO INCLUDE
$userids = $_GET['userid'];
$saturate = "/[^a-z0-9]/i";
$saturatesd = "/[^0-9]/i";
$sessionid = preg_replace($saturate,"",$sessionidbefore);
$userid = preg_replace($saturatesd,"",$userids);
$statustest = mysql_query("SELECT newmail,lastactive FROM login WHERE id = '$userids' LIMIT 1");
$statustesttwo = mysql_fetch_array($statustest);
$mails = $statustesttwo['newmail'];
$last_active_1 = $statustesttwo['lastactive'];
if($mails == '0'){
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/mail-yes.gif' style='border-style: none'></a>";
}else{
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/layout/mail-n.jpg' style='border-style: none'></a>";
}
If I understood your question correctly, this is the updating system for the "new mail" icon, and you need to check and update other stuff too. Since you want separate timers, you could parametrize the runme() function. Your JavaScript could be modified like this:
function runme(icon) {
var iconElementId;
var iconTimer;
switch (icon) {
case "mail":
iconElementId = "icon_messaging";
iconTimer = 6000;
break;
case "news":
iconElementId = "icon_notifications"; // I'm making up names and timeouts here
iconTimer = 3000;
break;
case "something":
iconElementId = "icon_something"; // Still making up
iconTimer = 8000;
break;
/* And so on, covering all your 9 cases */
}
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo $id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo $id;?>";
var strhehess = "&username=<?echo $name;?>";
ajaxRequest.open("GET", "auto.php?icon=" + encodeURIComponent(icon) + "&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById(iconElementId).innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1;
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout(function(){runme(icon);}, iconTimer);
}
setTimeout(function(){runme("mail");}, 5000);
setTimeout(function(){runme("news");}, 5000);
setTimeout(function(){runme("something");}, 5000);
/* And so on */
So, now your JavaScript sends a GET request to auto.php with the addition of the icon parameter. The PHP script will have to manage that, too.
//AUTO INCLUDE
$icon = urldecode($_GET['icon']);
$userids = $_GET['userid'];
$saturate = "/[^a-z0-9]/i";
$saturatesd = "/[^0-9]/i";
$sessionid = preg_replace($saturate,"",$sessionidbefore);
$userid = preg_replace($saturatesd,"",$userids);
switch($icon) {
case "mail":
$statustest = mysql_query("SELECT newmail,lastactive FROM login WHERE id = '$userids' LIMIT 1");
$statustesttwo = mysql_fetch_array($statustest);
$mails = $statustesttwo['newmail'];
$last_active_1 = $statustesttwo['lastactive'];
if ($mails == '0') {
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/mail-yes.gif' style='border-style: none'></a>";
} else {
echo "<a id='inboxspan' href='/home.php?pageid=80'><img src='images/layout/mail-n.jpg' style='border-style: none'></a>";
}
break;
case "news":
$statustest = mysql_query("SOME OTHER SQL QUERY");
$statustesttwo = mysql_fetch_array($statustest);
/* check whatever you need to */
if (/* something */) {
echo "the HTML for the icon";
} else {
echo "the HTML for the other icon ";
}
break;
/* And so on, again, covering all your 9 cases */
}
Let me know if this works for you.
function runme(icon) {
var iconElementId;
var iconTimer;
switch (icon) {
case "mail":
iconElementId = "icon_messaging";
iconTimer = 5000;
break;
case "gta":
iconElementId = "gta_icon";
iconTimer = <? echo $icon_secs[0]; ?>;
break;
case "burg":
iconElementId = "c_icon";
iconTimer = 5000;
break;
case "crimes":
iconElementId = "crimes_icon";
iconTimer = <? echo $icon_secs[1]; ?>;
break;
case "chase":
iconElementId = "chase_icon";
iconTimer = <? echo $icon_secs[2]; ?>;
break;
case "robbery":
iconElementId = "robbery_icon";
iconTimer = <? echo $icon_secs[3]; ?>;
break;
case "train":
iconElementId = "train_icon";
iconTimer = <? echo $icon_secs[4]; ?>;
break;
case "goods":
iconElementId = "goods_icon";
iconTimer = <? echo $icon_secs[5]; ?>;
break;
case "df":
iconElementId = "df_icon";
iconTimer = <? echo $icon_secs[6]; ?>;
break;
case "sm":
iconElementId = "sm_icon";
iconTimer = <? echo $icon_secs[7]; ?>;
break;
}
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
var str = "<?echo $id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo $id;?>";
var strhehess = "&username=<?echo $name;?>";
ajaxRequest.open("GET", "auto.php?icon=" + encodeURIComponent(icon) + "&id=" + str + strhehes + strhehess + strhehe, true);
ajaxRequest.send(null);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4) {
if (ajaxRequest.status == 200) {
attempt = 0;
document.getElementById(iconElementId).innerHTML = ajaxRequest.responseText;
document.getElementById("error_mess").innerHTML = '';
document.getElementById("error_mess").style.display = 'none';
} else {
attempt += 1
document.getElementById("error_mess").style.display = 'block';
document.getElementById("error_mess").innerHTML = '<br><font color="#ff4040" onMouseover="ddrivetip(\'There is an error connecting. The game will continue trying to connect again.\')" onMouseout="hideddrivetip()" style="cursor: pointer;">Error Code: ' + new XMLHttpRequest().status + '<br>Attempts: ' + attempt + '</font>';
}
}
}
setTimeout("runme('" + icon + "')", iconTimer);
}
setTimeout("runme('mail')", 5000);
setTimeout("runme('gta')", <? echo $icon_secs[0]; ?>);
setTimeout("runme('burg')", 5000);
setTimeout("runme('crimes')", <? echo $icon_secs[1]; ?>);
setTimeout("runme('chase')", <? echo $icon_secs[2]; ?>);
setTimeout("runme('robbery')", <? echo $icon_secs[3]; ?>);
setTimeout("runme('train')", <? echo $icon_secs[4]; ?>);
setTimeout("runme('goods')", <? echo $icon_secs[5]; ?>);
setTimeout("runme('df')", <? echo $icon_secs[6]; ?>);
setTimeout("runme('sm')", <? echo $icon_secs[7]; ?>);
I don't know what your exact problem is. Do you get an error?
What I quickly see is:
attempt += 1
Change this into
if (typeof attempt == "undefined") attempt = 0;
attempt ++;
So add the semi-colon ; , and first check if the var already exists
( ++ is the same as += 1 )
Is this function runme generated by PHP?
var str = "<?echo$id;?>";
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=<?echo$id;?>";
var strhehess = "&username=<?echo$name;?>";
Because if it is not, there is no way this code will work, because Javascript cannot interpret PHP.
In this case, you should put this as attributes of HTML elements and get'em with DOM.
When generating your HTML with PHP, do:
echo '<output id="data-id">' . $id . '<output>';
echo '<output id="data-user-id">' . $id . '<output>';
echo '<output id="data-user-name">' . $username . '<output>';
You can hide this elements with CSS. So then in your Javascript, you should do:
var str = document.getElementById('data-id').innerHTML;
var strhehe = "&rand=" + Math.random();
var strhehes = "&userid=" + document.getElementById('data-user-id').innerHTML;
var strhehess = "&username=" + document.getElementById('data-user-name').innerHTML;
Hope it helps.
I have this VeriSign script that is causing the javascript notifications on my site to say "undefined" instead of displaying the mesage
Verisign Code:
< !--dn = "www.mysite.com";
lang = "en";
tpt = "transparent";
vrsn_style = "WW";
splash_url = "https://trustsealinfo.verisign.com";
seal_url = "https://seal.verisign.com";
u1 = splash_url + "/splash?form_file=fdf/splash.fdf&dn=" + dn + "&lang=" + lang;
u2 = seal_url + "/getseal?at=0&sealid=2&dn=" + dn + "&lang=" + lang;
u3 = seal_url + "/getseal?at=1&sealid=2&dn=" + dn + "&lang=" + lang;
var sopener;
function vrsn_splash() {
if (sopener && !sopener.closed) {
sopener.focus();
} else {
tbar = "location=yes,status=yes,resizable=yes,scrollbars=yes,width=560,height=500";
var sw = window.open(u1, 'VRSN_Splash', tbar);
if (sw) {
sw.focus();
sopener = sw;
}
}
}
var MM_cVer = 6;
var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin: 0;
var ver = -1;
var v_ua = navigator.userAgent.toLowerCase();
var re = new RegExp("msie ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
ver = parseFloat(RegExp.$1);
}
var v_old_ie = (v_ua.indexOf("msie") != -1);
if (v_old_ie) {
v_old_ie = ver < 5;
}
function v_mact(e) {
var s;
if (document.addEventListener) {
s = (e.target.name == "seal");
if (s) {
vrsn_splash();
return false;
}
} else if (document.captureEvents) {
var tgt = e.target.toString();
s = (tgt.indexOf("splash") != -1);
if (s) {
vrsn_splash();
return false;
}
}
return true;
}
function v_mDown(event) {
if (document.addEventListener) {
return true;
}
event = event || window.event;
if (event) {
if (event.button == 1) {
if (v_old_ie) {
return true;
} else {
vrsn_splash();
return false;
}
} else if (event.button == 2) {
vrsn_splash();
return false;
}
} else {
return true;
}
}
function v_resized() {
if (pageWidth != innerWidth || pageHeight != innerHeight) {
self.history.go(0);
}
}
if (plugin) {
var words = navigator.plugins["Shockwave Flash"].description.split(" ");
for (var i = 0; i < words.length;++i) {
if (isNaN(parseInt(words[i], 10))) {
continue;
}
var MM_pVer = words[i];
}
var MM_play = MM_pVer >= MM_cVer;
} else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE") >= 0 && (navigator.appVersion.indexOf("Win") != -1)) {
document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n');
document.write('on error resume next \n');
document.write('MM_play = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_cVer)))\n');
document.write('</SCR' + 'IPT\> \n');
}
if (MM_play) {
document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
document.write(' codebase="https://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"');
document.write(' ID="s_s" WIDTH="100" HEIGHT="72" ALIGN="">');
document.write(' <PARAM NAME=movie VALUE="' + u3 + '"> <PARAM NAME=loop VALUE=false> <PARAM NAME=menu VALUE=false> <PARAM NAME=quality VALUE=best> <PARAM NAME=wmode VALUE=' + tpt + '> <PARAM NAME="allowScriptAccess" value="always">');
document.write(' <EMBED src="' + u3 + '" loop=false menu=false quality=best wmode=' + tpt);
document.write(' swLiveConnect=FALSE WIDTH="100" HEIGHT="72" NAME="s_s" ALIGN=""');
document.write(' TYPE="application/x-shockwave-flash" PLUGINSPAGE="https://www.macromedia.com/go/getflashplayer" allowScriptAccess="always">');
document.write(' </EMBED>');
document.write(' </OBJECT>');
} else {
document.write("<IMG NAME=\"seal\" BORDER=\"true\" SRC=\"" + u2 + "\" oncontextmenu=\"return false;\" alt=\"Click to Verify - This site has chosen a VeriSign SSL Certificate to improve Web site security\">");
if (document.addEventListener) {
document.addEventListener('mouseup', v_mact, true);
} else {
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = v_mact;
}
}
if (document.layers) {
pageWidth = innerWidth;
pageHeight = innerHeight;
window.onresize = v_resized;
}
}
if ((v_ua.indexOf("msie") != -1) && (ver >= 7)) {
var plat = -1;
var re = new RegExp("windows nt ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(v_ua) !== null) {
plat = parseFloat(RegExp.$1);
}
if ((plat >= 5.1) && (plat != 5.2)) {
document.write("<div style='display:none'>");
document.write("<img src='https://extended-validation-ssl.verisign.com/dot_clear.gif'/>");
document.write("</div>");
}
}-->
Versign on Page code:
<script type="text/javascript" src="https://seal.verisign.com/getseal?host_name=www.MySite.com&size=S&use_flash=YES&use_transparent=YES&lang=en"> </script>
Affected Javascript:
RemoveItem: function(itemId)
{
if(confirm(lang.CartRemoveConfirm)) {
document.location.href = "cart.php?action=remove&item="+itemId;
}
},
If the code with lang.CartRemoveConfirm belongs to you, it looks like an object with message strings. You should notice that the second row of the VeriSign script redefines lang as the string "en", overriding any value it might have before. Can you use some other variable name?
Same issue here, thinking about using an iframe for the seal on pages that use this lang (CS-Cart vs Verisign).
I am writing a Facebook app in PHP/FBJS. I have some code where I attach an addEventListener() to two buttons. When I run the app, the first button I click on fires the addEventListener() and the event handler is invoked as expected. But if I click on the second button or click on the same button again, the event handler is not invoked. Here is my code:
//PHP
public function loadCargoDialogFbjsAction() {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$loadableCargo = $this->getRequest()->getPost('loadableCargo');
$fbjs =
'<div id="load_cargo_select">
<form id="load_cargo_select_form" action="" method="POST">
<p>Your train has stopped in the city of ' . $loadableCargo['city'] . '</p>
<p>' . $loadableCargo['city'] . ' produces the following goods:</p>
<ul>';
if(count($loadableCargo['city_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['city_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>Your train is hauling the following goods:</p>
<ul>';
if(count($loadableCargo['train_goods']) <= 0) {
$fbjs .= '<li>None</li>';
} else {
foreach($loadableCargo['train_goods'] as $goods) {
$fbjs .= '<li>' . $goods['name'] . '</li>';
}
}
$fbjs .=
'</ul>
<p>What would you like to do?</p>
<input type="button" id="load-new-submit" name="load-cargo-new" value="Load new goods" />
<input type="button" id="discard-existing-submit" name="load-cargo-discard" value="Discard existing goods" />
</form>
</div>';
echo $fbjs;
}
// JavaScript/FBJS
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', cargoEventHandler); //discardExistingCargo);
dialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
dialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
dialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
function cargoEventHandler(evt) {
//new Dialog().showMessage('loadNewCargo', 'city id='+cityId+', train id='+trainId);
//debugger;
cityId = evt.target.cityId;
trainId = evt.target.trainId;
switch(evt.target.getId()) {
case 'load-new-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Load new goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
openCargoHolds = data.openCargoHolds;
cargoHoldsUsed = 0;
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'cityGoods': data.cityGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
//debugger;
var dialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Load cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-new', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-new-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
case 'discard-existing-submit':
ajax = new Ajax();
ajax.responseType = Ajax.JSON;
param = { 'load-cargo-submit': "Discard existing goods", 'city-id': cityId, 'train-id': trainId };
ajax.ondone = function(data) {
ajax.responseType = Ajax.FBML;
param = { 'openCargoHolds': data.openCargoHolds, 'trainGoods': data.trainGoods, 'trainId': data.trainId };
ajax.ondone = function(fbjsData) {
var dialog = new Dialog().showChoice('Discard Cargo', fbjsData, 'Discard cargo', 'Cancel');
dialog.onconfirm = function() {
var goods = [];
var goodsIds = [];
numGoods = document.getElementById('goods-count').getValue();
for(var i = 0; i < numGoods; i++) {
j = i + 1;
goods[i] = document.getElementById('goods-' + j).getValue();
goodsIds[i] = document.getElementById('goods-id-' + j).getValue();
}
var trainId = document.getElementById('train-id').getValue();
param = { "goods": goods, "goods-id": goodsIds, "train-id": trainId };
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
loadCargo();
}
ajax.post(baseURL + '/turn/do-load-cargo-discard', param);
//dialog.hide();
};
dialog.oncancel = function() {
loadCargo();
}
}
ajax.post(baseURL + '/turn/load-cargo-discard-dialog-fbjs', param);
}
ajax.post(baseURL + '/turn/load-cargo-select', param);
break;
}
return false;
}
Any help would be greatly appreciated. Thanks!
#Tim
I changed my loadCargo() function as follows to prevent duplication of those elements, but I am still running into the same problem as before.
var loadCargoDialog;
function loadCargo() {
var actionPrompt = document.getElementById('action-prompt');
actionPrompt.setTextValue('Loading cargo...');
var ajax = new Ajax();
ajax.responseType = Ajax.JSON;
ajax.ondone = function(data) {
//debugger;
ajax.responseType = Ajax.FBML;
ajax.ondone = function(fbjsData) {
//debugger;
if(data.loadableCargo.length == 0) {
moveTrainManual();
} else {
if(loadCargoDialog == null) {
loadCargoDialog = new Dialog().showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
var dlgBtnNew = document.getElementById('load-new-submit');
dlgBtnNew.cityId = data.loadableCargo.city_id;
dlgBtnNew.trainId = data.loadableCargo.train_id;
dlgBtnNew.addEventListener('click', cargoEventHandler, true); //loadNewCargo);
var dlgBtnDiscard = document.getElementById('discard-existing-submit');
dlgBtnDiscard.cityId = data.loadableCargo.city_id;
dlgBtnDiscard.trainId = data.loadableCargo.train_id;
dlgBtnDiscard.addEventListener('click', discardExistingCargo, true);
} else {
loadCargoDialog.showChoice('Load Cargo', fbjsData, 'Minimize', 'Pass');
}
loadCargoDialog.onconfirm = function() {
// Submit the form if it exists, then hide the dialog.
loadCargoDialog.hide();
actionPrompt = document.getElementById('action-prompt');
actionPrompt.setInnerXHTML('<span><div id="action-text">'+
'The "Load cargo" dialog has been minimized'+
'</div>'+
'<div id="action-end">'+
'<form action="" method="POST">'+
'<input type="button" value="Maximize" id="next-phase" onclick="loadCargo();" />'+
'</form>'+
'</div></span>');
actionButton = document.getElementById('next-phase');
actionButton.setValue('Maximize');
actionButton.addEventListener('click', loadCargoEventHandler);
};
loadCargoDialog.oncancel = function() {
moveTrainManual();
}
}
}
ajax.post(baseURL + '/turn/load-cargo-dialog-fbjs', data);
}
ajax.post(baseURL + '/turn/load-cargo');
}
It looks like you might be creating elements with the same id. That would cause it to break.
Now All of this code works fine in Firfox but in IE the divs dont change when the php infomation changes.
Can some one help me please as i am working on a project and this is holding me back
Thank you.
Here is the jQuery Code:
$.ajaxSetup({ cache: false });
$(document).ready(function(){
$("#not").css('display','none');
$("#fonline").css('display','none');
$("#not").hide();
$("#fonline").hide();
$("#shfm").click(function () {
$("#not").hide();
$("#fonline").toggle();
});
$("#notifi").click(function () {
$("#fonline").hide();
$("#not").toggle();
});
});
function closeboxes() {
$("#fonline").hide();
$("#not").hide();
}
function loadContent(id) {
$("#contentArea").load("notifications.php?o="+id+"");
};
$(document).ready(function() {
$("#settings").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Settings');
}
);
});
function FriendsContent(id) {
$("#fArea").load("friends_online.php?fo="+id+"");
};
$(document).ready(function() {
$("#Options").toggle(
function () {
$(this).html('X Close');
},
function () {
$(this).html('Options');
}
);
});
var refreshId = setInterval(function()
{
$('#fArea').fadeOut("slow").load('response.php').fadeIn("slow");
}, 10000);
PHP Code:
$cOption = $_GET['fo'];
switch($cOption) {
case 1:
$recordsPerPage = 5;
$pageNum = 1;
if(isset($_GET['pg'])) {
$pageNum = $_GET['pg'];
settype($pageNum, 'integer');
}
echo "<table width='98%' border='0' cellspacing='0' cellpadding='0'>";
$offset = ($pageNum - 1) * $recordsPerPage;
$onlineresult = mysql_query("SELECT * FROM online") or die (mysql_error());
while ($ousers = mysql_fetch_array($onlineresult)) {
$onuid = $ousers['uid'];
$flist = mysql_query("SELECT * FROM friends_list WHERE fid='$onuid' AND uid='$myid' LIMIT $offset, $recordsPerPage;") or die (mysql_error());
while ($fri = mysql_fetch_array($flist)) {
$id = $fir['id'];
$uid = $fri['uid'];
$fid = $fri['fid'];
$userinfomation = mysql_query("SELECT * FROM accounts WHERE id='$fid'");
$userinfo = mysql_fetch_array($userinfomation);
$v_tgid = $userinfo['tgid'];
echo "
<tr class='menutxt2'>
<td width='11%' height='21'><center>
</center></td>
<td width='50%'>$v_tgid</td>
<td width='39%'>View Profile</td>
</tr>
";
}
}
echo "</table>";
$query = "SELECT COUNT(id) AS id FROM friends_list;";
$result = mysql_query($query) or die('Mysql Err. 2');
$row = mysql_fetch_assoc($result);
$numrows = $row['id'];
$maxPage = ceil($numrows/$recordsPerPage);
$nav = '';
for($page = 1; $page <= $maxPage; $page++)
{
if ($page == $pageNum)
{
$nav .= "<span class='menutxt'>Pages: $page </span>";
}
else
{
$nav .= "";
}
}
if ($pageNum > 1) {
$page = $pageNum - 1;
$prev = "";
$first = "";
}
else {
$prev = '';
$first = '';
}
if ($pageNum < $maxPage) {
$page = $pageNum + 1;
$next = "";
$last = "";
}
else {
$next = '';
$last = '';
}
echo "$first <b>$prev</b> $nav<b> $next</b> $last";
echo "
";
break;
case 2:
echo 'Options';
break;
default:
echo 'Whoops, didn\'t understand that option: <i>'.$cOption.'</i>';
}
IE tends to cache ajax requests when you don't want it to. The .load() towards the end of your code is issuing a GET request which IE is probably caching instead of fetching from the server.
http://www.sitecrafting.com/blog/ajax-ie-caching-issues/
google search 'ie cache ajax jquery'