Using The Post Method In Ajax

22 09 2008

In the Rasmus’ 30 Second Ajax Tutorial, we’re using the get method to send our request:

function sndReq(action) {
     http.open('get', 'rpc.php?action='+action);
     http.onreadystatechange = handleResponse;
     http.send(null);
}

But what if we want to use the post method? Well, let’s modify that function to do just that:

function sndReq(action) {
    http.open('post', 'rpc.php', true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http.setRequestHeader("Content-length", action.length);
    http.setRequestHeader("Connection", "close");
    http.onreadystatechange = handleResponse;
    http.send(action);
}

That’s it, that’s all you need to modify. Of course, you’d need to modify your rpc.php page to receive requests using the post method.

Remember, this is one way to do it.

Hope this helps.



The textContent and innerText Properties

18 04 2006

In my original post, Using the innerText Property in Firefox, I wrote my example using document.all to determine when to use innerText or textContent.

Because the main purpose of that post was to explain to the reader that Firefox does not support the innerText property but the textContent property, I failed to consider other browsers… yes, shame on me! (thanks Paul for bringing this to my attention).

You see, there are browsers that although don’t support document.all, they DO support the innerText property: Safari and Konqueror.

So, it is more efficient to check if the innerText property is supported by the user agent (thanks, Matthias). The way I do it is like this:

var hasInnerText =
(document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;
var elem = document.getElementById('id');
var elem2 = document.getElementById ('id2');

if(!hasInnerText){
    elem.textContent = value;
    elem2.textContent = value;
} else{
    elem.innerText = value;
    elem2.innerText = value;
}

Why am I using document.getElementsByTagName("body")[0]? Well, because, as you know, document.getElementsByTagName returns an array of elements with that tag name, and since there’s only ONE body tag, I’m calling the first and only index of that array at once. This is so, as you can see in the example above, if you have more than one element that you need to assign a value to.

I have an example. If you wish, check the source out to see how it works.

Compatibility:

  • Linux:
    • Konqueror 3.5.2
    • Firefox 1.5.0.1
  • Mac X:
    • Safari 2.0.3
    • Camino 1.0
  • Windows:
    • Firefox 1.5.0.2
    • Opera 8.54
    • Internet Explorer 6
    • Internet Explorer 7.0.5346.5 Beta 2

Remember, this is one way to do it. Cheers! ;)



Multiple Submit Buttons on a Single Form

4 10 2005

At some point, people ask themselves “How can I have two submit buttons with different actions in one form?” Well, the approach I’ve used to accomplish this task is to ‘emulate’ the submit buttons with regular button controls and changing the form action based on what button was clicked.

In the following example I have a text field and 3 different buttons that will send the string to be searched to Google, MSN or Yahoo depending on what button the user clicks.

The Code

So, the JavaScript looks like this:

<script type="text/javascript">
<!--
    function IsBlankField(field){
	var j = 0;
	var chr;

	for(j; j < field.length; j++){
	    chr = field.charAt(j);

	    if(chr != "" && chr != " " && chr != "\n" && chr != "\t"){
		return false;
	    }
	}

	return true;
    }

    function SendTo(id){
        //shortening form elements
        var myForm      = document.getElementById('myForm');
        var txtSearch   = document.getElementById('wrdSearch');
	var srchURL;    // this variable will hold the URL of the search engine to be used
        var srchVar;    // this variable will hold the value of the text field 'name' which will hold the string to be searched 

        if(IsBlankField(txtSearch.value)){
            //if the form doesn't validate, send this alert
            alert("there's nothing to search for!");
        } else{
            if(id == "google"){
		srchURL = "http://www.google.com/search";
		srchVar = "q";
            } else if(id == "msn"){
		srchURL = "http://search.msn.com/results.aspx";
		srchVar = "q";
            } else{
		srchURL = "http://search.yahoo.com/search";
		srchVar = "p";
            }

            //adding the attribute name and values to the form and text field elements
	    myForm.setAttribute("action", srchURL);
	    txtSearch.setAttribute("name", srchVar);
	    myForm.setAttribute("target", "_blank"); //this, of course, will open a new browser window
	    myForm.setAttribute("method", "get");

            myForm.submit();           

        }
    }
//-->
</script>

And the HTML part looks like this:

<form name="myForm" id="myForm">
    Search: <input type="text" id="wrdSearch"/>
    <input type="button" name="google" id="google" value="Google" onClick="SendTo(this.id)"/>
    <input type="button" name="msn" id="msn" value="MSN" onClick="SendTo(this.id)"/>
    <input type="button" name="yahoo" id="yahoo" value="Yahoo" onClick="SendTo(this.id)"/>
</form>

Explanation

In the JavaScript, the IsBlankField(field) function takes as its argument the text field value and will check if it is empty or has space, new line or tab characters. If it does, the function will return true and the form will not validate.

if(IsBlankField(txtSearch.value)){
    //if the form doesn't validate, send this alert
     alert("there's nothing to search for!");
}

The SendTo(id) function takes one argument (the button id) so that we know what button triggered the event. Then we will add the attributes, with the correct values, to the form and text field elements using the DOM setAttribute() method. As you can see in the code sample, this method takes two parameters: the attribute name and the attribute value.

function SendTo(id){
    ....
    ....
    ....

    myForm.setAttribute("action", srchURL);
    txtSearch.setAttribute("name", srchVar); //this will add the name attribute to the text field element
    myForm.setAttribute("target", "_blank");
    myForm.setAttribute("method", "get");

Then, we submit the form.

    myForm.submit();
    ....
    ....
}

In the HTML, notice that the form does not have its name, action and method attributes (nor the text field has its name attribute). As I explained before, they are being added with the DOM setAttribute() method.

<form name="myForm" id="myForm">
    Search: <input type="text" id="wrdSearch"/>
    ....
    ....
</form>

See the demo.

Compatibility

This will work on Firefox 1.0.7, IE 6, Opera 8.01 and Konqueror 3.4.2 (I haven’t tested this on Safari, but most likely it’ll work :D )

That’s it! Hope this can help to get you started if you ever need to have 2 or more ’submit’ buttons on one form. And remember, this is one way to do it ;)

J



Using the innerText Property in Firefox

22 09 2005

I’ve read on different forums questions of people asking how they can make the innerText property work in Firefox. Many have suggested to use the innerHTML property instead, but that would not be useful because, obviously, the HTML tags would be either rendered or displayed (an example of the latter would be if we want such text to be displayed in a textarea or text field) giving undesired effects.

Well, in short, Firefox does not support the innerText property. Instead, it supports the textContent property.

So, you could ’sniff’ what browser the user is using and use the correct property accordingly.
So, you could check for the browser’s feature support to use the correct property accordingly (this is better than sniffing ;) )

Example (updated):

if(document.all){
     document.getElementById('element').innerText = "my text";
} else{
    document.getElementById('element').textContent = "my text";
}

That’s it. Hope it helps ;)

J

Addendum:
See also: The textContent and innerText Properties. This post will help you to make the innerText property work in Safari too ;)



Rasmus’ 30 second AJAX Tutorial

10 08 2005

This is a great and simple example/tutorial on AJAX by Rasmus Lerdorf (the creator of PHP).

It’s just AWESOME!

Rasmus’ 30 second AJAX Tutorial

(Original Post @ php-general mailing list)






LiveSTRONG