2
votes

I`m trying to make somethig like login with jquery. There should be a validation on text fields to echo error message. If the form is completely validated then function in jquery should update the div, where there is the input form and change it to the session name. But There is a problem, when posted form is validated then div remains empty, there is no session name.

HTML:

<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
    jQuery('#form').submit(function(){
        jQuery.ajax({
            type: 'POST',
            url: jQuery('#form').attr('action'),
            data: jQuery('#form').serialize(),
                success: function(data){
                    if(data == 'success'){ 
                        jQuery('#user').load(location.href+' #user>*');
                    }else{
                        jQuery('#info').html(data);
                    }                   
                }
        });
        return false;
    });
});
</script>
</head>
<body>
<div id="user">
<div id="info"></div>
<?php
session_start();
if(isset($_SESSION['user'])){
echo $_SESSION['user'];
}else{
echo '
<form method="post" action="session.php" id="form">
<input type="text" name="user" />
<input type="submit" name="do" value="ok" />
</form>
';
}
?>
</div>
</body>
</html>

PHP:

<?php

$user = mysql_real_escape_string($_POST['user']);

if(empty($user)){
    echo 'psc';
}else{
    echo 'success';
    session_start();
        $_SESSION['user'] = $user;
}



?>
1

1 Answers

0
votes

I think type: 'POST' in your ajax call is usually done in lower case: type: 'post'. I am not sure if this is the issue, but you may want to try it.

Aside from that, the other problem with your code is that you are not preventing the form from being submitted. So basically you are sending an ajax message, but then immediately loading a new page with the default submit that occurs when clicking the submit button. I would think that this has the effect of loading a blank page?

To fix this you could add to your submit handler the following lines:

jQuery('#form').submit(function(event){
   event.preventDefault();

Notice I have added event to the handlers arguments, and then called the preventDefault() method to stop the form from actually submitting. Returning false in the handler does not do this for you.