Ok. I need help with this. For some reason the onreadystatechange is fired multiple times. I really need to get this figured out tonight. It's the last task I have left and I don't know what to do or what's causing it. Please help.
I'm using AJAX (ndhr) to send over JSON 'Y-m-d h:i:s' to PHP to use the strtotime() function to return 'm-d-Y' back through AJAX. The JSON and PHP work great, but when the onreadystatechange is fired it does it multiple times. Almost like the readyState == 4 more times than it does.
var divs_d = ["d_2009", "d_2010", "d_2011"];
function ajax_get_json(cdiv,ocdv,ed){
var hr = new XMLHttpRequest();
hr.open("GET", "/json/sample.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
cdiv.innerHTML = "";
var data = JSON.parse(hr.responseText);
var cad = data.comm_archive;
var rndate;
var nda = new Array();
var ndac = 0;
var ec = 0;
for (ni = 0; ni < cad.length; ni++) {
if (cad[ni].year == ocdv) {
ec = ec + 1;
ed.innerHTML = '<h4>' + ocdv + ' (' + ec + ' entries)</h4>';
var ndhr = new XMLHttpRequest();
var url = "/inc/strtotime.php";
var vars = "ndate=" + cad[ni].publish_date;
ndhr.open("POST", url, true);
ndhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ndhr.onreadystatechange = function () {
if (ndhr.readyState == 4 && ndhr.status == 200) {
nda[ndac] = ndhr.responseText;
ndac = ndac + 1;
}
}
ndhr.send(vars);
}
}
nda.sort(function (a, b) { return b - a });
for (ndai = 0; ndai < ndac; ndai++) {
cdiv.innerHTML += '<h4>' + nda[ndai] + '</h4>';
}
}
}
hr.send(null);
}
function optionCchange() {
var ocdv = document.getElementById("optionCdate").value;
var ed = document.getElementById("ediv");
for (i = 0; i < divs_d.length; i++) {
var cdiv = document.getElementById(divs_d[i]);
if (divs_d[i] == "d_" + ocdv) {
cdiv.className = "bddiv show";
ajax_get_json(cdiv,ocdv,ed);
} else {
cdiv.className = "bddiv hide";
}
}
}
In your ndhr.onreadystatechange function ndhr represents the last ndhr created in the loop not the calling one, to reference the calling object use this.
ndhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
nda[ndac] = this.responseText;
ndac = ndac + 1;
}
}
The the last for(ndai = 0; ndai < ndac; ndai++) is behaving as you expect because of the asynchronous nature of ajax, by the time that code is executed the ajax requests have not finished yet. You'll have to execute this code in the on ready change state callback. Just use a counter to check if all the ajax requests have finished then execute the code.
If you need run the code once, you don't have to be anxious about how many times readystate 4 was fired. Simply use a boolean variable to check if the block of code has been executed.
Here's a pseudocode example of my idea.
executed = false;
if (readystate && (executed == false))
{
blablabla;
executed = true;
}
else
{
sry your code has been executed;
}
Related
I have a website, and all its files (html/js/css/php) are on the same remote host. I have a button on the site, when clicked it sends a httprequest to a PHP file, waiting for a response.
My site works perfect almost everywhere, but there is one place which when I connect to the wi-fi, when clicking the button it return whit the error ERR_EMPTY_RESPONSE. Other buttons and PHP files work. It is only this specific button and in this specific wi-fi.
Does anyone know why does it happen and how to fix it?
details:
the button is <button class="btn btn-default col-sm-5" type="submit">
the onClick function:
function search() {
var param = "";
var firstParam = true;
var form = document.getElementById("formCS");
var name = document.getElementById("songName").value.trim();
if (name != "") {
firstParam = false;
param += "name=" + name;
}
var creator = document.getElementById("creator").value.trim();
if (creator != "") {
if (firstParam) {
param += "creator=" + creator;
firstParam = false;
} else {
param += "&creator=" + creator;
}
}
var type;
if (document.getElementById("partners").checked) {
type = "partners";
} else if (document.getElementById("circle").checked) {
type = "circle";
} else if (document.getElementById("lines").checked) {
type = "lines";
} else if (document.getElementById("none").checked) {
type = "";
}
if (type != "") {
if (firstParam) {
param += "type=" + type;
firstParam = false;
} else {
param += "&type=" + type;
}
}
var year = document.getElementById("year").value;
if (year != "none") {
if (firstParam) {
param += "year=" + year;
} else {
param += "&year=" + year;
}
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
handleResponse(xhttp.response);
}
};
xhttp.open("GET", "search.php?" + param, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
the search.php file connects to a DB on the remote host and runs a sql query. nothing different from other buttons on the site.
the wi-fi is a free wi-fi provided by an academic institue.
after clicking the button there is an error in the console:
GET http://rikudim.info/search.php? net::ERR_EMPTY_REPONSE
I'm calling a PHP file with XMLHttpRequest, but now the call doesn't complete and I
have no idea why. The req.readyState isn't 4, and I don't know why because the PHP file is okay and does exactly what supposed to (just echo a string).
Can anyone see what I can not see?
function processAjax(id, option) {
if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id;
else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id;
//create AJAX request
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv();
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv();
req.open("GET", url, true);
req.send();
}
}
}
//this function handles the response from the ajax request
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
//all of the code below doesn't happen because its not the option
if (option == "lpath") {
var response = req.responseText.split('##');
var articles = response[0].split(';');
var quizes = response[1].split(';');
document.getElementById("article_id").innerHTML = "";
document.getElementById("quiz_id").innerHTML = "";
for (var i = 0; i < articles.length; i = i + 2) {
if ((i + 1) <= articles.length) {
var option = new Option( /* Label */ articles[i + 1], /* Value */ articles[i]);
document.getElementById("article_id").options.add(option);
}
}
for (var i = 0; i < quizes.length; i = i + 2) {
if ((i + 1) <= quizes.length) {
var option = new Option( /* Label */ quizes[i + 1], /* Value */ quizes[i]);
document.getElementById("quiz_id").options.add(option);
}
}
delete req, articles, quizes;
} else {
document.getElementById("catdiv").innerHTML += req.responseText;
document.getElementById("allchildren").value = req.responseText;
}
} else { //failed to get response
alert("Problem: " + req.statusText);
}
}
document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!";
}
req.onreadystatechange = targetDiv();
should be
req.onreadystatechange = targetDiv;
The original code calls targetDiv() immediately after that line of code is run, which is probably not what you wanted to do. The fixed code calls the function correctly, after the Ajax request is received.
I am trying to create a website like penny auction how to display the count down time?
i tried that using ajax, but sometimes it swallow one or two seconds, it shows seconds like 10,9,7,6,3... i mean it doesn't show the proper count down time.. please help me to solve this problem
here is my code
<?php
#session_start();
include "includes/common.php";
include_once "includes/classes/class.Auction.php";
$objAuction = new Auction();
$result=$objAuction -> getStatus();
echo $result;
?>
//ajax code
function getStatusOne(pId)
{
var strURL="get_status_one.php?pId="+pId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
//alert(req.responseText);
var result= req.responseText.substr(1).split("|");
for (var x = 0; x < result.length; x++)
{
var resultN=result[x].split(",");
var prId=resultN[0];
var temp=resultN[1];
var sec=parseInt(temp);
var price=resultN[2];
//alert(prId+' '+temp+' '+price);
var mem=resultN[3];
var img=resultN[4];
var autobid=resultN[5];
if(img=='') {
img='images/profile/no_image.jpg'
}
if(!price)
{
price='0.00';
}
if(!mem)
{
mem='No Bidders Yet';
}
if(document.getElementById("bid_price"+prId))
{
document.getElementById("bid_price"+prId).innerHTML='$'+price;
document.getElementById("bidder_name"+prId).innerHTML=mem;
document.getElementById("userimg").src=img;
document.getElementById("bid_rate").innerHtml=autobid;
if(sec<= -1)
{
sold(prId);
if(document.getElementById('end'+pId))
{
document.getElementById('end'+pId).style.display="block";
}
if(document.getElementById('div_bid_image'))
{
document.getElementById('div_bid_image').style.display="none";
}
if(document.getElementById('clsBidB'+pId))
{
document.getElementById('clsBidB'+pId).style.display="none";
}
}
else {
if(document.getElementById('div_bid_image').style.display == "none")
{
document.getElementById('div_bid_image').style.display="block";
}
if(sec >=0)
{
SetCountdownText(sec,"div_timer"+prId,prId);
}
}
}
}
}
else
{
//alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
//php code to calculate time
function getStatus()
{
$selProd="select a.pdt_id, unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."') as seconds, b.bid_price,c.uname from tbl_products a left join tbl_auction b on a.pdt_id=b.product_id left join tbl_members c on b.member_id=c.member_id where(select unix_timestamp(a.end_date) - unix_timestamp('".date('Y-m-d H:i:s')."'))>= 0 ";
if($this->ExecuteQuery($selProd,"norows") > 0)
{
$auctionArr=$this->ExecuteQuery($selProd,"select");
$auctionName=$this->array2str($auctionArr);
}
return $auctionName;
}
function array2str($array,$level=1)
{
$str = array();
foreach($array as $key=>$value) {
if(is_int($key))
{
$nkey = $key;
$nvalue = is_array($value)?'|'.$this->array2str( $value ) : $value;
$str[] = $nvalue;
}
}
return implode(',',$str);
}
try this
<?php
$target = mktime(0, 0, 0, 14, 07, 2011) ;
$today = time () ;
$difference =($target-$today) ;
$days =(int) ($difference/86400) ;
print "Our event will occur in $days days";
?>
Assuming you have something like a DIV with the ID "countdown" (to display the countdown in):
Example JavaScript (assumes use of jQuery - recommended):
(function(jQuery) {
updateCountdown("countdown"); // Call on page load
var countdown = setInterval('updateCountdown("countdown")', 1000); // Update countdown every second
})(jQuery);
function updateCountdown(elementId) {
jQuery.ajax({
url: "/ajax/countdown.php?auctionId=123",
type: "GET",
dataType: "json",
success: function(response) {
// Insert value into target element
jQuery("#"+elementId).html(response["timeRemaining"]);
// Stop countdown when complete
if (response["countdownComplete"] == true)
clearInterval(countdown);
}
});
}
Example PHP script (assumed to be at /ajax/countdown.php by the above JavaScript):
<? php
/* Insert your own logic here */
$response["timeRemaining"] = "5 seconds";
$response["countdownComplete"] = false; // Set to true when countdown complete
echo json_encode(response);
?>
I'd recommend doing all the calculation server side (in PHP) as it has really excellent time/date handling (with lots of built in methods) and requires less code to implement overall.
Have a PHP page echo out the countdown time. And then use something like jQuery's AJAX HTTP Request for that page and populate the response in a DOM element somewhere.
Why do you need Ajax to display the countdown time? Why can't you just display it when the page loads along with the rest of the data?
i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<body>
<a href="addevent.php" rel="facebox" >link</a>
</body>
addevent.php
<head>
<script src="inc/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="inc/facebox.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i<elemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i < len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i<formNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i < max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
</script>
<script type="text/javascript">
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i < lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") > -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j < labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
</script>
</head>
<form name="eventAgendaForm" id="eventAgendaForm" >
<ul class="checklist cl3">
<li ><label for="c1">
<input id="checkId" name="checkName" value="1" type="checkbox" >
</label></li></ul>
<input class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" />
</form>
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.
I am trying to implement a Javascript/PHP/AJAX clock into my website so that I can have a simple clock which can operate in different timezones (tutorial is here http://networking.mydesigntool.com/viewtopic.php?tid=373&id=31)
This itself works fine, but I already have a javascript stopwatch running on the page, and the 2 seem to clash and the clock won't display while the stopwatch is working.
This is the script for the clock:
<script type="text/javascript">
function loadTime ()
{
http_request = false;
if(window.XMLHttpRequest)
{
// Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType)
{
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
}
else if(window.ActiveXObject)
{ // IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
}
}
}
var parameters = "time=";
http_request.onreadystatechange = alertContents;
http_request.open('POST', 'time.php', true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents()
{
if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
result = http_request.responseText;
document.getElementById('clock').innerHTML = result;
}
}
}
</script>
<body onload="setInterval('loadTime()', 200);">
and this is the code for the stopwatch:
<script type="text/javascript">
window.onload = function()
{
stopwatch('Start');
}
var sec = 0;
var min = 0;
var hour = 0;
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1;
} else {
min = min;
}
if (min == 60) {
min = 0;
hour += 1;
}
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Stop "; }
if (text == "Stop ") { document.clock.theButton.value = "Start"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true;
}
SD=window.setTimeout("stopwatch();", 1000);
}
function resetIt() {
sec = -1;
min = 0;
hour = 0;
if (document.clock.theButton.value == "Stop ") {
document.clock.theButton.value = "Start";
}
window.clearTimeout(SD);
}
</script>
Could someone help me get them to work side-by-side please?
Thanks for any help
For one, your’re declaring an onload event handler in your HTML:
<body onload="setInterval('loadTime()', 200);">
which is consequently overwritten in script:
window.onload = function()
{
stopwatch('Start');
}
This means the original onload call is never executed.
You should try using addEventListener so you can add multiple event handlers to the same event.
A couple more points:
Don’t pass a string to setInterval and setTimeout, just pass the function itself. More efficient and less error-prone: setInterval(loadTime, 200);
Instead of writing all that JS code to work with different browsers, use jQuery, mootools, or one of the gazillion other frameworks. They make it a lot easier to get it right on all browsers.
Try this:
See the subtle '+=' instead of '=' !
window.onload += function()
{
stopwatch('Start');
}