2

I'm finally at the point of testing my site in other browsers (built it mostly in Chrome). Unfortunately, a lot of stuff seems to function differently. I'll begin with the very first problem: upon login, I have a JS/jQuery check to make sure the username and password match, and upon failure it should stop the submission.

However, while it works in Chrome and Safari, in Mozilla and IE the submission is still going through (hitting an apology page, but still something I'd rather just not see at all).

I've tried subbing out event.preventDefault() for e.preventDefault() or evt.preventDefault() but none of them work, the form still submits (and for the second two it makes it so that it submits in Chrome as well). Here is my code, would love any thoughts:

function checkLogin()
{
    // get the variables, execute some other checks (eg, things not blank)

    // run ajax code to determine if pieces match
    $.ajax({
    type: "POST",
    url: "check_login.php", 
    data: {'username': username, 'password': password},
    async: false,
    success: function(result) 
    {
      if (result == 1)
      {
        $('#loginoff').html("Invalid username/password");
        e.preventDefault();
        return false;
      } 
      else
      {
        $('#loginoff').html("");
        return true;
      } 
    }
    });
}

Please note that the function is definitely going through and returning 1 when the username and password don't match as, in all cases, the 'Invalid username/password' message is coming up.

Also, in case anybody is interested in the HTML:

<form action="login.php" method="post" onsubmit="return checkLogin()">
<!-- code for inputs, eg username -->
<input type="submit" class="btn" value="Log In"/>
</form>
cschippe
  • 81
  • 2
  • 10

5 Answers5

6

I'd suggest preventing the event to begin with, then when you want the form to submit, do it with the native submit method since it bypasses jQuery.

var form = document.getElementById("formid");
$(form).submit(function(e){
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: "check_login.php",
        data: {
            'username': username,
            'password': password
        },
        //async: false,
        success: function (result) {
            if (result == 1) {
                $('#loginoff').html("Invalid username/password");
            } else {
                $('#loginoff').html("");
                form.submit(); // note, form is a form NODE, not a jQuery object containing a form.
            }
        }
    });

});

