Bhushan
Bhushan

Reputation: 364

Getting unexpected result with jquery ajax post method from php script

This is my form from which i am expecting post results in my div id="response"

<!DOCTYPE html>
<html>
<head>
<title>AJAX POST</title>
<script src="jquery.js"></script>
<script>
    $(document).ready(function(){
        $('input[name="submit"]').click(function(){
            var username=$('input[name="username"]').attr("value");
            var password=$('input[name="password"]').attr("value");
            var data1=encodeURIComponent(username);
            var data2=encodeURIComponent(password);
            $.post("response.php",{username:data1,password:data2},function(data){
            $("#form").hide();
            $("#response").text(data);
            });
        });
    });
</script>
</head>
<body>
<div id="form">
<form action="response.php" method="post">
<input type="text" name="username" value=""/><br/>
<input type="password" name="password" value=""/><br/>
<input type="button" name="submit" value="submit"/>
</form>
</div>
<div id="response"></div>
</form>
</body>
</html>

This is my server side script

<?php
echo $_POST["username"]."<br/>";
echo $_POST["password"];
?>

After filling the form and clicking the submit button the response that i get is "<br/>" I don't understand this.Please explain.

Upvotes: 0

Views: 415

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

To get the input value you need to use .val() not .attr('value'). .attr('value') will return the value of the attribute which is ''(empty string) here

var username=$('input[name="username"]').val();
var password=$('input[name="password"]').val();

Upvotes: 4

Related Questions