1

I am trying to get a basic AJAX form working. I want to get a line of text to display upon success of a PHP form through AJAX, but on submission of the form I am just directed to the PHP file. Can anyone identify the problem to make the text appear on the same page upon login success?

Code is below:

HTML JS PHP

in order:

$(document).ready(function() {
    $(".loginform").submit(function () {
        var username = $('input[id=username]').val(); 
        var password = $('input[id=password]').val(); 
        $.ajax({
            type: "POST",
            url: "login.php",
            data : "username="+username+"&password="+password,
            type: "POST",
            success: function (data) {
                var success = data['success'];
                if(success == false){
                    var error = data['message'];
                    alert(error);
                }
                if(success == true) {
                    $('#result').write('Login success! Loading dashboard...');                                
                }
            }
        });           
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
Please log in:

<form name="loginform" class="loginform" method="post" action="login.php">
Username: <input name="username" id="username" /><br />
Password: <input name="password" id="password" /><br />
<input name="submit" type="submit" />
</form>
</p>

<p>
<div id="result">

</div>
</p>
Styphon
  • 10,304
  • 9
  • 52
  • 86
Kaostherom
  • 13
  • 2

4 Answers4

1

Check this similar one: event.preventDefault doesn't seem to work

TLDR Answer: You have to just return false; to prevent PHP form submission in the callback for the onSubmit event:


For Code Improvement:

Please use correct indentation for better clarity and feel free to follow the comments for some suggestions of improvement ;). Let me know if you need any more clarifications :)

JQuery:

$(document).ready(function() {
      $(".loginform").submit(function (event) {
           // the proper way would be
           //var username = $('input#username').val(); 
           //var password = $('input#password').val(); 
           var username = $('input[id=username]').val(); 
           var password = $('input[id=password]').val(); 
           $.ajax({
                 type: "POST",
                 url: "login.php",
                 //based on michael's post it should be
                 //data: {username: username, password: password},
                 data : "username="+username+"&password="+password,
                 //type: "POST", <-- not needed based on michael's post
                 success: function (data) {
                       var success = data['success'];
                       //probably needs to be success==="false" and I suggest 
                       //not to use success name again in there..
                       if(success == false){ 
                           var error = data['message'];
                           alert(error);
                        }
                        // probably should be just else{ or else if(success==="true")
                        // I would check it first in the if because usually you will  
                        // have a success more often than a failure
                        if(success == true) {  
                             //based on Styphon's answer there is no write so it  should be  
                             //one of: append(element), prepend(element), text("content") or html("content")
                             $('#result').write('Login success! Loading dashboard...');                                
                        }
                 }

           });  
           // return false is like calling event.preventDefault(); and event.stopPropagation(). 
           //As such prevents redirection to PHP/Server code */ or in other words it WON'T 
           //submit the form to PHP using the name=" " input attributes 
           //and method=" "/action=" " attributes in your form tag
           return false;        
      });
});

HTML

If you are submitting the form only through AJAX and not the old way then you only need whatever I have below. Some suggestions:

  • don't use <br/> use css positioning
  • alternatively you could use <button class="someclass">value</button> instead of <input type="submit"/> and in javascript you would do $("button.someclass").click(function(event){ blabla }) instead of $(".loginform").submit(function(event){blabla}); but don't forget return false;
<p>
Please log in:
<form class="loginform">
    Username: <input id="username" /><br /> 
    Password: <input id="password" /><br />
    <input name="submit" type="submit" class="someclass" />  
</form>
</p>

<p>
<div id="result">

</div>
</p>

PHP:

IMPORTANT: Never store passwords in plain text in your database (e.g for production). Use some hashing (MD5/SHA-1) and compare the user's input hashed with what it is in the database hashed (See for details: How do I create and store md5 passwords in mysql). Btw even that is not enough and you need to also use Salting before hashing..

e.g:

$hashedpass = hash('sha256', $pass);
$query = "select * from user where name = '$escapedName' and password = '$hashedpass'; ";
Community
  • 1
  • 1
Michail Michailidis
  • 11,792
  • 6
  • 63
  • 106
  • No matter how much it hurts you not to, recommendations that are this much out of the scope of the question shouldn't go into an answer :( Maybe a comment on the original question instead. – yerforkferchips Oct 24 '14 at 20:59
  • 1
    meh - I put a TLDR .. and I disagree. It is important to give good suggestion so less bad code is being reinforced through sharing..I think this what codereview is trying to do but is beta. I separated it a bit more - so now scrolling shouldn't be a problem..we are not lazy :) – Michail Michailidis Oct 24 '14 at 21:02
  • 1
    I separated it a bit more - so now scrolling shouldn't be a problem..we are not lazy :) - I couldn't fix all the syntax issues on the previous comment :P but oh well – Michail Michailidis Oct 24 '14 at 21:08
1

You need to return false to prevent form from submitting. Also, you have declared type: "POST" two times and the data looks more like a $_GET request. I've changed the code below.

$(document).ready(function() {
        $(".loginform").submit(function () {
            var username = $('input[id=username]').val();
            var password = $('input[id=password]').val();
            $.ajax({
                type: "POST",
                url: "login.php",
                data : {
                    username : username,
                    password: password
                },

                success: function (data) {
                var success = data['success'];
                    if(success == false){
                        var error = data['message'];
                        alert(error);
                    }
                    if(success == true) {
                        $('#result').write('Login success! Loading dashboard...');
                    }
                }

            });
            return false;
        });
    });
baao
  • 71,625
  • 17
  • 143
  • 203
  • +1 for the correct format of data in POST compared to OP's that looks like serialized data for GET request – Michail Michailidis Oct 23 '14 at 15:17
  • @Kaostherom did you even check my answer :( ? I easily put 2h in it with more than 15+ edits .. it is not about getting the right code to capy/paste it but learn and fix a lot of issues on top of that – Michail Michailidis Oct 27 '14 at 15:57
0

The problem is you're not stopping the form from submitting, so after it runs the Ajax the form goes on to submit like a normal form. To stop this just return false at the end of your function.

$(document).ready(function() {
    $(".loginform").submit(function () {
        var username = $('input[id=username]').val(); 
        var password = $('input[id=password]').val(); 
        $.ajax({
            type: "POST",
            url: "login.php",
            data : "username="+username+"&password="+password,
            type: "POST",
            success: function (data) {
                var success = data['success'];
                if(success == false){
                    var error = data['message'];
                    alert(error);
                }
                if(success == true) {
                    /* There is no .write function, you either want .append() to 
                    add text on to the end, or to replace the contents .text() 
                    or .html(). In this case I would use .text() */
                    $('#result').text('Login success! Loading dashboard...');
                }
            }
            return false; /* <-- returning false here stops the form submitting. */
        });           
    });
});
Styphon
  • 10,304
  • 9
  • 52
  • 86
  • Maybe that's because I was busy formatting all his code, not to mention you failed to explain ***why*** you need to return false. People learn more if you explain why they need to do something rather than just giving them the answer. – Styphon Oct 23 '14 at 14:31
  • You bet I had said that return false; means calling event.preventDefault(); and event.stopPropagation(), I just didn't have a comment for that.. You can see that in the link I posted which is also my accepted answer.. On top of that I talked about data format the if conditions and the duplicate type="POST" – Michail Michailidis Oct 23 '14 at 14:33
  • But neither your answer nor the link explains why, that after the ajax runs the form still submits and that using return false stops that. – Styphon Oct 23 '14 at 14:35
  • That's just you it clearly says that.. in both the post and link .. and i believe you are wrong the ajax DOESN'T even submit .. the default params and name properties based on the METHOD and ACTION of form tag are being submitted ;) – Michail Michailidis Oct 23 '14 at 14:36
  • 1
    In addition, @MichailMichailidis, you mentionend the duplicate POST and data format after you've seen it in my answer... But never mind. Hope he will accept yours ;-) – baao Oct 23 '14 at 14:36
  • I will give you credit @michael my bad ;) +1 for that – Michail Michailidis Oct 23 '14 at 14:37
  • @MichailMichailidis I don't know whether there is a language barrier here or not, but you are wrong sir. Neither your post nor the linked post explain that the form will continue to submit after the function has finished running. – Styphon Oct 23 '14 at 14:40
  • "As such prevents redirection to PHP/Server code" - I believe the OP knows what form submission is as he is calling `.submit(function(){});` Pff.. anyway I made it even more explicit – Michail Michailidis Oct 23 '14 at 14:43
  • @MichailMichailidis That still doesn't tell the user it stops the original form submitting. If you're unaware that the form is still submitting your comment is clear. Not to mention you added it after I had already posted my answer. – Styphon Oct 23 '14 at 14:45
  • you mean reposted and I gave you a credit - you forget that you posted 7 minutes after I had given a correct answer but you keep complaining about other minor things – Michail Michailidis Oct 23 '14 at 14:51
  • @MichailMichailidis I could post 7 days after you posted a correct answer if I think it's incomplete and my answer adds something. That's how SO works... – Styphon Oct 23 '14 at 14:59
  • You are too selfish and I thought SO is a friendly community - I have more important things to do - I stop here – Michail Michailidis Oct 23 '14 at 15:01
  • I'm far from selfish, I give my time to help people on here, far more than you do! – Styphon Oct 23 '14 at 18:13
  • I just started being active even though I am a member for 3 years.. see I have 15+ edits for my last post you have just 2..I care too you are not the one special in SO. I said you are selfish having the argument "I posted a question that adds something" compared to mine that adds about ten plus yours and you are complaining about that tiny thing that I would have seen either way since I am writing code for 16 years (since age 12) which I gave you credit for and I didn't down vote you just cause.. – Michail Michailidis Oct 24 '14 at 14:17
0

This might not be your problem, but FWIW:

In your ajax code block, you are posting the data to login.php. You have not mentioned the name of the page on which your ajax source code resides -- if it is login.php, then you will get the behaviour you are describing.

By design, AJAX should post to an external (separate) PHP file. There is a way to post AJAX to the same page, but it requires configuration (ask Felix Kling, he knows how to do it).

See this answer for more information.

values not updated after an ajax response

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111