this also allows you to remove async: false which is ALWAYS a good thing(other than within webworkers.)

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • To the OP: See how `e` gets in there? – Sparky Jan 23 '13 at 18:22
  • Can you elaborate a bit on the 'e' that's in the function? Thus far, the way I've done it is: – cschippe Jan 23 '13 at 18:28
  • function checkLogin() { // some code to check basics // run ajax code to determine if pieces match $.ajax({ type: "POST", url: "check_login.php", data: {'username': username, 'password': password}, async: false, success: function(result) { if (result == 1) { $('#loginoff').html("Invalid username/password"); event.preventDefault(); return false; } else { $('#loginoff').html(""); return true; } } }); } } – cschippe Jan 23 '13 at 18:31
  • And in my code, what I have is:
    With this when I submit:
    – cschippe Jan 23 '13 at 18:33
  • I tried doing it this way but unfortunately had no luck. Just to test it I tried it with just some basic code inside to see if it would be able to stop the form submit but it still went through. Any other thoughts? – cschippe Jan 23 '13 at 18:51
  • 1
    Yes, remove your onsubmit="..." and use an event handler similar to mine. – Kevin B Jan 23 '13 at 19:51
  • Okay, trying this again. Just to be clear, you have 'form.submit()' at the end, is 'form' here the name of the form? Or just the actual word form? – cschippe Jan 23 '13 at 20:50
  • it's the variable that i declared at the top. – Kevin B Jan 23 '13 at 20:53
  • Made the changes but still couldn't make it work unfortunately... I'm blown away by how annoying a simple thing like this can be... – cschippe Jan 23 '13 at 20:59
  • Just by the way, I mean the situation is annoying, not you, I really appreciate your help. – cschippe Jan 23 '13 at 21:00
  • What state is it in currently? is the form still submitting wildly, or is it not submitting at all and simply doing nothing with no errors. If it's not submitting and not throwing an error, more than likely it's mostly working, we just need to debug why the ajax request is failing. – Kevin B Jan 23 '13 at 21:02
  • It just goes straight to submitting, none of the 'validations' I have in there work. I figured out that a workaround is to just take the submit button out of the form, do an 'onclick', then submit when it returns true. The downside is that you can't submit by pressing enter...but given how long I've spent on just this piece when I have lots of other things not working between browsers (it really bothers me that several SQL table updates aren't happening...) I feel like I need to take what I can get here... – cschippe Jan 23 '13 at 21:12
  • If it's submitting, then we are either close, or the submit event isn't being bound. Assuming we're close, comment out `form.submit`, does it still submit? – Kevin B Jan 23 '13 at 21:14
  • If I comment out form.submit, it still submits. Both with and without it commented out, it acts as if there is no validation function whatsoever (as if I have just clicked submit with no JS in place to clear it) – cschippe Jan 23 '13 at 21:28
  • 1
    That means the `$(form)` and `var form = ...` isn't selecting the form. Does the form have an id, and did you place it in place of `"formid"`? – Kevin B Jan 23 '13 at 21:36
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23259/discussion-between-cschippe-and-kevin-b) – cschippe Jan 23 '13 at 21:37
2

Set the console to persist the console.log. You should see a JavaScript error

e.preventDefault();  //<--trying to prevent the form from submitting

Where is e defined?

function checkLogin()  <-- No e defined

You will have an error which means the form will submit since nothing prevented it from stopping.

function checkLogin(e) {
    e = e || window.event;

and since it is not a jQuery wrapped event object, you need to do it like

$.Event(e).preventDefault();
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Thanks, this works for IE, but it's still submitting in Mozilla Firefox. Any thoughts? – cschippe Jan 23 '13 at 19:18
  • If you take the Ajax call out of the code and just call the preventDefault does it prevent it? When you set persist log on Firebug is there any errors? – epascarello Jan 23 '13 at 19:26
  • If I remove the Ajax call but keep $.Event(e).preventDefault() (after defining 'e' as you did above), it does not prevent it in Firefox. In terms of your question about the persist log, I actually have never heard of Firebug, so I don't know how to check that – cschippe Jan 23 '13 at 19:29
  • I ended up going with a workaround, shifted it to 'onclick' and put it directly into the button, then removed the button from the form, then when it returns true I do $('#formname').submit(). It's frustrating I couldn't land something that worked with what I had a bit better (since I've actually got a ton of forms with this problem now), but this was still helpful in getting me there. Thanks – cschippe Jan 23 '13 at 19:49
  • And if the user hits the enter key in a textbox on your form what happens? – epascarello Jan 23 '13 at 19:51
  • ...Nothing. I guess that's a problem. Any thoughts on how to make it work with Firefox? – cschippe Jan 23 '13 at 20:44
0

In addition to the ajax issues mentioned by others, IE8 doesn't do preventDefault().

PreventDefault alternative for IE8

(event.preventDefault) ? event.preventDefault() : event.returnValue = false; 
Community
  • 1
  • 1
isherwood
  • 58,414
  • 16
  • 114
  • 157
  • 2
    He's using jQuery and that takes care of this. Since jQuery is IE8 compatible, `preventDefault()` will work in IE8 as long as jQuery is used. – Sparky Jan 23 '13 at 18:15
  • jQuery normalizes this, assuming the event is a jQuery bound event, this wouldn't be an issue. However, we of course can't see that part of the code so you may be right. – Kevin B Jan 23 '13 at 18:16
  • I'm afraid I tried this and it still fires the submission (after clearly returning 1, as it prints "Invalid username/password"). Any other thoughts on this? – cschippe Jan 23 '13 at 18:24
0

Unfortunately I was unable to do as I had hoped in the title as I could never successfully prevent the submit in all four browsers (Mozilla was a persistent holdout).

What I ended up doing, then, was the following:

1.) In my HTML, I changed the boundaries of the so that it only contained the inputs, but the 'Submit' button was OUTSIDE of

2.) Then, instead of have like I had, I moved "return checkLogin()" down to the submit button (now outside of the form) and changed it to 'onclick'.

3.) This way, I didn't need any preventDefault() as there was no default to occur. I simply went to the ajax request, and in the 'return true' case, set it to do $('#mainform').submit();

Note: By doing this, I was also able to make the ajax request no longer asynchronous, which everyone says is good (I'm still new so not as sure of its importance).

Hopefully this helps anybody who comes across the same issue.

cschippe
  • 81
  • 2
  • 10
0

I eventually figured out how to make it work in general:

in the section, the function should be written as:

Note the 'event' as an input for checkLogin

Then the function I used is below. Key changes are a.) preventing the default submission at the start (note, $.Event(e) is necessary or else it won't work in IE), b.) defining the form using getElementById, c.) submitting the function using form.submit(). Hopefully people find this helpful.

function checkLogin(e)
{
var form = document.getElementById("mainloginform");
$.Event(e).preventDefault();

// set error counter
var counter = 0;
var username = $('#loginusername').val();
var password = $('#loginpassword').val();

// check that username is not blank
 if (username==null || username=="")
{
    $('#usernameoff').html("Must enter your username");
    counter++;
}
else
{
    $('#usernameoff').html("");
}

// check that password is not blank
 if (password==null || password=="")
{
    $('#passwordoff').html("Must enter your password");
    counter++;
}
else
{
    $('#passwordoff').html("");
}

// if counter zero at this point, return false, else return true
if (counter > 0)
{
    return false;
}
else
{
    $.post("check_login.php", {'username': username, 'password': password}, function(result)
    {
        if(result == 1)
        {
            $('#loginoff').html("Invalid username/password");
            return false;
        }
        else
        {
            $('#loginoff').html("");
            form.submit();
            return true;
        }
    });
}
}
cschippe
  • 81
  • 2
  • 10