Putting together a submit button that doesn't force a page reload

1k Views Asked by At

I have several forms on a single page (anywhere from 1-20+) and I want each one to have it's own submit button. The submit button for each form will ideally POST the data in the form to a handler php file that will submit it to a database. It'd also be nice if it replaced the form with some "Data Submitted" confirmation text, but that is sort of fluff on top I can add on later. I'd like to do this with ajax but I'm unsure how to accomplish this.

Lets just pretend my form is a single field and it looks something like this:

<form action="submitHandler.php" method="post">
    <input type="text" value="testdata" name="Details" id="details">
    <button type="submit" onclick="functionThatSendsData">Submit</button>
</form>

This is my getXMLHTTP() function. I've used it before for some other ajax related things so I'm quite sure it's correct

function getXMLHTTP() { //function to return the xml http object
    var xmlhttp=false;  
    try{
        xmlhttp=new XMLHttpRequest();
    }
    catch(e)    {       
        try{            
            xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e){
            try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1){
                xmlhttp=false;
            }
        }
    }

    return xmlhttp;
}

I would have to imagine my SubmitHandler.php would do something like this:

$data=$_POST['Details'];

//make connection to database, bail if no connection
$connection = odbc_pconnect('db','','');
if (!$connection) { exit("Connection Failed: " . $connection); }

//Insert Fields into DB
$sql = "INSERT INTO TestTable (Data) VALUES ('$data')";
$rs = odbc_exec($connection, $sql);
if (!$rs) { exit("Error in SQL"); }

It appears I mostly need help with the 'functionThatSendsData' that would be executed on the submit button click. This is a simple example but obviously it'd need to be scaled to accommodate more field values (10 or so). Could anybody help me out with this? If I could get it working with just one piece of data I could scale it myself I'm assuming.

2

There are 2 best solutions below

1
Hoser On BEST ANSWER

http://www.webmaster-talk.com/javascript-forum/230390-how-can-i-submit-form-without.html

Post 8 in this thread helped me tremendously. Figured I'd post it for anybody who later stumbles upon this.

1
Zeal On

You need to cancel the submit action of the button.

Classically write return false as return value of your script.

return false;

Or declare a preventdefault at the beginning of your action when you use Jquery: http://api.jquery.com/event.preventDefault/