I am working with grails, in springsource tool suite, and I am facing a problem updating the SQL databse. In the page, the user is asked to enter details of his property, say address, city etc., and once clicking on button ‘save’ the details need to be saved in the database. Now what I need to do is, dynamically add the input fields (of address, city, etc) to the page, everytime the user clicks on button ‘add’. So because of this, i need to use AJAX to post the data to the server. However, I am having trouble updating it. Here is the code of the view(.gsp file)-
<head>
<script type="text/javascript">
var rad1, rad2, button1, button2;
function add() {
var newP = document.createElement("p");
var input1, input2,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "text";
input1.placeholder = "street";
input1.id = "address";
newP.appendChild(input1);
input2 = document.createElement("input");
input2.type = "text";
input2.placeholder = "city";
input2.id = "city"
newP.appendChild(input2);
area.appendChild(newP);
}
</script>
</head>
<body>
<form name='prop' method="post" action="save">
<g:hiddenField name="owners.id" value="${session.user.id }" />
<input type="button" value="+Add" onclick= "add();" ><br>
<input type="button" name="create" id="save_button" class="save" value="save" />
</form>
<script type="text/javascript" src="ajax.js"></script>
</body>
Here is what my Ajax code looks like in a separate ajax.js file-
$('#save_button').click(function() {
var street = $('#address').val();
var city = $('#city').val();
$.ajax({
type: "POST",
url: "${createLink(controller: 'property', action: 'save')}",
data: { address: street, city: city },
success: function(data) {
alert(data);
}
});
});
And here is the code in my property controller(save action)-
def save = {
def propertyInstance = new Property(params)
if (propertyInstance.save(flush: true)) {
flash.message = "Property successfully added."
redirect(controller:"user", action: "show", id:params.owners.id)
}
else {
render(view: "create", model: [propertyInstance: propertyInstance, id:params.owners.id])
}
}
What am I doing wrong here? I am not at all familiar with Ajax, so sorry if its an obvious mistake.. please help.
$('#address').val();and$('#city').val();will get you the value of the first#addressor#cityelement jQuery finds. If you want to make, let’s say, an array for all the address and city values provided you could do this:If there’s two address and city inputs on the page, the result will look something like this:
Edit: To reset the fields on submission (or “add” if you change the jQuery selector), you could do this: