Page 3 of 4 FirstFirst 1234 LastLast
Results 21 to 30 of 33

Thread: Calling Functions from Functions.

  1. #21
    Join Date
    Jul 2008
    Posts
    65
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    John,

    I did not want to reply having not tested it thoroughly. I now have.

    Your suggested fix (as usual) worked.

    I am finding the uses of this endless.

    I wanted to create a paginated news page. A combination of PHP, and this has made it possible.

    I have two pages.

    news.php which contains a div called' NewsDiv
    getnews.php which uses PHP to fetch all the news.

    With some simple onclicks, getnews.php gets the news and puts it in the div on news.php



    Prior to this conversation/chat, the pagination system I was using was one off dynamicdrive in fact: http://www.dynamicdrive.com/dynamici...nate/index.htm


    It was extremely complicated, really hard to integrate with PHP etc etc.

    I was just curious as to the downsides of pretty much basing my website around your function. Is it really slow, or inefficient or something. Surely there must be a negative?

    Thanks

  2. #22
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    The real negative with this and any other javascript is that if the user doesn't have javascript enabled, your site may be inaccessible to them. However, if you already had a pure PHP solution, that could be a fall back.

    The function itself is about as efficient as these things can be. As stated before, it chooses the optimal method for making a request as the page loads so that each request made doesn't have to determine anything about that. It also creates a new instance not only of a request, but also of the final disposition of that request, so it is fairly bulletproof. That's to say you can have several requests going on at one time and they will not conflict unless you do something outside the loadXmlHttp function to cause them to do so.

    From a coding point of view, the loadXmlHttp function could be improved to optionally allow POST requests and a designer defined callback (rather than simply always having to send the output to an element). It could also have more response callbacks, like for loading, failure, etc. Right now it only responds if the request is successful.

    Slow servers and/or low bandwidth combined with a sluggish computer on the user's end will cause problems, but not much more than they would with an ordinary page. This plagues all AJAX routines, this one probably less so than others because of its efficiency. With AJAX you are imposing another layer to everything you do (not entirely unlike a frameset or iframe). Poor network conditions and/or slow response on the user end will affect it more than an ordinary page, but not much more.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #23
    Join Date
    Jul 2008
    Posts
    65
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Well.. my thinking is that given the percentage of users with javascript disabled... I wont bother catering for them. The site looks really good with javascript enabled. It is designed for javascript, and if a user does not want to enable it, it is their loss.

    One thing I have encountered is chucks of text.
    For example a comments system... actually any user input really.

    If a user inputs data into a textarea, how can you use loadXmlHttp to pass said data to a php script to insert it into a database, and then reload a page?

    Cheers

  4. #24
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    I wouldn't use it for that. Ordinary PHP can do that. If the textarea is in a form that submits to the page itself:

    Code:
    <form action="<?php echo $PHP_SELF; ?>" method="post">
    <textarea name="token_for_the_post_data" rows=25 cols=60></textarea><br>
    <input type="submit" value="Update">
    </form>
    Then the page itself could check its post data when it loads for the "token_for_the_post_data" to see if its there and has a value, and to update whatever you want with that.

    Refinements on this could include using PHP for setting the post token on the basis of previous actions so that one form could be used successively to update various things, or alternatively the textarea could be repopulated by PHP with the just submitted data.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #25
    Join Date
    Jul 2008
    Posts
    65
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Fair enough.

    My thinking here however is user experience. Yes PHP can easily do it, but it requires a page reload..

    ATM I have used Ajax, so that on one page you have 3 most recent news posts. On clicking the title it uses Ajax to replace the contents of the div with any comments that have been made on said post. It also presents a textarea to add your own comment.

    What I was wanting was the ability to post a comment without reloading the page... meaning that once news.php has loaded the user doesnt actually have to reload at all, and can do anything.

    Thoughts?
    Cheers

  6. #26
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by clowes View Post
    how can you use loadXmlHttp to pass said data to a php script to insert it into a database, and then reload a page?
    Quote Originally Posted by clowes View Post
    Yes PHP can easily do it, but it requires a page reload..
    Huh? That's what I thought you were asking at first, but then I actually read the post more carefully (see first quote).

    Anyways, it cannot. Not in it's present form. Now, I've had no experience doing this, well some (very little) via an almost completely different method (using a form to GET to a PHP page in an unseen iframe that updates a Session variable used in an ongoing javascript process on the top page). I know in theory what to do, it's really not all that different. But I would need to study up on it a bit more before presenting a trial version.

    However, certain types of post requests might not be able to be made using AJAX. For these (if any) the method outlined in my previous post or a modification on that where the post request is made to a PHP page in an unseen iframe could be used.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. #27
    Join Date
    Jul 2008
    Posts
    65
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    I had a think about this... and it got me thinking about what I was using before in my chat script (before you showed me your function).

    Code:
    if(document.getElementById){
    window.alert = function(text){
    err(text);
    }
    }
    function err(text){
    document.getElementById("alert").innerHTML = text;
    setTimeout('document.getElementById("alert").innerHTML = ""', 3000);
    }
    function makeRequest(){
    if(window.XMLHttpRequest){
    return new XMLHttpRequest();
    } else if(window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
    err("You browser doesn't support XMLHttpRequestObject");
    }
    }
    var req = makeRequest();
    function send(){
    if(req.readyState == 4 || req.readyState == 0){
    if(document.chatform.guestname.value != "" && document.chatform.chatext.value != ""){
    req.open("GET", "send.php?name="+document.chatform.guestname.value+"&msg="+escape(document.chatform.chatext.value));
    req.send(null);
    
    new loadXmlHttp('getnewspost.php','NewsDiv');
    } else {
    alert('Hey where is your name or message??');
    }
    }
    document.chatform.chatext.value = '';
    }

    Is that not it right there? onclick="send(); return false;"

    It would update the database using send.php and the variables pass by GET, then it would run a new loadXmlHttp to reload the news post content (with the new comment).

    Surely?

  8. #28
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    That will do it via GET, yes, with some improvement though. The query string must be URI Component Encoded (which lengthens the string) in case it contains characters like & or + that otherwise would have a special meaning. The space character may have to be converted to a +. This encoding business isn't critical in all browsers/for all servers, but will be for some. I'm not certain if PHP then has to be told to decode the value(s) or if it does so automatically.

    However, I thought your question was via POST not GET:

    Quote Originally Posted by clowes
    What I was wanting was the ability to post a comment
    But now upon re-reading it I see that was probably not the case. Anyways, POST can handle more characters. GET is limited to, well I've seen different values, and it varies by browser. 2008 was mentioned as one limit in IE, no version number given.

    Also, with a POST, headers must be sent and the data is sent as part of the req.send(data). Not as a query string. See how data replaces null? The data must be URI Component Encoded as well. This is all fairly easy to work out, except for the handling of radio and checkboxes. To combine it into one function that can perform both GET and POST requests is a little tricky too.

    If you are serious about doing it right and want to use both GET and POST, I would suggest using a library designed for that. The jQuery library looks to be one of these, and is otherwise a very good script library. See:

    http://docs.jquery.com/Ajax

    I've always wanted to work out a POST request though. I have code now (been working on it off and on today), not completely finsihed, that can handle it, with the exception that it will not present radio and checkboxes in the same format as actually submitting the form would. Instead of an array, it will send the values of any that are checked.

    I'm probably not going to work on this much further today, but when I have something decent I'll let you know. I think I will also work it out so it can do a GET like that as well. Not a real good idea for textarea though unless you can guarantee that the encoded length (including the name(s) of the textarea(s) will be under 2000 characters.
    Last edited by jscheuer1; 12-19-2009 at 08:29 PM. Reason: add info
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  9. The Following User Says Thank You to jscheuer1 For This Useful Post:

    clowes (12-19-2009)

  10. #29
    Join Date
    Jul 2008
    Posts
    65
    Thanks
    8
    Thanked 0 Times in 0 Posts

    Default

    Sorry,

    I am not great at explaining myself. I want a user to be able to add a comment to a database via a form. I was not specifically referring to utilizing the POST function, although that is the norm when using forms.

    I believe PHP can decode the values itself automatically.

    jquery and the like go over the top of my head. Loads of files, loads of complex code, and loads of ne wknowledge. I much prefer to have just what I need, gradually understand it, and build it up.

    On that basis, I'd love to be able to see your function on completion.
    Cheers for your time.

  11. #30
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,167
    Thanks
    44
    Thanked 3,240 Times in 3,201 Posts
    Blog Entries
    12

    Default

    Yes, as I looked at it further,I found some things that would probably just be transparent, like PHP understanding what to do with name/value pairs passed as POST or GET encoded URI Component data. There are now so many possible arguments, all of which are optional, that I've switched to using an Object to pass them to the function. This makes it a little trickier to use, but really simplifies its use for any particular purpose. See the comments at the beginning of the code for an explanation and example. But say you have a form you want to post to back to the page itself and see the post result in a div with an id of 'result', you could do:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
    #result {
    	width: 15em;
    	height: 1.75em;
    	border: 1px solid pink;
    }
    </style>
    <script type="text/javascript" src="http_get_post.js"></script>
    <script type="text/javascript">
    function mcb(){
    	if (this.success()){
    		/<\/div>([^<]*)<\/b/.test(this.xmlHttp.responseText);
    		this.el.innerHTML = RegExp.$1;
    	}
    }
    </script>
    </head>
    <body>
    <form action="#" onsubmit="new loadXmlHttp({bust: true, form: this, id: 'result', method: 'post', callback: mcb});return false;">
    <input type="text" name="test" value="bob"><br>
    <input type="submit" value="Go!">
    </form>
    <div id="result">
    
    </div>
    <?php echo $_POST['test']; ?>
    </body>
    </html>
    Now, the right way to do this would be to add/attach the event to the form. So I will make a function for doing that as part of the overall function. But if you know how to do that, you may do it yourself. If you control the page and know what you are doing, it really doesn't hurt anything doing it this way. Also, knowing me, I'll probably come up with efficiencies and/or other improvements. For now though, here's the function:

    Code:
    /* loadXmlHttp Script 2009 John Davenport Scheuer
       as first seen in http://www.dynamicdrive.com/forums/
       username: jscheuer1 - This Notice Must Remain for Legal Use
       */
    
    /* reqObject Properties - //all optional, comma delimit
    	url: page_to_fetch //defaults to this page
    	method: POST_or_GET //defaults to GET
    	el: element_to_populate //defaults to none, overrides id
    	id: id_of_element_to_populate //defaults to none, requires no el
    	form: form_submitting_data //defaults to none, requires no query
    	data: encoded_data_to_send_with_POST_request //defaults to none, requires POST and no form
    	query: encoded_data_to_send_with_GET_request //defaults to none, requires GET, overrides form
    	callback: function_to_run_on_success //defaults to populate, in default mode requires el or id
    	bust: true_OR_false //defaults to false, add cache busting time stamp to request?
    	*/
    
    /* Usage:
    	new loadXmlHttp({reqObject Properties})
       Example:
    	new loadXmlHttp({url: 'somePage.php', method: 'POST', form: document.forms.myform})
    	*/
    
    function loadXmlHttp(req){
    	if(loadXmlHttp.xmlHttp){
    		var f = this, r;
    		for(r in req){
    			if((req.hasOwnProperty && req.hasOwnProperty(r)) || !req.hasOwnProperty){
    				f[r] = req[r];
    			}
    		}
    		f.xmlHttp = loadXmlHttp.xmlHttp();
    		f.el = f.el || (f.id? document.getElementById(f.id) : null);
    		f.method = f.method? f.method.toUpperCase() : 'GET';
    		f.url = f.url || location.href;
    		f.bustCache();
    		f.url += f.method === 'GET' && f.query? f.qa + f.query : '';
    		if(f.method === 'GET' && !f.query && f.form){
    			f.encodeData();
    			f.url += f.qa + f.data;
    		}
    		f.xmlHttp.open(f.method, f.url, true);
    		if(f.callback !== null){
    			f.xmlHttp.onreadystatechange = typeof f.callback === 'function'?
    			function(){f.callback.apply(f);} : function(){f.stateChanged();};
    		}
    		if(f.method === 'POST'){
    			if(f.form){
    				f.encodeData();
    			}
    			f.xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    			f.xmlHttp.setRequestHeader('Content-length', f.data? f.data.length : 0);
    			f.xmlHttp.setRequestHeader('Connection', 'close');
    		}
    		f.xmlHttp.send(f.method === 'POST' && f.data? f.data : null);
    	}
    	else alert('Your browser does not support AJAX!'); // substitute your desired request object unsupported code here
    }
    
    //setup - while parsing:
    loadXmlHttp.xmlHttp = null; loadXmlHttp.re = /^http/.test(location.href); loadXmlHttp.qa = /\?/;
    /*@cc_on @*/ // used here and below, limits try/catch to those IE browsers that both benefit from and support it
    /*@if(@_jscript_version >= 5) // prevents errors in old browsers that barf on try/catch & problems in IE if Active X disabled
    try {loadXmlHttp.ie = window.ActiveXObject}catch(e){};
    @end @*/
    if (window.XMLHttpRequest && (!loadXmlHttp.ie || loadXmlHttp.re))
    	loadXmlHttp.xmlHttp = function(){return new XMLHttpRequest();}; // Firefox, Opera 8.0+, Safari, others, IE 7+ when live - this is the standard method
    else if (/(object)|(function)/.test(typeof createRequest))
    	loadXmlHttp.xmlHttp = createRequest; // ICEBrowser, perhaps others
    else {
    	loadXmlHttp.xmlHttp = null;
    	// Internet Explorer 5 to 6, includes IE 7+ when local //
    	/*@if(@_jscript_version >= 5)
    	try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Msxml2.XMLHTTP");};}
    	catch(e){try{loadXmlHttp.xmlHttp = function(){return new ActiveXObject("Microsoft.XMLHTTP");};}catch(e){}}
    	@end @*/
    }
    
    loadXmlHttp.prototype = {
    	stateChanged: function(){
    		if (this.el && this.xmlHttp.readyState == 4 && (this.xmlHttp.status == 200 || !loadXmlHttp.re)){
    			this.el.innerHTML = this.xmlHttp.responseText;
    		}
    	},
    	encodeData: function(){
    		var els = this.form.elements; this.data = '';
    		for(var i = 0; i < els.length; ++i){
    			if(els[i].name){
    				this.data += (i? '&' : '') + els[i].name + '=' + encodeURIComponent(els[i].value);
    			}
    		}
    	},
    	bustCache: function(){
    		this.qa = loadXmlHttp.qa.test(this.url)? '&' : '?';
    		if(this.bust){
    			this.url += this.qa + 'bustacache=' + new Date().getTime();
    			this.qa = '&';
    		}
    	},
    	success: function(require_el){
    		return (this.el || require_el === false) && this.xmlHttp.readyState == 4 && (this.xmlHttp.status == 200 || !loadXmlHttp.re);
    	}
    };
    //end setup
    I've tested this pretty thoroughly, though it may have some kinks in it yet. If you have questions, problems or suggestions, feel free.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

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
  •