2

I have a form which should submit data after pressing the submit button. After tagging a few input fields as required the form always shows me when there is no input in the required field after pressing the submit button - so far, so good.

What I would like to realize is that there is a redirection to another page if the submission was successful. If there are some empty required fields the form should show me, without redirecting me to another page.

By now I have the following code:

Submit button:

<div class="form-group">
     <div class="col-sm-offset-2 col-sm-10">
    <button type="submit" name="submityes" id="submityes" class="btn btn-danger">Submit</button>
      </div>
  </div>

Also I have the following js function to submit the form and to redirect me to another page:

$('document').ready(function () {
    "use strict";
    $(function () {
        $('#submityes').click(function () {
            $.ajax({
                type: "POST",
                /* url: "process.php", //process to mail
                data: $('form.contact').serialize(), */
                success: function (msg) {
                    window.location.replace("/submit_resolved.php");
                },
                error: function () {
                    alert("error");
                }
            });
        });
    });
});

The problem I have right now is that I will always be redirected to the "submit_resolved.php" page, whether all required fields are complete or not.

How can I solve this problem? I only want to be redirected when all required fields are not empty.

Osmund Francis
  • 771
  • 10
  • 27
Tim Kühn
  • 47
  • 1
  • 1
  • 12
  • 1
    Your current code doesn't submit the *form*, it makes an Ajax request without first doing any validation. Why don't you just do a standard (non-Ajax) form submit, and then handle the redirection within your PHP? – nnnnnn Mar 21 '17 at 12:59
  • You can change your event listener to listen for `submit` of the form then use the `required` attribute on your HTML elements.... You will want to add `event.preventDefault();` if you change the eventlistener to listen for the form submit to prevent the form doing it's default action `post` so maybe wrap the form with a form tag.... – NewToJS Mar 21 '17 at 13:01
  • Thank you. How can I do the code without ajax? And what is the difference between doing it with ajax and not? – Tim Kühn Mar 21 '17 at 13:35

5 Answers5

4

You should bind to the submit event, not click event:

UPDATED TO MATCH THE COMMENTS

$(function () {

    var submityesClicked;

    //catch the click to buttons
    $('#submityes').click(function () {
        submityesClicked = true;
    });
    $('#submitno').click(function () {
        submityesClicked = false;
    });

    $('#webform').submit(function (e) {
        e.preventDefault();//prevent the default action

        $.ajax({
            type: "POST",
            /*url: "process.php", //process to mail
             data: $('form.contact').serialize(),*/
            success: function (msg) {
                window.location.replace(submityesClicked ? "/submit_resolved_yes.php" : "/submit_resolved_no.php");
            },
            error: function () {
                alert("error");
            }
        });
    });
});

The submit event is triggered only if the form is valid.

Note that the submit event is triggered by the form but the click event is triggered by the input element.

Constantin Galbenu
  • 16,951
  • 3
  • 38
  • 54
  • Thank you. So to bind the submit event I need to change the selector from '#submityes' to something else? Unfortunately I am not sure which expression to write in there. – Tim Kühn Mar 21 '17 at 14:19
  • Oh, I think I got it. I gave the form the name/id "webform" and I wrote '#webform' instead of '#submityes' into the brackets. Now I have another little problem: the form has two different submit buttons ('#submityes' and '#submitno'). Both should redirect the user to a different page. How can I implement this into the code? It should be something like "if '#webform' is submitted via '#submityes' redirect to X, if it is submitted via '#submitno' redirect to Y' – Tim Kühn Mar 21 '17 at 14:23
  • Something that I don't understand is why should I use the preventDefault()? Because of that, my form is not sent to my email. But without the preventDefault() my form is sent and my redirection is working too. So how is it usefull to have it? – Thierry Lemaitre Apr 27 '20 at 18:09
  • If you don't prevent the default behavior of the form then it will be send two times, first in the AJAX call and second as the default behavior when a user press the submit button. – Constantin Galbenu Apr 28 '20 at 16:21
2

Do redirection on complete. Not on success

$('document').ready(function () {
    "use strict";
    $(function () {
        $('#submityes').click(function () {
            $.ajax({
                type: "POST",
                /* url: "process.php", //process to mail
                data: $('form.contact').serialize(), */
                success: function (msg) {
                    //window.location.replace("/submit_resolved.php");
                },
                complete: function () {
                    window.location.replace("/submit_resolved.php");
                },
                error: function () {
                    alert("error");
                }
            });
        });
    });
});
Osmund Francis
  • 771
  • 10
  • 27
Alex Slipknot
  • 2,439
  • 1
  • 18
  • 26
  • The OP doesn't want any redirection if the form didn't validate successfully (as in, no redirection if required fields were left blank). – nnnnnn Mar 21 '17 at 13:01
  • Maybe my misunderstanding... But anyway first we have to validate - before submit, then send request via ajax and when response received - check if all ok and process result in success. Then if all ok, in complete we have to redirect user. Am I right? – Alex Slipknot Mar 21 '17 at 13:08
0

I assume you are validating form in process.php so, you have to return error if validation fail from process.php like this.

header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
die(json_encode(array('message' => 'ERROR', 'code' => 1337)));

check this link: Return errors from PHP run via. AJAX?

Hope this may be helpful to you.

Community
  • 1
  • 1
Maya Shah
  • 950
  • 7
  • 17
0

The simplest thing you can do is to add "required" attribute to you input elements.Example:

<form action="/action_page.php">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form> 

It's a HTML5 attribute, so no JavaScript required. And it is supported by all major browsers. Check this link:

http://caniuse.com/#search=required

Anyway, you shouldn't rely just on front-end verification. Check those inputs on back-end, too.

ebu_sho
  • 394
  • 6
  • 17
0
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
     <div class="col-sm-offset-2 col-sm-10">
        <form action="">
           Username: <input type="text" id="usrname" required>
          <button type="button" name="submityes" 
           id="submityes" class="btn btn-danger">Submit</button>
       </form> 
  </div>

function isValid(){
  var usrname = $("#usrname").val();
    if(usrname == ""){
      return false;
    }
  return true;
}
$(function () {
    $('#submityes').submit(function () {
    if(isValid() == true){
        $.ajax({
            type: "POST",
           /*url: "process.php", //process to mail
            data: $('form.contact').serialize(),*/
            success: function (msg) {
                alert("success");
                window.location.replace("/submit_resolved.php");
            },
        });
        }else{
        alert("error");
        }
    });
});
Aravindh Gopi
  • 2,083
  • 28
  • 36