Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I connect to SQL from JavaScript MVC?

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>
like image 276
MrM Avatar asked Jul 14 '26 04:07

MrM


1 Answers

Using AJAX via JQuery's getJSON() is a method I use a lot. getJSON() is a wrapper for the ajax() 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.

function addRowsViaAJAX() {

    var d = new Date(); // IE hack to prevent caching

    $.getJSON('/ControllerName/ActionName', { Data: $('#MyForm').serialize(), Date: d.getTime() }, function(data) {
        // callback on success
        alert(data);
    }, 'json');
}

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.

public virtual JsonResult ActionName(string data)
{
   // take the data and parse the linear stream... I like to use the FormCollection
   FormCollection collection = new FormCollection();

   foreach (string values in data.Split('&')){
     string[] value = values.Split('=');
     collection.Add(value[0], value[1]);
   }
   // Now do your database logic here
   return Json("Success");
}
like image 79
Gabe Avatar answered Jul 18 '26 00:07

Gabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!