phpknight Posted January 9, 2009 Share Posted January 9, 2009 Hi, I am finally getting used to writing AJAX in combination with PHP, but most of the sample scripts dealing with multiple requests simply use two objects. What I am looking for is to use a multi-purpose AJAX script that I could use with a potentially infinite number of objects since most of my scripts rely heavily on databases. If anybody can point me on the way, that would be great. BTW, I don't want to use a library since I have been unable to even get one of the libraries to have all their test scripts even work on both IE and Firefox. Even the best ones seem to break. That being said, I'm open to suggestions Quote Link to comment Share on other sites More sharing options...
corbin Posted January 9, 2009 Share Posted January 9, 2009 I've never had jQuery break between FF and IE.... But errrr.... I don't get what the problem is. This seems pretty easy if you already know how to use JS/AJAX. What's wrong with having more than 2 objects? The only way to use AJAX is through objects (as far as I know) since that's how it's implemented in JS (APIs pretty much). How would you have more than 2 objects without having more than 2 objects? Also, if you don't like any of the libraries, you could always write your own AJAX class. Quote Link to comment Share on other sites More sharing options...
phpknight Posted January 9, 2009 Author Share Posted January 9, 2009 I tried scriptaculous, and their examples did not work. I've never used jQuery. I primarily use PHP/mySQL. For AJAX, I learned most from this book: http://www.amazon.com/AJAX-PHP-Building-Responsive-Applications/dp/1904811825/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1231542429&sr=8-1. But it only has one object that use used for the whole JS script. The examples I found online only discuss two objects, and that just delays but doesn't solve the potential problems. However, if it is so easy, if you could just point me in the right direction, I would appreciate it. Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 Are you are asking how to instantiate more than 1-2 XMLHttpRequestObjects at a time? <script type="text/javascript"> function newXHRO() { try { return new XMLHttpRequest(); } catch(e) {} try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} alert("XMLHttpRequest not supported"); return null; } </script> <script type="text/javascript"> function someAjaxFunc() { var XHRO = new newXHRO(); XHRO.onreadystatechange=function() { if(XHRO.readyState==4 && XHRO.status==200) { //or you could change this anonymous function //to callback to some other function } } XHRO.open("GET",url,true); XHRO.send(null); return false; } </script> It returns a new XMLHttpRequestObject each time, and multiple functions can get their own new Objects as well. Or have I misunderstood? Quote Link to comment Share on other sites More sharing options...
phpknight Posted January 10, 2009 Author Share Posted January 10, 2009 I think that might be right. In my current script, it has this before any functions: var xmlHttp = createXmlHttpRequestObject(); //this function does what you suggest So, if what you are saying is correct, then all I really have to do is somehow create the object inside a function, and then I will be able to use all the objects I want? But how will the server response, state change function, and processing functions not cancel each other out or otherwise mess up? Right now, if two different Ajax calls go out, one cancels the other. So, I just don't do anything until the first one finishes, but I know this defeats the purpose of using Ajax. Right now, in order to keep things separate, I send Ajax IDs with each call. So, a drag and drop might send 1 whereas a click on a list element would send 2, etc. That way, I use a switch to process it and process the server response correctly. This helps me use it but does not help with mutliple calls at once. Is this the right idea, or am I going about this part wrong? Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 This isn't my strong point, but I think if you setup your ajax function to be generic, such as a target url, method type(post/get) , params, and callback function as argument you can handle it differently. So if you have things that say update the innerHTML of something on their action as well as GET to the server, you could send them all through the main ajax function and have different call back functions, or the same function with different targets (<div id="updateMe"> vs <div id="amount">) kinda thing. Does that make any sense? I had a book about it, but I don't know where it is atm... Quote Link to comment Share on other sites More sharing options...
corbin Posted January 10, 2009 Share Posted January 10, 2009 Hrmmmmmm.... I'll have to test this later to be sure, but this is how I would imagine it would work: The var containing the AJAX object would be created inside of the function scope, and it would be destroyed on leaving the function scope. That would mean that the request may finish, but would the callback still be bound? By design, I would guess no, but chances are, most browsers probably handle this correctly. I shall test it tomorrow. Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 [note to self: pg 227] I just looked in my Pro JS Techniques book (by John Resig) and the way he does it is to have the ajax function (object) take an onSuccess property which usually holds a function (in the same way you'd define an anonymous function) You can download the source code here of his examples: http://jspro.org/code/ Note: He has many errors throughout which will make your head spin, but the examples that work are pretty good. excerpt: Note Not all functions used in this excerpt have been included <script type="text/javascript"> function ajax( options ) { options = { type: options.type || "POST", url: options.url || "", timeout: options.timeout || 5000, onComplete: options.onComplete || function(){}, onError: options.onError || function(){} onSuccess: options.onSuccess || function(){}, options.data || "" };//options var xml = new XMLHttpRequest(); //open the ajax request xml.open(options.type, options.url, true); var timeoutLength = options.timeout; //keep track of when the request has been successful var requestDone = false; //intialize the cancel callback setTimeout( function(){requestDone = true;}, timeoutLength ); //readystate stuff xml.onreadystatechange = function(){ if( xml.readyState == 4 && !requestDone ){ options.onSuccess( httpData( xml, options.type ) ); }else{ options.onError(); } //call a function after completion options.onComplete(); //unset the xml obj xml = null; }; xml.send(); }//ajax </script> Sample implementation: <html> <head> <title>Some Title</title> <!-- require that ajax function from above here --> <script type="text/javascript"> window.onload = function(){ ajax({ url: "scores.html", type: "GET", onSuccess: function( html ){ var scores = document.getElementById("scores"); scores.innerHTML = html; } });//ajax }//onload </script> </head> <body> <h1>Title</h1> <div id="scores"></div> </body> </html> After looking through this, the example and function might not work together because I don't think I grabbed all dependencies when copying it from the book to here. However it should give you an idea of a possible solution; if it makes any sense lol. Quote Link to comment Share on other sites More sharing options...
RichardRotterdam Posted January 10, 2009 Share Posted January 10, 2009 What I am looking for is to use a multi-purpose AJAX script that I could use with a potentially infinite number of objects since most of my scripts rely heavily on databases. Maybe instead of sending multiple ajax requests you could do a single request to one php file that sends structured json or a xml. that way you would put less stress on the server. And since you are using php, php 5.1 (not sure which version) has a function called json_encode() to make things a whole lot easier. BTW, I don't want to use a library since I have been unable to even get one of the libraries to have all their test scripts even work on both IE and Firefox. Even the best ones seem to break. Javascript frameworks have ajax functionality to work with the most major browsers not work against it. If something doesn't work on all the browsers it usually isn't the framework to be blamed but rather the script that is written by the developer. Quote Link to comment Share on other sites More sharing options...
RichardRotterdam Posted January 10, 2009 Share Posted January 10, 2009 What I am looking for is to use a multi-purpose AJAX script that I could use with a potentially infinite number of objects since most of my scripts rely heavily on databases. Maybe instead of sending multiple ajax requests you could do a single request to one php file that sends structured json or a xml. that way you would put less stress on the server. And since you are using php, php (not sure which version I think it's 5+) has a function called json_encode() to make things a whole lot easier. BTW, I don't want to use a library since I have been unable to even get one of the libraries to have all their test scripts even work on both IE and Firefox. Even the best ones seem to break. Javascript frameworks have ajax functionality to work with the most major browsers not work against it. If something doesn't work on all the browsers it usually isn't the framework to be blamed but rather the script that is written by the developer. Quote Link to comment Share on other sites More sharing options...
corbin Posted January 10, 2009 Share Posted January 10, 2009 Hrmmmmmm.... I'll have to test this later to be sure, but this is how I would imagine it would work: The var containing the AJAX object would be created inside of the function scope, and it would be destroyed on leaving the function scope. That would mean that the request may finish, but would the callback still be bound? By design, I would guess no, but chances are, most browsers probably handle this correctly. I shall test it tomorrow. My last guess was right. Although I personally think it's a weird design, it's how things work. Apparently AJAX object variables continue to live even after the function scope is left. Quote Link to comment Share on other sites More sharing options...
phpknight Posted January 10, 2009 Author Share Posted January 10, 2009 Can you give me some example code there? I tried implementing this, and the statechange function does not see/recognize the Ajax object. I might be missing something. Quote Link to comment Share on other sites More sharing options...
xtopolis Posted January 10, 2009 Share Posted January 10, 2009 What does your Error Console say? Post the code you have if you can't debug off the console. Quote Link to comment Share on other sites More sharing options...
phpknight Posted January 10, 2009 Author Share Posted January 10, 2009 xmlHttp is undefined It is saying that right away in the handleRequestStateChange function. Quote Link to comment Share on other sites More sharing options...
corbin Posted January 10, 2009 Share Posted January 10, 2009 Can we see your code? Or, if you're using something already posted on here, can you tell me which snippet. Quote Link to comment Share on other sites More sharing options...
phpknight Posted January 10, 2009 Author Share Posted January 10, 2009 Okay, I've never actually posted code, so hopefully I did this right. Bolding inside there wasn't working, so I have marked the two important lines with ************** above and below. // creates an XMLHttpRequest instance function createXmlHttpRequestObject() { // will store the reference to the XMLHttpRequest object var xmlHttp; // this should work for all browsers except IE6 and older try { // try to create XMLHttpRequest object xmlHttp = new XMLHttpRequest(); } catch(e) { // assume IE6 or older var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"); // try every prog id until one works for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) { try { // try to create XMLHttpRequest object xmlHttp = new ActiveXObject(XmlHttpVersions[i]); } catch (e) {} } } // return the created object or display an error message if (!xmlHttp) alert("Error creating the XMLHttpRequest object."); else return xmlHttp; } // read a file from the server function handleEvent(x, y, a, b) { **************************** var xmlHttp = createXmlHttpRequestObject(); normally this line is outside all functions ***************************** if (xmlHttp && xmlHttp.readyState!=1 && xmlHttp.readyState !=2 && xmlHttp.readyState!=3) { // try to connect to the server try { // get the two values entered by the user //FORMAT REQUEST HERE xmlHttp.open("GET", "THE URL" + params, true); xmlHttp.onreadystatechange = function () {handleRequestStateChange(x, y);}; xmlHttp.send(null); break; } } // display the error in case of failure catch (e) { alert("Can't connect to server:\n"+xmlHttp.readyState + e.toString()); } } else { alert ("Hold on a minute. I'm not finished!"+xmlHttp.readyState); } } function handleRequestStateChange(x, y) { switch (ajaxID) { case 1: // when readyState is 4, we are ready to read the server response **************************** //as soon as xmlHttp is referred to, the program halts because it does not recognize it since it is now inside the function if (xmlHttp.readyState == 4) ... *************************** } Quote Link to comment Share on other sites More sharing options...
corbin Posted January 11, 2009 Share Posted January 11, 2009 Ah.... I've explained why this happens in like 4 threads. Gotta search now. http://www.phpfreaks.com/forums/index.php/topic,209190.0.html That thread pretty much sums it up, but I doubt you want to read it all, so I'll reexplain the important parts ;p. There are two ways I like to pass around the AJAX object. xmlObject.onreadystatechange = someFunction; And then in someFunction: function someFunction() { alert(this.responseText); } The function assigned to onreadystatechanged is executed from inside of the scope of the instace to which you assign it. So, it can use the "this" magic-variable to access all of the instance's stuff. Another way, is to pass it along. xmlRequest.onreadystatechange = function() { someFunction(this); } function someFunction(aobj) { alert(aobj.responseText); } In most situations, I prefer the first way. Sometimes I use the second way and check for the readyState in the anonymous function though. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.