I am populating a list of names that will be added to my Sql Database. In this simple case, how do I send the information to SQL server without my page being refreshed?
<script type="text/javascript">
function addNewRow() {
$('#displayPropertyTable tr:last').after('<tr><td style="font-size:smaller;" class="name"></td><td style="font-size:smaller;" class="address"></td></tr>');
var $tr = $('#displayPropertyTable tr:last');
var propertyCondition = $('#txtPropAddress').val();
if (propertyCondition != "") {
$tr.find('.name').text($('#txtPropName').val());
$tr.find('.address').text($('#txtPropAddress').val());
}
}
</script>
...
<table id="displayPropertyTable" width= "100%">
<tr>
<td style="font-size:smaller;" class="name"></td>
<td style="font-size:smaller;" class="address"></td>
</tr>
</table>
...
<table>
<tr>
<td><b>Name</b></td>
<td colspan="2"><input id="txtPropName" type="text" /></td>
</tr>
<tr>
<td><b>Address</b></td>
<td colspan="2"><input id="txtPropAddress" type="text" /></td>
</tr>
</table>
...
<button onclick="addNewRow();">Add</button>
Using AJAX via JQuery’s
getJSON()is a method I use a lot.getJSON()is a wrapper for theajax()method I believe.Here’s an example of JS Method that serializes the form data and does an ajax request passing the serialized data.
If successful in this case you can pass back a Json Object. In my example I simply pass back a string that says “Success”. So you will see an alert box now displaying Success in it, for my simple example.
In you controller here’s an example of an Action to use for AJAX
Your data comes in serialized as a linear string so you will have to parse it, which is pretty easy. Then take the data and do your respective database logic. Then return a Json Object.