OMG, I am in need of a way to set up arrays of XML Requests based on the idShout - 1.
So it would be something like this...
var req = new Array();
req[idShout - 1] = ALL XML Data...
Here's what I got so far but it's not working at all :(
var idShout;
var req = new Array();
function htmlRequest(url, params, method)
{
req[req.push] = ajax_function();
for (i=0;i<req.length;i++)
{
(function (i) {
if (req[i])
{
if (method == "GET")
{
req[i].onreadystatechange = function()
{
if (req[i].readyState != 4)
return;
if (req[i].responseText !== null && req[i].status == 200)
{
document.getElementById("shoutbox_area" + idShout).innerHTML = req[i].responseText;
}
}
}
req[i].open(method,url,true);
if (method == "POST")
req[i].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (params == "")
req[i].send(null);
else
req[i].send(params);
return req[i];
}
else
return null;
})(i);
}
}
function ajax_function()
{
var ajax_request = null;
try
{
// Opera 8.0+, Firefox, Safari
ajax_request = new XMLHttpRequest();
}
catch (e)
{
// IE Browsers
try
{
ajax_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajax_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
//No browser support, rare case
return null;
}
}
}
return ajax_request;
}
function send(which)
{
var send_data = "shoutmessage=" + document.getElementById("shout_message" + which).value;
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dreamaction;sa=shoutbox;xml;send_shout="+ which;
htmlRequest(url, send_data, "POST");
document.getElementById("shout_message" + which).value = "";
document.getElementById("shout_message" + which).focus();
return true;
}
function startShouts(refreshRate, shoutCount)
{
clearInterval(Timer[shoutCount-1]);
idShout = shoutCount;
show_shouts();
Timer[shoutCount - 1] = setInterval("show_shouts()", refreshRate);
return;
}
function show_shouts()
{
var url = smf_prepareScriptUrl(smf_scripturl) + "action=dreamaction;sa=shoutbox;xml;get_shouts=" + idShout;
htmlRequest(url, "", "GET");
}
Any help at all on this would be greatly appreciated...
Basically, I'm setting the Timer Arrays in a different function before this, and I call startShouts which is supposed to show all of the information, but startShouts gets called more than once, which is why I have idShout set to equal shoutCount. So it will go something like this: shoutCount = 1, shoutCount = 2, shoutCount = 3, everytime it is being called. So I set the req[idShout - 1] array and it should return the result right??
Well, I get no errors in Firefox in the error console with this code above, but it doesn't work... Any ideas anyone?? As it needs to output into more than 1 area... argg.
Thanks for any help you can offer here :)
Thanks guys :)
Also, a little more info on this...
Basically there is 1 or more Shoutboxes on any given page (Don't ask why?), I need to be able to grab the info of this and put it into the document.getElementById("shoutbox_area" + idShout), since the idShout for each element changes incrementing by 1 for each Shoutbox that is on that page. The values for the Shoutbox can be different, example the refreshRate can be different. 1 Shoutbox can have a refresh rate of like 2000 milliseconds, while the other can have a rate of 250 milliseconds, they need to be different and refresh at the times that are defined for them, so this is why I decided to make a Timer array, though not sure I have setup the Timer array the way it is meant to be setup for the setInterval function. Here is the way it get's done in a different javascript function that runs just before startShouts gets called...
This part is outside of the function and within the document itself:
var Timer = new Array();
And this part is in the function...
Timer[shoutCount - 1] = "";
So not sure if this is correctly setup for Timers...?
Since XHRs are asynchronous, by the time the readystatechange callback function fires the value of i has changed. You need to create a separate closure for the i variable during your loop. The easiest way to do this is wrap an anonymous function around the code block and call it with i passed as the first argument:
for (i=0;i<req.length;i++)
{
(function (i) {
if (req[i])
{
if (HttpMethod == "GET")
{
req[i].onreadystatechange = function()
{
if (req[i].readyState != 4)
return;
if (req[i].responseText !== null && req[i].status == 200)
{
document.getElementById("shoutbox_area" + idShout).innerHTML = req[i].responseText;
}
}
}
req[i].open(HttpMethod,url,true);
if (HttpMethod == "POST")
req[i].setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
if (params == "")
req[i].send(null);
else
req[i].send(params);
return req[i];
}
else
return null;
})(i);
}
Related
I have a problem with following code:
var status = null;
var action = 1;
function test() {
if(status != null || action == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I get expected results in Firefox and IE alert('I should be here'). But in Chrome i get alert('Why am i here?').
I'm not able to reproduce this for you, but I might just have the answer:
if(status !== null || action === 3) {
Compare the variable not just by value but also by type, by using an extra =
status and action var names seem too good to not be system reserved. maybe your chrome has something running with a status var allocated. try changing them to something else and see if it makes a difference.
var myStatus = null;
var myAction = 1;
function test() {
if(myStatus != null || myAction == 3) {
alert('Why am i her?');
}else {
alert('I should be here');
}
}
test();
I have 3 ajax call in one function and checkAjaxCompletion which checks each ajax completion flag.
What the code below does is send multiple separate ajax calls and interval method checks completion flags to determine whether to proceed or keep interval. (I know clearInterval is not shown but the point is I want to use something other than interval)
Current code is:
function manyAjax() {
setInterval( function() { checkAjaxCompletion(); } , 200);
ajax1();
ajax2();
ajax3();
}
function ajax1() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function ajax2() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function ajax3() {
//send ajax request to server and if success set flag to 1. Default is 0. Error is 2.
}
function checkAjaxCompletion() {
if(ajax1_flag == 1 && ajax2_flag == 1 && ajax3_flag == 1) {
//everything went success, do some process
}
else if(ajax1_flag == 2 || ajax2_flag == 2 || ajax3_flag == 2) {
//some ajax failed, do some process
}
else {
//all ajax have not been completed so keep interval i.e. do nothing here
}
}
But I'm hesitating to depend on using interval function because calling it so often seem such waste of memory. There must be better way to do. I'm thinking if observer pattern can be applied here but would like to hear opinions.
It is observer-notifier, if you want to call it that - but each of your ajax calls will more than likely have a callback in javascript when they complete. Why not call checkAjaxCompletion() at the end of each of them, and do nothing if you're still waiting on others?
Dustin Diaz does a great job with this example.
function Observer() {
this.fns = [];
}
Observer.prototype = {
subscribe : function(fn) {
this.fns.push(fn);
},
unsubscribe : function(fn) {
this.fns = this.fns.filter(
function(el) {
if ( el !== fn ) {
return el;
}
}
);
},
fire : function(o, thisObj) {
var scope = thisObj || window;
this.fns.forEach(
function(el) {
el.call(scope, o);
}
);
}
};
The publisher:
var o = new Observer;
o.fire('here is my data');
The subscriber:
var fn = function() {
// my callback stuff
};
o.subscribe(fn);
To unsubscribe:
var fn = function() {
// my callback stuff
};
o.subscribe(fn);
// ajax callback
this.ajaxCallback = function(){
$.ajax({
type: "POST",
url: ajax.url,
data: {key: value},
async : !isAll,// false使用同步方式执行AJAX,true使用异步方式执行ajax
dataType: "json",
success: function(data){
if(data.status == 'successful'){
selfVal.parent().find('.msg').addClass('ok').html(msg.ok);
}else if(data.status == 'failed'){
checkRet = false;
selfVal.parent().find('.msg').removeClass('ok').html(msg.error);
}else{
checkRet = false;
}
return this;
}
});
}
return this;
Maybe you want to check your inputvalue callback ajax in your form;
You can view my website Demo, hope help you.
http://6yang.net/myjavascriptlib/regForm
Okay my idea was to make your own object that can handle sending an array of requests, keep a history of each request and do what i'm gonna call 'postProccessing' on each response, here is a probably very dodgy bit of code to hopefully demonstrate what I am thinking.
var Ajax = function() {
var request, callback, lst;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = handleResponse;
this.history = [{}];
this.send = function(args) {
for (var i = 0; i < args.length; i++) {
if (args.url) {
request.open(args.type || 'GET', args.url);
}
request.send(args.data || null);
callback = args.callback;
lst++;
}
}
function handleResponse() {
var response = {
url: '',
success: true,
data: 'blah'
};
history.push(response);
if (postProccess()) {
callback();
}
}
function postProcess() {
if (this.history[lst].success) {
return true;
} else {
return false;
}
}
}
function addphoto()
{
var ajaxRequest = initAjax();
if (ajaxRequest == false)
{
return false;
}
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
return ajaxRequest.responseText;
}
}
// Capture form elements
var values = {
"category" : encodeURIComponent(document.addphoto.category.options[document.addphoto.category.selectedIndex].value),
"photo_title" : encodeURIComponent(document.addphoto.photo_title.value),
"photo_descrip" : encodeURIComponent(document.addphoto.photo_descrip.value)
}
var queryString = '?', i = 0;
for (var key in values)
{
if (i != 0)
{
queryString += '&'
}
queryString += key + '=' + values[key];
i++;
}
// Execute Ajax
ajaxRequest.open("POST", "ajaxcheckform.php" + queryString, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(null);
}
function ajaxCheckform(formname)
{
var response = addphoto(); // <--This is undefined and not sure why
var responseObj = JSON.parse(response);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
I'm sure I must be making some basic error somewhere, but I'm having trouble locating it. In this script, ajaxCheckform() is a function that executes one of several similar functions. Above, I included addphoto(), which is one of several functions I'll need that look like this.
On a side note, I'd love to know I can call upon a function dynamically. The addphoto() function will be only one such function being called up at that moment and I'm trying to find a way to pass formname as the function I need. I've searched Stackoverflow and Google. I've found nothing that works.
Note, I'm aware of jQuery, but I'm not there yet. I need this function to work first.
It is not addphoto() thats undefined but response is undefined. ajaxRequest is asynchronous and the addphoto() function will return before the request completes.
try this
function addphoto() {...
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
var responseObj = JSON.parse(ajaxRequest.responseText);
if (responseObj.success == 1) {
// Successful form!
alert(responseObj.success_text);
}
else {
// Error!
alert(responseObj.error);
}
}
}
....
}
function ajaxCheckform(formname) {
addphoto();
}
That's because response is set to the return of addphoto(), which is nothing. What you want to do is have ajaxCheckForm get called when the AJAX call is completed:
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
ajaxCheckform(ajaxRequest.responseText);
}
}
Then your ajaxCheckform will work with that data:
function ajaxCheckform(responseText)
{
var responseObj = JSON.parse(responseText);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
You can't return from an event handler (which onreadystatechange is).
You have to do the work inside that event handler.
addphoto() does not return anything (or rather, returns inconsistently) ... the onreadystatechange event's handler is returning the value, but there is no caller that will receive that json string.
I'd highly suggest that you abstract these details away with something like jquery ... just follow the docs for suggested usage and this code will be much simpler
You're sending a GET style parameter list to a POST method.
You need to send that string in the body of your HTTP request.
var response = addphoto(); // <--This is undefined and not sure why
The addphoto() function never has a return statement in it, so it returns undefined. And the ajaxRequest is asynchrous and wont return immediately.
I run a JavaScript function that send a xmlHttpRequest to an .ashx (let's name it send_req() that run on page load for first time). For onreadystatechange, I have a function that receive XML data and show it on the page (let's name this one getanswer()).
I want to automatically update XML data on the page every 20 seconds. For that, I use setTimeout(send_req(),20000) in the end of writexml(), but it doesn't update data on the page. I add an alert() at the **** line in the code. It shows on the page every one second!
And my code works fine if I use it without setTimeout.
Here is my code
var Population = "";
var Available_money = "";
var resource_timer;
var httpReq_resource;
function send_req() {
if (window.ActiveXObject) {
httpReq_resource = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
httpReq_resource = new XMLHttpRequest();
}
var sendStr = "user_id=1";
if (httpReq_resource)
{
httpReq_resource.onreadystatechange = getanswer;
httpReq_resource.open("POST", "Answer_Resource_change.ashx");
httpReq_resource.send(sendStr);
}
}
function getanswer() {
var results = httpReq_resource.responseXML;
if (httpReq_resource.readyState == 4) {
if (httpReq_resource.status == 200) {
try {
var value;
var values = results.getElementsByTagName("values");
for (var i = 0; i < values.length; i++) {
value = values[i];
Population = value.getElementsByTagName("Population")[0].firstChild.nodeValue;
Available_money = value.getElementsByTagName("Available_money")[0].firstChild.nodeValue;
... and some more like two line up
}
make_changes();
**********************************
resource_timer = setTimeout(send_req(), 20000);
}
catch (e) {
}
}
}
}
function make_changes() {
$("li span#l1").text(Available_money + '/' + Population);
...and some more like up line
}
This:
resource_timer = setTimeout(send_req(), 20000);
Should be:
resource_timer = setTimeout(send_req, 20000);
The first executes the result of send_req() after 20 seconds, the second executes send_req itself.
I have this code that make 3 requests to a server, the code works fine with the request but when I receive the response the code fails, take avoid the first response and give me the third.
phone.open("POST", '/', true);
phone.setRequestHeader("Content-type", elmnt.getAttribute('ctype'));
phone.send(reqStr);
This is the code that catch the response.
phone = new ConstructorXMLHttpRequest();
onreadystatechange = function(){
if(phone.readyState == 4){
if(phone.status == 200){
var val = phone.responseText;
alert(phone.responseText)
dataInsert(val);
break;
}else{
alert("Problemas status:"+phone.status+" state:"+phone.readyState);
break;
}
}
};
#Hemlock here is the code of the constructor:
function ConstructorXMLHttpRequest()
{
if(window.XMLHttpRequest) /*XMLHttpRequest(Browsers Mozilla, Safari and Opera). */
{
return new XMLHttpRequest();
}
else if(window.ActiveXObject) /*IE*/
{
/*There a several difference between versions of IE, so
* if the kids of MS release a new please put in this Array.*/
var versionesObj = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < versionesObj.length; i++)
{
try
{
return new ActiveXObject(versionesObj[i]);
}
catch (errorControlado)
{
}
}
}
throw new Error("Couldn't make a XMLHttpRequest");
}
The reason people think this is funny is because your case statement is A) useless because you don't actually want to take different actions depending on the state of the object, you actually only want to act on its status under one condition and B) your case is used in conjunction with an if statement, which is redundant - not to mention syntactically erroneous.
I think you're trying to do
if(phone.readyState == 4){
var val = phone.responseText;
alert(val);
dataInsert(val);
}else{
alert("Problemas status:"+phone.status+" state:"+phone.readyState);
}
I also think you should look into using a 3rd party library like jQuery to do your ajax.
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: 'getData.html',
success: function(val) {
alert(val);
dataInsert(val);
}
});