user2131323
user2131323

Reputation: 105

AJAX form submission is not functioning

I'm trying to make a set of JavaScript functions that will allow me to load and submit forms dynamically. I have managed to create a working function that loads the form into the page, but I cannot get the submit function to work correctly. What happens is, when I click submit, the form that had loaded in already (using JavaScript load function) disappears and the original content reappears. Also the alert in the submit function does not appear.

I have looked all over this site and found similar issues, but none that load the form in using AJAX then submit using AJAX, all of the others already have the form loaded.

Any help would be much appreciated, I am very new to using AJAX.

Form

echo $Error;
echo '<form id="login" method="post">';
echo '<input type="test" name="Email" placeholder="[email protected]"';
if(isset($Email)) echo "value = ".$Email;
echo '      />'."<br />";
echo '<input type="password" name="Pass" placeholder="Password" />'."<br />";
echo '<input type="submit" value = "Login"/>'."<br />";
echo '</form>';

Load page Function

function Page(url,output)
{
    var Request = '';
    if (window.XMLHttpRequest)
    {
        Request=new XMLHttpRequest();
    }
    else
    {
        Request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    Request.onreadystatechange=function()
    {
        if (Request.readyState==4 && Request.status==200)
        {
            document.getElementById(output).innerHTML = Request.responseText;
        }
    }
    Request.open("GET",url,true);
    Request.send();
}

Submit function

$(function () {
$('form#login').on('submit', function(e) {
    alert('Found');
    $.ajax({
        type: 'post',
        url: 'php/login.php',
        data: $(this).serialize(),
        success: function (complete) {
            document.getElementById('output').innerHTML = complete;
        }
    });
    e.preventDefault();
  });
});  

Upvotes: 0

Views: 96

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

If you're loading the form using AJAX you'll need a delegated event handler:

$(document).on('submit', 'form#login', function(event) {
    // your AJAX form submission code here
});

When your usage of .on() executes it's looking for that element to exist at that point, but it doesn't, which means you don't end up with any event handler being bound.

There's also a typo in your server-side code for the form: <input type="test" That should likely be type="text"

Full code:

$(function () {
    $(document). on('submit', 'form#login', function(e) {
        alert('Found');
        $.ajax({
            type: 'post',
            url: 'php/login.php',
            data: $(this).serialize(),
            success: function (complete) {
                document.getElementById('output').innerHTML = complete;
            }
        });
        e.preventDefault();
    });
});  

Upvotes: 2

Related Questions