Turning a delimited string retrieved via AJAX back into a multidimensional array - javascript

I imagine at some point my familiarity with PHP is making me write something incorrectly, but I've been reading up and can't seem to find a way to achieve what the below is intended to achieve. In the end, I should have a multidimensional array like such:
cardArray[#]
'uniqueID' => "#";
'cardName' => "blahblah";
'series' => "blahblah";
(Where the #s are actual numbers, of course.) The string that is returned via AJAX is formatted such that each set of 3 is delimited by a colon and within each set each item is delimited by a pipe. (The final line I just threw in as a test to see if ANYTHING was getting stored.)
Here's the code:
function buildCardList() {
var returnedString;
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) {
returnedString = xmlhttp.responseText;
}
}
xmlhttp.open("POST","test02.php",true);
xmlhttp.send();
var cardArray = new Array();
cardArray = returnedString.split(":");
for (var i = 0; i < cardArray.length; i++) {
var tempVar = cardArray[i];
var tempArr = tempVar.split("|");
cardArray[i] = {
"uniqueID" : tempArr[0],
"cardName" : tempArr[1],
"series" : tempArr[2]
};
}
document.getElementById("test").innerHTML = cardArray[0]['uniqueID'] + "<br>" + cardArray[0]['cardName'] + "<br>" + cardArray[0]['series'] + "<br><br>";
}

Related

progress bar using multiple ajax calls for asp.net

I have an application that has a long time processing in code behind.
I was thinking on starting the long time processing by calling from javascript a page,
function OnCopy(type){
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){
//window.clearInterval(interval_handler);
alert('done');
}
}
xmlhttp.open("GET", "<%=Request.Path %>?copy=" + type, true);
xmlhttp.send();
interval_handler = window.setInterval(OnCheckStatus, 1000);
}
The last line of this function will start a timer, to check every second the status:
function OnCheckStatus(){
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){
//window.clearInterval(interval_handler);
//var result = eval(xmlhttp.responseText);
//var pb = document.getElementById('progressbar_' + result[0]);
//if(pb != null)
// pb.innerHTML = result[1] + ' % - ' + result[2];
debug++;
var pb = document.getElementById('progressbar_test');
pb.innerHTML = debug;
}
}
xmlhttp.open("GET", "<%=Request.Path %>?checkstatus=1", true);
xmlhttp.send();
}
On code behind I have this long time processing function and check status function:
private void Copy(string type)
{
Application["ProgressBar.Type"] = type;
for (int i = 0; i < 100; i++)
{
System.Threading.Thread.Sleep(100);
Application["ProgressBar.Value"] = i.ToString();
}
Application["ProgressBar.Type"] = null;
Application["ProgressBar.Value"] = null;
}
private void CheckStatus()
{
Response.Clear();
string type = (string)Application["ProgressBar.Type"];
string value = (string)Application["ProgressBar.Value"];
if (type == null) type = "";
if (value == null) value = "";
string response = "['" + type + "','" + value + "','" + DateTime.Now.ToString("HH:mm:ss") + "']";
Response.Write(response);
Response.End();
}
Now, the problem is that until the Copy function is not finished, there is no answer on the CheckStatus function from code behind (I think all calls are queued), but, when is finished, the displayed debug value is starting from 10, directly, like all the answers for these 10 calls are coming at the same time.
Is like ASP.NET is only responding to one call only at a time, from the browser. I was having the impression that the server will process at least 2 calls at the same time from the same browser.
Can you help me with this, please?
Please check this article. I think that it will help you with your issue.
But also there is an integrated solution in asp.net webforms named as UpdateProgress msdn link with example

Displaying binary code of a file in ajax

I want to display the binary code of a music file. But somehow the code below doesn't seem to work. Any suggestions??
function binary() {
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.open("GET","1.wav",true);
xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
xmlhttp.onreadystatechange = function(buffer) {
var binaryCode = "";
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var binStr = this.responseText;
for (var i=0; i<binStr.length; i++) {
var byte = binStr.charCodeAt(i) & 0xff; // get byte at i
binaryCode += byte;
}
}
document.getElementById("result").innerHTML = binaryCode; // should display binary code
};
xmlhttp.send();
}
Not all byte values are expressible in a string and will not appear or cause the string to cut off short.
XMLHttpResponse.ResponseText/ResponseXML will return the http response content as a string. Any byte values of 0 for example will terminate the string.
Have the server return a Base64 representation of the bytes and decode into byte values on the client side.
Your code seems to be working fine on my chrome browser.
What is exactly the problem your are experimenting ?
You may want to display the binary in an hexadecimal form by doing something like:
binaryCode += '0x' + byte.toString(16) + ' '
edit:
this jsfiddle works on my chrome:
http://jsfiddle.net/e6Kfk/
However, i do not think that this method is crossbrowser, especially if you want to deal with ie (haven't tested it though)

Need 2 functions to run onLoad with Ajax - only 1 working

Starts with shuffle functions (just shuffles arrays). It works.
Then I define 2 global variables that will determine the random order for images to be displayed on the page.
picOrder will be a simple array from 0 to picCount, with picCount determined by Ajax onload. The picCount is being retrieved, but the the picOrder array is not being set! If I manually run "arrangePics();" in the console it works. It fills the array picOrder and then shuffles it. But it does not work by placing the calls to both functions inside "" or by putting the "doStuff()" function in there.
Array.prototype.shuffle = function() {
var s = [];
while (this.length) s.push(this.splice(Math.random() * this.length, 1)[0]);
while (s.length) this.push(s.pop());
return this;
}
var picOrder = new Array();
var picCount;
function getPicCount() {
// picCount = array(10);
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) {
picCount = xmlhttp.responseText;
}
}
xmlhttp.open("GET","/example.com/images.php?count=hello",true);
xmlhttp.send();
//picCount.shuffle;
}
function arrangePics() {
for(var i = 0;i<picCount;i++) {
picOrder[i] = i;
}
picOrder.shuffle();
//alert(picOrder);
}
HTML
<body onLoad="getPicCount();arrangePics();">
or
<body onLoad="doStuff();">
You need to arrangePics() after the asynchronous AJAX call has returned, i.e. you can only call it in the if (xmlhttp.readyState==4 && xmlhttp.status==200) {} (callback) block otherwise you cannot be sure that the data has been fully received.
What is currently happening is that JavaScript is calling getPicCount();arrangePics(); - the first method initiates the AJAX call and returns immediately and then the second method will by trying to arrange 0 pics. Executing arrangePics() manually on the console would have introduced enough delay into the system for the AJAX call to complete and the picCount would be set as expected.
So if you change the callback function to:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
picCount = xmlhttp.responseText;
for(var i = 0;i<picCount;i++) {
picOrder[i] = i;
}
picOrder.shuffle();
}
it should shuffle the pics after the count has been received.

