I have a standard form on poll.php:
<form method="POST" action="createpoll.php"&开发者_StackOverflow社区gt;
..blah...
</form>
Is there anyway to process the form without leading the user to createpoll.php, something like calling createpoll.php on submit?
This technology is called AJAX. With help of JAvaScript libraries it's become really easy to use it. You can use JQuery or Prototype. Search for AJAX submission. There are a lot of answers on this topic - i.e., stackoverflow questions.
For exapmle, using JQuery method ajax() it looks like this(JavaScript):
$.ajax({
type: "GET", // method - Get or Post
url: "cart.php", // Url to send data
data: { addproduct: productIDVal, isAjax: 'true'}, // Parameters
success: function(theResponse) {
// code to operate with response, if the request was succesful.
// It can be string or array.
}
});
A great, extremely easy way to use Ajax in your form can be found here: http://jquery.malsup.com/form/
This is a great tutorial that should help you get started: http://onlamp.com/pub/a/onlamp/2005/05/19/xmlhttprequest.html
You're going to need to capture form submission with JavaScript, submit the data with XMLHttpRequest (XHR), and parse the response.
Courtesy of http://js.isite.net.au/snippets/form2obj
You can also find the obj2query
function on the same site.
<form action="submit.here" method="POST" onsubmit="submit_via_xhr( this.method,
this.action, obj2query( form2obj( this ) ), successFunction ); return false">
function form2obj(theForm) {
var rv = {};
if (typeof(theForm) == 'string')
theForm = document.getElementById(theForm);
if (theForm) {
for (var i = 0; i < theForm.elements.length; i++) {
var el = theForm.elements[i];
if (el.name) {
var pushValue = undefined;
if (
(el.tagName.toUpperCase() == 'INPUT'
&& el.type.match(/^text|hidden|password$/i))
|| el.tagName.toUpperCase() == 'TEXTAREA'
|| (el.type.match(/^CHECKBOX|RADIO$/i) && el.checked)
){
pushValue = el.value.length > 0 ? el.value : undefined;
}
else if (el.tagName.toUpperCase() == 'SELECT') {
if( el.multiple ) {
var pushValue = [];
for( var j = 0; j < el.options.length; j++ )
if( el.options[j].selected )
pushValue.push( el.options[j].value );
if( pushValue.length == 0 ) pushValue = undefined;
} else {
pushValue = el.options[el.selectedIndex].value;
}
}
if( pushValue != undefined ){
if(rv.hasOwnProperty( el.name ))
if( rv[el.name] instanceof Array ) {
rv[el.name] = rv[el.name].concat( pushValue );
}
else {
rv[el.name] = [].concat( rv[el.name], pushValue );
}
else {
rv[el.name] = el.value;
}
}
}
}
}
return rv;
}
精彩评论