I'm trying to build a simple AJAX POST. It consists of a username and a password. The username element in my html remains undefined after the user has submitted the data. What could be the problem. Here is my code.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#form").bind('click', function (event) {
alert(username = $("#username").val())
event.preventDefault();
$.post("/main3/",
username = $("#username").val(),
function (data) {
alert(data);
$('#content').html(data)
})
return false;
});
});
</script>
</head>
<body>
<form id="form">Name
<input type="text" name="username" />
</br>Age
<input type="text" name="age" />
</br>
<input type="submit" />
</form>
<div id="content"></div>
</body>
I have included the whole page for reference. My server is Django.
You are passing the parameter incorrectly, pass it as an object, and use a correct selector for the element you want to select to get its value (there is no element with id username)
$.post("/main3/", {username: $("[name=username]").val()},
You do not have an element with an id of username
in your code. You have an input element which has a NAME of username
. name is not the same as id.
<input type="text" id="name" name="name" />
^^^^^^^^^^--missing