Making XMLHttpRequest using form, a.k.a. cancel form submission

The trick is how to make an XMLHttpRequest call to a page (mostly a server-side script like PHP) instead of (without) letting the browser loading that page. You just need to cancel the form submission by appending “return false” at the end of the xmlhttprequest call.

<!–HTML

<form action=””><input id=”btn” type=”button” name=”submit” value=”Search!” /></form>

//–>

<!–javascript

function sub( f){

//do something first, like make validating the form and making an XMLHttpRequest, etc.,

//return false will cancel form submission
return false;

}

window.onload = function(){

var btnEl = document.getElementById(“btn”);

if (btnEl){

btnEl.onclick = function(){

//this.form refers to the button’s form value

//just in case you need to grab some “input” values directly from the form

sub(this.form);
}
}

}

//–>

Here is a good article talking about “From Tricks” back in 1997.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: