Jump to content

Multiple AJAX requests (on the fly--more than 2)


phpknight

Recommended Posts

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

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

 

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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?

 

 

 

Link to comment
Share on other sites

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...

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

[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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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) ...
***************************
         }

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.