SitePoint Sponsor

User Tag List

Results 1 to 21 of 21
  1. #1
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Cant get AJAX response

    Hi all,

    I'm starting to go in circles attempting to get a simply AJAX request to work Ideally i am trying to encapsulate my AJAX calls within a class, but I was running into what I assumed to be variable scoping problems, so I have tried strinping the request out of the class but seem to be having the same problems.

    Code:
    function createRequest() {
            try {
                    request = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            request = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    request = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    request = null;
                            }
                    }
            }
            if (request == null)
            alert ("Error creating request object");
    
    }
    
    
    
    function submitComments() {
            var querystring = "n=foo";
            createRequest();
    
            request.onreadystatechange = function() {alert(request.status);}
    
            request.open("POST", './includes/server_form_handlers/add_client_ajax.php', true);
    
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", querystring.length);
            request.setRequestHeader("Connection", "close");
    
    
            request.send(querystring);
    
    }
    The above code is just to test the call, once I got that working (and understood) then I was going to return to trying to encapsulate it within a class.

    For some reason the above code however generates errors (of undescript nature in firefox (4 of them, 1 for each time the callback is made)) and will not launch a pop up with the status.

    Any help, ideas would be greatly greatly appreciated

    Many thanks indeed

    /Matt

  2. #2
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One issue I can see right away is where you're declaring your vars - if at all.

    If you're going to use "request" as your XHR object, declare it outside of your function to make it globally available.

    If the submitComments function is the only one that will use the XHR object, consider declaring a variable local to it and have your "createRequest" function simply return the XHR object to be used.

    Another suggestion: it's Msxml2.XMLHTTP not Msxm12.XMLHTTP

  3. #3
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi jtrelfa,

    Thanks very much for your reply, I have implemented these (thanks very much) but am still receiving the same errors.

    If I change the anonomous function to alert out the response.readyState it will output the correct sequence and make it to 4, however it is still giving me the same errors when trying to output the the status, and just blank when outputing the responseText (even though there is a response text).

    I'm really confused as to why this is happening so any advce would be greatly appreciated!!

    Code:
    request = null;
    
    function createRequest() {
            try {
                    request = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            request = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    request = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    request = null;
                            }
                    }
            }
            if (request == null)
            alert ("Error creating request object");
    
    }
    
    
    
    function submitComments() {
            var querystring = "n=foo";
            createRequest();
    
            request.onreadystatechange = function() {alert(request.status);}
    
            request.open("POST", './includes/server_form_handlers/add_client_ajax.php', true);
    
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", querystring.length);
            request.setRequestHeader("Connection", "close");
    
    
            request.send(querystring);
    
    }

  4. #4
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm not 100% sure about this, but here are a few things...

    1. I don't think you should try to access 'status' until readyState is 4.

    2. Try putting the "request.onreadystatechange = function()" after the "request.open()" line.

    3. Also, you're not setting the Method header:

    request.setRequestHeader('Method', 'POST ' + url + ' HTTP/1.1');

  5. #5
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Mike,

    Thanks very much for your reply, I played with this a little more, but am going to really sink my teeth into it tonight, I have however got the following code working ok now;

    Code:
    function createRequest() {
            try {
                    request = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            request = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    request = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    request = null;
                            }
                    }
            }
            if (request == null)
            alert ("Error creating request object");
    
    }
    
    
    function submitComments() {
           // var request = null;
    
            params = "n=name";
    
            createRequest();
            request.open("POST", './includes/server_form_handlers/add_client_ajax.php', true);
            request.onreadystatechange = function() {alert(request.status)};
    
            request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            request.setRequestHeader("Content-length", params.length);
            request.setRequestHeader("Connection", "close");
    
            request.send(params);
            return false;
    }
    So Im now going to try and include it back into an existing class to encapsulate it encapsulate, hopefully this run will go a little smoother.

    I will let you know how i get on . .

    Thanks a lot for the help

    /Matt

  6. #6
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


    Good work!

  7. #7
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Well, I played with this a little bit more last nite, but unfortunately cant seem to get the hang of encapsulating the request within a class.

    Im almost positive it has to do with variable scoping, but i cant for the life of me get my head around it . .so once again. . . any help with be masively appreciated!

    I currently have the class below to hold and create an XHR

    Code:
    function sendRequest(url, data) {
            this._request = undefined;
            this._url = url;
            this._params = data;
            var _this = this;
    
            this.loader = function() {
                    this._request = _this.createRequest();
    
                    this._request.open("POST", './includes/server_form_handlers/add_client_ajax.php', true);
                    this._request.onreadystatechange = function(){_this._handler()};
                    this._request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            this._request.setRequestHeader("Content-length", _this._params.length);
            this._request.setRequestHeader("Connection", "close");
    
                    this._request.send(this._params);
            }
    
            this.handler = function() {
                    alert(this._request.readyState)
                    alert(this._request.responseText);
            }
    
            this.createRequest = function() {
    
                    var xmlHttp;
                    try
                    {
                            xmlHttp = new ActiveXObject("Msxml2.XMLHttp");
                    }
                    catch(e)
                    {
                            try
                            {
                                    xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
                            }
                            catch(e2)
                            {
                            }
                    }
    
                    if(xmlHttp == undefined && (typeof XMLHttpRequest != 'undefined'))
                    {
                            xmlHttp = new XMLHttpRequest();
                    }
    
                    return xmlHttp;
            }
    
    
    }
    Many many thanks

    /Matt

  8. #8
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Matt,

    Some ideas/suggestions/questions...

    1. Show us the code that uses the sendRequest object.

    2. The method named "handler" is called as "_handler".

    3. Since you pass the data to the constructor, this object is only good for one request, unless you want to send the same data again. Perhaps accept the data as an arg to the loader method.

    4. Your object creates a new XMLHttpRequest object for every request. An alternative is to keep a reference to only one XMLHttpRequest object - then don't allow another request while one is busy, or serialize requests.

    5. You have:

    this._request.onreadystatechange = function(){_this._handler()};

    An alternative is:

    this._request.onreadystatechange = _handler;

    and now _handler should be private:

    function _handler() {
    // must use "_this" here
    }

    6. Think about how you are going to use your object in different types of applications. This will give you ideas about how to design the object - what services it should provide. Look at other people's implementations and get ideas from them. Here is one of mine: xHttpRequest. Also look at the XHR implementations in the Prototype library and other popular libs.

  9. #9
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Mike,

    Once again thanks very much for your feedback.

    Ive been trynig with this a little more thismorning but am getting some really strange results. The following code will now work fine in IE, but not firefox!!

    Code:
    function sendRequest(url, data) {
    	
    	alert('called');
    	this._request = undefined;
    	this._url = url;
    	this._params = data;
    	var _this = this;
    	
    	this.loader = function() {
    		alert(params);
    		_this._request = _this._createRequest();
    		
    		_this._request.open("POST", 'includes/add_client_ajax.php', true);
    		_this._request.onreadystatechange = _this._handler;
    		_this._request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            _this._request.setRequestHeader("Content-length", _this._params.length);
            _this._request.setRequestHeader("Connection", "close");
    		
    		_this._request.send(_this._params);
    	}
    	
    	this._handler = function() {
    		alert(_this._request.readyState)		
    		alert(_this._request.responseText);
    	}
    	
    	this._createRequest = function() {
    
    		var xmlHttp;
    		try
    		{
    			xmlHttp = new ActiveXObject("Msxml2.XMLHttp");
    		}
    		catch(e)
    		{
    			try
    			{
    				xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
    			}
    			catch(e2)
    			{
    			}
    		}
    		
    		if(xmlHttp == undefined && (typeof XMLHttpRequest != 'undefined'))
    		{
    			xmlHttp = new XMLHttpRequest();
    		}
    		
    		return xmlHttp;
    	}
    	
    	
    }
    For some reason in FF it just wont send the data! (which is now really starting to break my resolve

    The ove function is called from within a function which resides within a 'formHandler' class i have written. The function within formHandler is attatched to the forms onSubmit handler and after validating the fields it creates a new sendRequest object. then calls the loader function.

    Once again thanks for all your help so far and any more is massively appreciated!!

    /Matt

    p.s. the error im getting in firefox when i try to read the request.status is;

    Code:
    Error: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: http://server1/~matthew/nrcc/includes/utility.js :: anonymous :: line 168"  data: no]
    Source File: http://server1/~matthew/nrcc/includes/utility.js
    Line: 168

  10. #10
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't see that you've utilized any of my tips except for #2 and only half of #5. You are using "_this" in "loader" when it is not needed. Have a look at this page and pay attention to the comments in the code to help understand what we mean by "private" properties and methods and what this means for the "this" keyword.

    Re-inventing wheels for the sake of learning is a good thing - I do it all the time. But it's a waste of time if you don't utilize your resources. Use a search engine and find lots of different implementations (there are hundreds of them out there). Study what they did and ask questions about "why" they did it. Load them into a test page and try them out - then come up with your own.

  11. #11
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Mike,

    Thanks for replying. Apologies for not posting up the code that is using the above, totally missed that, and as it turns out i think that that may be the crucial part.

    Ive looked at many examples on the web, and have even disected parts, but as soon as I then start to piece them into my application that is where I am coming unstuck, I have even had a really close look at yours, which looks like a fantastic solution, but as you put it, im much more of a fan of writing something for myself to achieve a greater understanding of it . .

    From examining various implementation am I correct in thinking that the difference between ;

    1) var _n = "test";
    2) this.n = "test";

    is that 1) is a private variable (i.e. scope within the class/function (object)) only and 2) has public scope?

    In reference to the re-usability of your script, i.e. hold a reference to the XHR object and re-use it by passing the data to the send function, that is definitely what I am wanting to do, but i'm really keen on understanding exactly where I'm going wrong at such an early stage, with the base functionality there I can then look at expanding the class/script to encompass your recommendations (as you have in your class)

    After further disecting my code i now know the circumstance under which FF fails, I just dont understand why it is happening;

    The XHR class remains as (A very bare bones one at the moment - i'm literally just trying to get it working);

    Code:
    function testClass() {
    	
    	this.send = function() {
    		var request = null;
    			alert('d');
    		params = "n=name";        
    	
    		request = createRequest();
    		request.open("post", 'includes/server_form_handlers/add_client_ajax.php', true);
    		request.onreadystatechange = giveFeedback;
    	
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.setRequestHeader("Content-length", params.length);
    		request.setRequestHeader("Connection", "close");
    	
    		request.send(params);
    		return false;
    	}
    
    	createRequest = function() {
            try {
                    request = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            request = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    request = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    request = null;
                            }
                    }
            }
            if (request == null)
            alert ("Error creating request object");
     	return request;
    	}
    
    
    	giveFeedback = function(){   
    	 if (request.readyState == 4) {
    			alert(request.status)
    				alert(request.responseText);         
    	}
    
    }
    
    }
    The above code will work fine in IE and FF when called from within a normall code script - for instance;

    Code:
    window.onload = init;
    function init() {
        
    	var ins1 = new testClass();
    	$('create_client').onsubmit = ins1.send;
    
    }
    However where the ailure is then introduced is by trying to instantiate the testClass() from within another object (which is what I am trying to do) - for instance;

    Code:
    window.onload = init;
    function init() {
    	
    	var ins1 = new holder();
    	$('create_client').onsubmit = ins1.init;
    
    }
    which is creating;

    Code:
    function holder() {
    	
     this.n = new testClass();
     var _t = this;
     
     this.init = function() {
    	//var ins = new testClass();
    	_t.n.send();
     }
    
    }
    Which then trys to create an 'internal' XHR request (testClass)

    So for some reason (which im playing with at the moment) i just cant get ff to work when the XHR object is created within my holder function . .

    Many thanks for your ongoing help Mike, I shall continue with my perseverence on this, if for no other reason now than the sense of relief when i finally DO figure out where i'm going wrong . . .ofcourse by then they'll probably be composing my epitaph!!

    Thanks again

    /Matt
    Last edited by mwells; Feb 18, 2007 at 09:53. Reason: my awfull grammer!

  12. #12
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No apologies needed. I provide support to many different people so my replies are usually made very quickly - but sometimes that makes them sound a little harsh. I certainly don't mean for it to be that way. In fact, there's nothing I enjoy more than working with someone like yourself who is serious about learning. I really do appreciate that. I myself still have much, much to learn - but I enjoy it

    I'm looking over your excellent post. It really shows how you've been researching/experimenting/learning. I'll be away from home for the rest of the day but hopefully I can return to this thread tonight.

    Have a great day!

  13. #13
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    From examining various implementation am I correct in thinking that the difference between ;

    1) var _n = "test";
    2) this.n = "test";

    is that 1) is a private variable (i.e. scope within the class/function (object)) only and 2) has public scope?
    Yes, and, in testClass, send is a public method and both createRequest and giveFeedback are private methods.

    Within a public method, 'this' refers to the instance object. I like to use private methods for event listeners, where 'this' refers to the event target.

    Code in any nested function of testClass has access to all parameters and private properties of testClass. If a nested function will be called at some later time (an event listener), and it refers to a private prop, then that creates a closure.

    Now, about this statement:

    $('create_client').onsubmit = ins1.send;

    'send' will be called, however 'this' will not equal 'ins1'. The statement above assigns a reference to the function 'send' to the onsubmit property of an element. Note how it will be called (when submit occurs):

    element.onsubmit();

    so in the onsubmit code 'this' refers to 'element' and not 'ins1'. It "appears" that your first code snippet works properly because your 'send' method does not refer to 'this'. Your second code snippet has a similar hidden problem and may be why FF is having a problem with it.

    One way around the above is:

    $('create_client').onsubmit = function() { ins1.send(); };

    This can be very useful, but IMO when people find themselves doing this alot it is indicating a design flaw.
    Last edited by MikeFoster; Feb 19, 2007 at 18:25. Reason: fixed typo in last expression

  14. #14
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    HI Mike,

    Thanks very much for your reply again, I'm at work at the moment but will look into using the anonomous function tonight.

    After playing a little more with it last night I have got to the point where i have combined my formHandler and XHR classes, so that the XHR functions are now within the main class.

    The main (and now only) class contains the init function, which adds various even listeners etc and I had it working so that when i added this.form.onsubmit = send; a request was generated and I could access the status etc.

    However if I then generated (and attatched as the this.form.onsubmit = ..) another function 'submitter' which was basically;

    Code:
    submitter = function() {
      if(validate()) {
         send();
     }
    }
    The same problems arose again.

    So i seem to be able to call the send function directly on the even handler, but not from within another function which is attatched as the handler . . so possibly your suggestions above will help on that front . .fingers crossed ey!!

    Anyhow, I shall have a look again thisevening and will post up my results!! . .i have the inclination that I'm possibly getting closer now, and I have definitely gained quite some understanding of OO design/implementation within JS (your post above was really helpfull in clearing a lot of stuff up - thanks for that)

    Id just like to say thanks again for your continued patience/help on this, im pretty sure by now, without it, I would have given up and headed for another solution . .even if i never get this working i have learned a massive amount, so i certainly dont look at is as a wasted effort!

    /Matt

  15. #15
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi,

    Right!! . .I now know exactly where the problem lies . .the only issue i now is that i have no idea why it is that way!

    If i have the following;

    Code:
    function formHandle(form, url, handler)
    {
    	
    	// ----------------
    	// PRIVATE VARS
    	// ----------------
    	var instance = this;	
    	var request = null;
    	
    	
    	// ----------------
    	// PUBLIC VARS
    	// ----------------
    	this.form = form;
    	this.url = url;
    	this.handler = handler;
    	
    
    	// ---------------
    	// PUBLIC METHODS
    	// ---------------
    
           /*
    	* Function to initialise the form
    	*/
    	this.init = function() {
    			
    		//Add the highlightors
    		this.addHighlightor(this.form.getElementsByTagName("input"));
    		this.addHighlightor(this.form.getElementsByTagName("select"));
    		this.addHighlightor(this.form.getElementsByTagName("textarea"));
    		
    		//Give focus to the form
    		Form.focusFirstElement(this.form);
    		
    		request = createRequest();
    		
    		form.onsubmit = send;
    				
    	}
    
    	var send = function() {
    		var params = "me=you";
    	
    	
    		//request = createRequest();
    		request.open("post", 'includes/server_form_handlers/add_client_ajax.php', true);
    		//request.onreadystatechange = giveFeedback;
    		request.onreadystatechange = function() {alert(request.responseText)};
    	
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.setRequestHeader("Content-length", params.length);
    		request.setRequestHeader("Connection", "close");
    	
    		request.send(params);
    		return false;
    	}
    
    	var createRequest = function() {
            var xhr;
    		try {
                    xhr = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            xhr = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    xhr = null;
                            }
                    }
            }
            if (xhr == null)
            alert ("Error creating request object");
     		return xhr;
    	}
    
    
    	var giveFeedback = function(){   
    		if (instance.request.readyState == 4) {
    			alert(instance.request.status)
    				alert(instance.request.responseText);         
    		}	
    	}
    	
    }
    that will work fine!

    However if i dont directly attach the request sending method to the onsubmit event it fails!! and i have no idea why! (it only fails in IE)

    Code:
    function formHandle(form, url, handler)
    {
    	
    	// ----------------
    	// PRIVATE VARS
    	// ----------------
    	var instance = this;	
    	var request = null;
    	
    	
    	// ----------------
    	// PUBLIC VARS
    	// ----------------
    	this.form = form;
    	this.url = url;
    	this.handler = handler;
    	
    
    	// ---------------
    	// PUBLIC METHODS
    	// ---------------
    
           /*
    	* Function to initialise the form
    	*/
    	this.init = function() {
    			
    		//Add the highlightors
    		this.addHighlightor(this.form.getElementsByTagName("input"));
    		this.addHighlightor(this.form.getElementsByTagName("select"));
    		this.addHighlightor(this.form.getElementsByTagName("textarea"));
    		
    		//Give focus to the form
    		Form.focusFirstElement(this.form);
    		
    		request = createRequest();
    		
    		form.onsubmit = submitter;
    				
    	}
    
    /*
     * Test method
    */
    	function submitter() {
    		if (validate()) {
    		       send();    //send() wont work when called from here!!!!	
    		} else {
    			return false;
    		}
    	}
    
    	var send = function() {
    		var params = "me=you";
    	
    	
    		//request = createRequest();
    		request.open("post", 'includes/server_form_handlers/add_client_ajax.php', true);
    		//request.onreadystatechange = giveFeedback;
    		request.onreadystatechange = function() {alert(request.responseText)};
    	
    		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		request.setRequestHeader("Content-length", params.length);
    		request.setRequestHeader("Connection", "close");
    	
    		request.send(params);
    		return false;
    	}
    
    	var createRequest = function() {
            var xhr;
    		try {
                    xhr = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            xhr = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    xhr = null;
                            }
                    }
            }
            if (xhr == null)
            alert ("Error creating request object");
     		return xhr;
    	}
    
    
    	var giveFeedback = function(){   
    		if (instance.request.readyState == 4) {
    			alert(instance.request.status)
    				alert(instance.request.responseText);         
    		}	
    	}
    	
    }
    I just have no worldly clue as to why send will only work when directly attatched to the onsubmit handler and not when called from within another function?

    I also tried the anonomous function on the onsubmit but with the same results

    I can now get by this by including all the code in the send method within the body of the submitter code, i can ork with that at the moment but i'd be really keen/interested to know why its not working . .

    Many thanks

    /Matt

  16. #16
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the only issue i now is that i have no idea why it is that way!
    One method for trying to understand a problem is to extract it out of your code, which serves to isolate the problem so that you can study it.

    The following works fine in IE6, FF1.0.7, Safari 2.0.4:
    Code:
    window.onload = function()
    {
    	var o = new myObj();
    	o.init();
    }
    
    function myObj()
    {
    	this.init = function()
    	{
    		document.forms[0].onsubmit = greetingWrapper;
    	}
    	
    	function greetingWrapper()
    	{
    		greeting();
    		return false;
    	}
    	
    	var greeting = function()
    	{
    		alert("Hello world");
    	}
    }
    Code:
    <body>
    <form method="post" action="http://www.google.com">
    
    <input type="submit" value="Submit" />
    </form>
    By the way, your two versions aren't consistent with each other. You call an undefined function in your second version, which won't allow send() to execute in any browser:
    Code:
    function submitter() {
    		if (validate()) {
    		       send();    //send() wont work when called from here!!!!	
    		} else {
    			return false;
    		}
    	}
    Last edited by 7stud; Feb 19, 2007 at 18:21.

  17. #17
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    7stud is right. You're making it more complex before you get your previous problems fixed.

  18. #18
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi 7Stud, many many thanks for your post.

    I'm at work now but will look at stripping this right back down tonight though.

    Just as a side note the validate() function is actually defined in my class, ive just tested it enough to (think) that its ok, apologieds if i'd of been better just including it!

    Many thanks to you both, i'll post back tonight!

    /Matt

  19. #19
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Right,

    back to basics!

    The following code wont work for me in firefox, it does however work in IE and Opera.

    Code:
    function formHandle(form, url)
    
    {
    
    	var _i = this;	
    	var url = url;
    
    	this.form = form;
    	this.id = form.id;
    
    	this.request = null;
    
           /*
    	* Function to initialise the form
    	*/
    	this.init = function() {
    		this.request = createRequest();
    		form.onsubmit = sendWrap;
    	}
    
            var sendWrap = function() {
                 send();
            }
    
    	var send = function() {
    		var params = "me=you";
    		_i.request.open("post", 'includes/server_form_handlers/add_client_ajax.php', true);
    		_i.request.onreadystatechange = function() {alert(_i.request.responseText)};
    		_i.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    		_i.request.setRequestHeader("Content-length", params.length);
    		_i.request.setRequestHeader("Connection", "close");
    		_i.request.send(params);
    		return false;
    	}
    
    
    	/*
    	* Function to return an XHR object
    	*/
    	var createRequest = function() {
    
            var xhr;
    		try {
                    xhr = new XMLHttpRequest();
            } catch (trymicrosoft) {
                    try {
                            xhr = new ActiveXObject("Msxm12.XMLHTTP");
                    } catch (othermicrosoft) {
                            try {
                                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (failed) {
                                    xhr = null;
                            }
                    }
            }
            if (xhr == null)
            alert ("Error creating request object");
    
    	return xhr;
    	}
    
    }
    If however I change the onsubmit to say 'send' (i.e. point it directly at the send function) then it will work without and problem (in all three browsers)

    Does anyone have any idea as to why this may be?

    Many thanks indeed

    /Matt

  20. #20
    I'll take mine raw silver trophy MikeFoster's Avatar
    Join Date
    Dec 2002
    Location
    Alabama, USA
    Posts
    2,560
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tested your code and the only thing I had to do to get it to work was to return false from sendWrap.

  21. #21
    SitePoint Member
    Join Date
    Feb 2007
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Mike,

    Thanks very much for that (vital) little tip. With that addition the code is now working. .sorry it took me a little while to respond, after the saga it has turned into it was quite an emotional moment when it started working!!

    So the next job is to start adding in my extra functionality, and somehow devise a way to allow me to pass a funtion to the class which will act as the onreadystatechange function . .

    As i said before, many many thanks for all your perseverance/help on this, i would of given up a long time ago, but instead have learned a bunch about OO programming in JS.

    All the best

    /Matt


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •