Snazzy Sanoj
Snazzy Sanoj

Reputation: 802

Form Submission with another Form's data

I have two forms in a single page like,

<form action="login.php" method="POST">
    <input type="text" name="username">
    <input type="submit" value="submit">
</form>

<form action="login2.php" method="POST">
    <input type="text" name="code">
    <input type="submit" value="submit">
<form>

The only possible ways to login will be,

  1. username and code
  2. code only

A user can't login with username alone.

When user needs to login with username and code, the request should be sent to the login.php, and when the user needs to login with code alone, the request should be sent to login2.php.

So far, the code alone method works fine, but I'm not sure, how to submit the code value along with the first form's request, for username and code method by using JS/JQuery?

Any help would be appreciated :)

Upvotes: 2

Views: 1737

Answers (1)

eckymad
eckymad

Reputation: 1070

I'd combine the forms into one and let the server-side php script to decide if it was login method (1) or (2).

    if(isset($_POST['username']) && isset($_POST['code'])){
        // Username and code login
    }
    else if (isset($_POST['code'])){
        // Code only login
    }

Alternatively, use a bit of JavaScript to take the form values from the form to check if the username is present, and post the values to the desired script. With jQuery this would be something like:

$("#loginForm").on("submit", function(e){

    var username = $('input[name="username"]).val(),
        code = $('input[name="code"]).val(),
        login_script = username ? 'login.php' : 'login2.php';

    // Prevent form submitting
    e.preventDefault();

    $.ajax({
        url: login_script,
        method: 'POST',
        data: { username: username, code: code },
        success: function(response){
            console.dir(response);
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.error(arguments);
        }
});

Upvotes: 1

Related Questions