Reputation: 2436
I am trying to insert a record into MySQL database using HTML form. I am using AJAX to call web services in Java. But it is not working. It gives an alert saying false. When I tried with POSTMAN it works fine. But using AJAX it's not working. Can anybody help me? Thanks in advance.
Code in Add.jsp
<body>
<form id="submit">
Username:<br>
<input type="text" name="username"><br>
Email:<br>
<input type="email" name="email"><br><br>
Password:<br>
<input type="text" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "http://localhost:8080/WebService/webresources/users/insert",
data: formToJSON(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
alert('Success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Error: ' + textStatus);
}
});
});
});
function formToJSON()
{
return JSON.stringify
({
"username": $('#username').val(),
"email": $('#email').val(),
"password": $('#password').val()
});
};
</script>
Code in Service
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/insert")
public boolean insertUsers(String content)
{
Gson g = new Gson();
Users u = (Users) g.fromJson(content, Users.class);
UsersDAO dao = new UsersDAO();
return dao.insertUsers(u);
}
Upvotes: 2
Views: 1117
Reputation: 853
You have to add id
for all the input fields.
Try this.
<body>
<form id="submit">
Username:<br>
<input type="text" id="username" name="username"><br>
Email:<br>
<input type="email" id="email" name="email"><br><br>
Password:<br>
<input type="text" id="password" name="password"><br><br>
<button id="submit">Save</button>
</form>
</body>
And in this, You have to change this,
$("#submit").submit(function(event)
into this,
$("#submit").click(function(event)
Upvotes: 1