javascript ajax: get value

i have problem in getting and testing the return value of ajax.
my code is, and return when alert is => Nan.
function getValue(table1, table2, id1, id2)
{
alert("table name "+table2+" id: "+id2);
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)
{
alert("ajax value: "+xmlhttp.responseText - 0);
var val = xmlhttp.responseText - 0;
var price = document.getElementById("price");
var original= price.value;
original = original - 0;
var new_val = original + val;
price.value = new_val;
document.getElementById("showprice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","_pages/ajax/advert_temp.php? t1="+table1+"&t2="+table2+"&id1="+id1+"&id2="+id2+"",true);
xmlhttp.send();
}
I am assuming you are talking about this alert.
alert("ajax value: "+xmlhttp.responseText - 0);
Order of operations here says
Add "ajax value: " and xmlhttp.responseText
Take result of 1 and subtract zero [aka "stringNumber" - 0 = NaN]
You need to change the order of operations so it is
alert("ajax value: " + (xmlhttp.responseText - 0) );
But it really makes no difference in your alert if it is a string or a number since the alert displays strings.
You can also use parseInt or parseFloat for converting numbers which some people might like to read instead of -0.

Javascript - object properties not transferring

I am pretty new to Javascript and cannot for my life figure out why the following object properties are not transferring.
I am calling the object as follows:
var URL = "TABLE=_Products&COLUMNS=price_Qty,Sale&MATCH=internal_Model&ROWS="+itemnum ;
var ITEM = new get_Database_Info(URL) ;
and the get_Database_Info is:
function get_Database_Info(PARAMS) {
alert(toString(this));
var URL = document.location.protocol+'//'+document.location.host+'/Catalog/Tools/ajax_Database_Request.php' ;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlhttp){alert('Error: Cannot send XML request.');}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(toString(this));
var RESPONSE = xmlhttp.responseText ;
RESPONSE = RESPONSE.replace(/^\s+/, '');
var ARR = RESPONSE.split('||') ;
ARR.pop() ;
for(var i=0; i<ARR.length; i++){
var temparr1 = ARR[i].split('=') ;
var NUM = temparr1[0] ;
this[NUM] = new Array() ;
var temparr2 = temparr1[1].split('/|') ;
temparr2.shift() ;
for(var x=0; x<temparr2.length; x++){
var temparr3 = temparr2[x].split('??') ;
this[NUM][temparr3[0]] = temparr3[1] ;
}
}
}
}
xmlhttp.open("POST", URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", PARAMS.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(PARAMS);
}
I have verified that all the properties are in 'this' within the scope of get_Database_Info but they are not transferring back to ITEM.
When are you checking the contents of the object? The request is asynchronous, so you have to wait until the callback has processed the response before there are any properties in the object.
If you look for the properties immediately after the object is created, they will never be there. Even if the response is really quick, the first time that the callback can run is when you exit the function where you created the object, so the browser gets the control back.
I would venture to guess that the when the function that is attached to onreadystatechange runs that this is no longer attached to the object that is being created in the constructor but is probably attached to the global object or the xmlhttp object. I would try using the var that=this pattern:
function get_Database_Info(PARAMS) {
alert(toString(this));
var URL = document.location.protocol+'//'+document.location.host+'/Catalog/Tools/ajax_Database_Request.php' ;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var that=this; // value of that will be stored in the closure
if(!xmlhttp){alert('Error: Cannot send XML request.');}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(toString(that));
var RESPONSE = xmlhttp.responseText ;
RESPONSE = RESPONSE.replace(/^\s+/, '');
var ARR = RESPONSE.split('||') ;
ARR.pop();
var arrLength = ARR.length; // always precompute array length
for(var i=0; i<ARR.length; i++){
var temparr1 = ARR[i].split('=') ;
var NUM = temparr1[0] ;
// that is actually equal to the object that I created
// in the constructor.
that[NUM] = new Array() ;
var temparr2 = temparr1[1].split('/|') ;
temparr2.shift() ;
var arrayLength = temparr2.length; // always precompute length
for(var x=0; x<arrayLength; x++){
var temparr3 = temparr2[x].split('??') ;
that[NUM][temparr3[0]] = temparr3[1] ;
}
}
}
}
xmlhttp.open("POST", URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", PARAMS.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(PARAMS);
Also, as noted in the comments, when you are iterating over the values in an array for a for loop, you should not use array.length directly, as the length method will be called every time through the loop, adding a great deal of unnecessary work.
Also, as #Guffa notes, the function that adds the values is called asynchronously, so the properties will not exist until the XmlHttpRequest has completed, and that is a very dangerous anti-pattern. I would strongly advise against it. It's better to have your constructor make a synchronous request for the data.

Categories