NickC
NickC

Reputation: 1353

Submitting a form without page refresh

I realize that Ajax is the recognized way to submit a form without page refresh but to do that involves cycling through each field and constructing the Post string to submit.

Is there not some alternative way to use the browsers built-in functionality to submit the form but intercept the returned html to stop the page being refreshed?

Edit: Not the same as the suggested duplicate which asks about form validation: "I am wanting to run javascript user validation"

Edit2: The primary problem is how to stop the servers response to the submit from navigating to a new page. Is there something the server could respond with which would stop the whole page getting refreshed?

Edit3: What about returning an http 204 response: Server has received the request but there is no information to send back, and the client should stay in the same document view. This is mainly to allow input for scripts without changing the document at the same time

Upvotes: 0

Views: 863

Answers (1)

Adrian Bratu
Adrian Bratu

Reputation: 508

yes there is.. the idea is to have the form action and the onsubmit event handled

consider the code below:

<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }

}

at this point you are intercepting the call to ensure that the form is valid. if everything passes than a page refresh will trigger. If you want the refresh not to occur you need to handle the post via ajax where you will need to rebuild the entire call. hope this will help you out.. cheers

a simple way to do it, if you are using jquery is to serialize the data using the http://api.jquery.com/serialize/ functionality

one way to do this is if you are using jQuery:

<form id="myForm" name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">


function validateForm() {
    var x = document.forms["myForm"]["fname"].value;
    if (x == "") {
        alert("Name must be filled out");
        return false;
    }

    var url = $('#myForm').attr('action');
    var data = $('#myForm').serialize();
    $.post(url, data);
}

Upvotes: 1

Related Questions