I'm new in ASP.NET CORE, and I'm trying to send data from dynamically created input fields to Controller - ajax

$("#addRow").click(function ()
{
#{
new VLSM_Model().LansValues.Add(new Lans());
}
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
html += '<input type="number" id="[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $(this).serializeArray();
$.ajax(
{
type: "POST", //HTTP POST Method
url: "VLSM_Controller/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br/>
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br/>
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br/>
<div class="form-group">
<input type="submit" value="Calculate VLSM" class="btn btn-info" id="createButton"/>
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
I created dynamically input fields as you can see from code, but I have difficulties to pass the data to controller, and to use the data for calculations inside the controller.
My question is how to pass data from dynamically created input fields with ajax to controller and how to use passed data for any kind of calculations.

Model binding system will look through the property by name. So you need match the name attribute in html with model property name. That is to say, your dynamic added input fields should have name attribute:name="LansValues[index].InitialLanValues".
Here is a whole working demo:
Model:
public class VLSM_Model
{
public string IP_Address { get; set; }
public List<Lans> LansValues { get; set; }
public int cidrValue { get; set; }
}
public class Lans
{
public int InitialLanValues { get; set; }
}
View:
Modify type="submit" to type="button", otherwise the ajax will not hit.
#model VLSM_Model
<h1>VLSM CALCULATE</h1>
<hr />
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group" style="width: 35%">
<label asp-for="IP_Address" class="control-label"></label>
<input asp-for="IP_Address" class="form-control" />
<span asp-validation-for="IP_Address" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<div id="inputFormRow" style="width: 35%">
<div class="input-group mb-3">
<br />
<div class="input-group-append"></div>
</div>
</div>
<div id="newRow">
<input type="hidden" id="totalLans" value="0" />
</div>
<button id="addRow" type="button" class="btn btn-info">Add Network</button>
</div>
<span asp-validation-for="LansValues" class="text-danger"></span>
<br />
<div class="form-group" style="width: 35%">
<label asp-for="cidrValue" class="control-label"></label>
<input asp-for="cidrValue" class="form-control" />
<span asp-validation-for="cidrValue" class="text-danger"></span>
</div>
<br />
<div class="form-group">
#*change here*#
<input type="button" value="Calculate VLSM" class="btn btn-info" id="createButton" />
</div>
</form>
<div>
<a asp-action="VlsmResult">Back to List</a>
</div>
JS:
Change the dynamic html to name="LansValues[' + (rowCount - 1) + '].InitialLanValues" and change var inputData = $(this).serializeArray(); to var inputData = $('form').serializeArray();.
#section Scripts
{
<script>
$("#addRow").click(function ()
{
#*#{new VLSM_Model().LansValues.Add(new Lans());}*#
var rowCount = parseInt($("#totalLans").val());
rowCount++;
$("#totalLans").val(rowCount);
var html = '';
html += '<div id="inputFormRow" style="width: 35%">';
html += '<div class="input-group mb-3">';
//change id attribute to name attribute and modify the name
html += '<input type="number" name="LansValues[' + (rowCount - 1) + '].InitialLanValues" class="form-control m-input" placeholder="Enter number of Hosts" autocomplete="off" style="width: 30%" required>';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger" style="margin-right: 5px">Remove Network</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
$(document).on('click', '#removeRow', function ()
{
var rowCount = parseInt($("#totalLans").val());
rowCount--;
$("#totalLans").val(rowCount);
$(this).closest('#inputFormRow').remove();
});
$(document).ready(function () {
$("#createButton").click(function ()
{
var inputData = $('form').serializeArray(); //change here...
$.ajax(
{
type: "POST", //HTTP POST Method
url: "Home/Create", // Controller/View
data: inputData,
success : function(response) {
console.log(response)
}
});
});
});
</script>
}
Controller:
public class HomeController : Controller
{
[HttpPost]
public IActionResult Create(VLSM_Model model)
{
//...
}
}
Note:
Actually if you just use form submit, it also can work well. If you use form submit, just change your original code:name="LansValues[' + (rowCount - 1) + '].InitialLanValues" in $("#addRow").click() function. Then remove the $("#createButton").click() function. No need change any other code.

Related

Cannot save value using ajax in laravel

I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());

Core MVC 2 and Ajax wrong data type

I apologize for the subject topic too general, I have difficulties with Ajax work at all, I'm not able to sent/get up any response. The topic is probably duplicated, but I do not see the error in my code. All tutorials I found say the same thing but it still dont work for me, please take a look.
View
#model ValueTypeEditViewModel
#{
ViewBag.Title = "Dodaj Wartość";
Layout = "_AdminLayout";
}
<div class="col">
<form asp-action="EditValue" method="post">
<input type="hidden" asp-for="ValueType.ValueId" />
<input type="hidden" asp-for="ValueType.TypeId" />
<div class="form-group">
<label asp-for="ValueType.Value" class="m-1"></label>
<div><span asp-validation-for="ValueType.Value" class="text-danger"></span></div>
<input asp-for="ValueType.Value" class="form-control" />
</div>
#if (Model.IsSysParam)
{
<div class="form-group">
<label asp-for="ValueType.Controller" class="m-1"></label>
<div><span asp-validation-for="ValueType.Controller" class="text-danger"></span></div>
<input asp-for="ValueType.Controller" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Code" class="m-1"></label>
<div><span asp-validation-for="ValueType.Code" class="text-danger"></span></div>
<input asp-for="ValueType.Code" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ValueType.Description" class="m-1"></label>
<div><span asp-validation-for="ValueType.Description" class="text-danger"></span></div>
<textarea asp-for="ValueType.Description" class="form-control"></textarea>
</div>
<div class="form-group">
<label asp-for="ValueType.IsSysParam" class="m-1"></label>
<div><span asp-validation-for="ValueType.IsSysParam" class="text-danger"></span></div>
<input type="checkbox" asp-for="ValueType.IsSysParam" class="form-control" />
</div>
}
#if (Model.ValueType.ValueId != 0)
{
<div class="form-group">
<label asp-for="ValueType.CreateDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.CreateDate</label>
</div>
<div class="form-group">
<label asp-for="ValueType.EditDate" class="m-1"></label>
<label class="m-1">#Model.ValueType.EditDate</label>
</div>
}
#*#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
#*<form method="post">
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
</form>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}*#
<div class="text-left">
<button class="btn btn-primary mt-1" type="submit">Zapisz</button>
</div>
</form>
<form asp-route="#(Model.IsSysParam ? RouteUrl.Name.SystemList : RouteUrl.Name.CategoryList)" method="post">
<div class="text-left">
<input type="hidden" name="isSysParamCategory" value="#Model.IsSysParam.ToString()" />
<button class="btn btn-secondary btn mt-1">Anuluj</button>
</div>
</form>
<form method="post">
#if (!Model.IsSysParam)
{
<div class="row">
<div class="col-5">
<select id="lbProducts" class="form-control" asp-items="Model.Products" size="#Model.ListBoxSize" multiple></select>
<label class="m-1">Lista Przedmiotów</label>
</div>
<div class="col-1 align-self-center">
<div class="d-flex justify-content-center">
<button id="addItems" class="btn btn-light mt-1" type="button"><i class="fa fa-long-arrow-right" aria-hidden="true"></i></button>
</div>
</div>
<div class="col-5">
<select id="lbAddedProducts" class="form-control" size="#Model.ListBoxSize" multiple></select>
<button asp-page-handler="saveValueItems" id="saveValueItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-floppy-o" aria-hidden="true"></i></button>
<button id="removeItems" class="btn btn-primary mt-1" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
</div>
}
</form>
</div>
At View you can see comented code started with - '#if (!Model.IsSysParam)'. Firstly I tried to fire Ajax from 'main' from with asp-page-handler="saveValueItems" at button. Then I added nested form in form with post (there is commented too), in the end I tried to created separeted form in the bottom of example. (by the way, I'm a beginner with mvc and don't really know if I can nesting form in form)
All the time I get the same error
Ajax
$(saveValueItems).click(function () {
var data = [];
var addedItems = $(addedItemList).find('option');
for (var i = 0; i < addedItems.length; i++) {
var item = addedItems[i];
data.push($(item).val());
}
$.ajax({
type: "POST",
url: "/admin/category/editvalue/96/35?handler=saveValueItems",
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('spoko');
},
failure: function (response) {
alert(response);
}
});
})
I hardcoded url to be sure I send request to good action. I have this in mind to test only with this one item/values.
Controller
[ValidateAntiForgeryToken]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "editvalue/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValueAjax)]
public ActionResult OnPostSaveValueItems([FromBody] int[] arrValueItems)
{
string test = "Hello Response Back";
return new JsonResult(test);
}
Startup.cs
I added to Startup.cs ValidateAntiForgeryToken before AddMvc() too
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
services.AddMvc();
Question:
I do not understand why I am sending the wrong data type. I want to send an int table and I receive a message that I'm sending ValueType and the view is expecting ValueTypeEditViewModel.
I do not know where to look for the cause of the error
1 Edit:
All actions for edit page
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.SystemCreateValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}", Name = RouteUrl.Name.CategoryCreateValue)]
public ViewResult CreateValue(int typeId, bool isSysParamCategory)
{
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(typeId, isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpGet]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public ViewResult EditValue(int typeId, int valueId)
{
bool isSysParamCategory = repository.GetCategoryByTypeId(typeId).IsSysParam;
return View(RouteUrl.Edit + RouteUrl.Value, new ValueTypeEditViewModel(repository.GetValue(typeId, valueId), isSysParamCategory, repositoryProduct.Products, Convert.ToInt32(repository.GetSysParamByCode(SysParams.ProductListBoxSize))));
}
[HttpPost]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.System + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.SystemEditValue)]
[Route(RouteUrl.Admin + RouteUrl.Slash + RouteUrl.Category + RouteUrl.Slash + "[action]/{typeId?}/{valueId?}", Name = RouteUrl.Name.CategoryEditValue)]
public IActionResult EditValue(AureliaCMS.Models.ValueType valueType)
{
if (ModelState.IsValid)
{
repository.SaveValueType(valueType);
return View(RouteUrl.Save, new SaveCategoryType(repository.GetCategoryByTypeId(valueType.TypeId).IsSysParam, valueType.Value, false));
}
else
{
return View(valueType);
}
}

insert data from dynamic inputs to database in codeigniter

everyone.
I'm beginner in CodeIgniter, I trying to insert data from dynamic input to database, I searched too much but I got nothing so far
my model is empty till now because I don't know how to insert data from dynamic inputs
This is my view
<form id="bookForm" method="post" class="form-horizontal"action="order/insert">
<div class="form-group">
<div class="col-xs-3">
<label for="customer_name">Customer :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="customer_name" id="customer_name">
<?php foreach ($customerdata as $c):
echo "<option value ='$c->c_id'>" . $c->c_name . "</option>";
endforeach;
?>
</select>
</label>
</div>
<div class="col-xs-3">
<label for="invoice_number">Invoice Number :
<input type="text" class="form-control" name="invoice_number" id="invoice_number" placeholder="Invoice Number"/>
</label>
</div>
<div class="col-xs-3">
<label for="branch">Branch :
<input type="text" class="form-control" name="branch" id="branch" placeholder="Branch"/>
</label>
</div>
<div class="col-xs-3">
<label for="payment_term">Payment Term :
<br>
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="payment_term" id="payment_term">
<option id-="cash">Cash</option>
<option id-="bank">Bank</option>
<option id-="other">Other</option>
</select>
</label>
</div>
<br>
<br><br><br><hr>
<label class="col-xs-1 control-label">Product</label>
<div class="col-xs-4">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="product[0].title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="product[0].qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="product[0].price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default addButton"><i class="fa fa-plus"></i></button>
</div>
</div>
<!-- The template for adding new field -->
<div class="form-group hide" id="bookTemplate">
<div class="col-xs-4 col-xs-offset-1">
<select class="selectpicker" data-show-subtext="true" data-live-search="true" name="title">
<?php
foreach($order as $row):
echo"<option value ='$row->p_id'>".$row->p_name. "</option>";
endforeach;
?>
</select>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" name="qty" placeholder="Quantity" />
</div>
<div class="col-xs-2">
<input type="text" class="form-control" name="price" placeholder="Price" />
</div>
<div class="col-xs-1">
<button type="button" class="btn btn-default removeButton"><i class="fa fa-minus"></i></button>
</div>
</div>
<div class="form-group">
<div class="col-xs-5 col-xs-offset-1">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
This Jquery
<script>
$(document).ready(function() {
var titleValidators = {
row: '.col-xs-4', // The title is placed inside a <div class="col-xs-4"> element
validators: {
notEmpty: {
message: 'Product is required'
}
}
},
isbnValidators = {
row: '.col-xs-4',
validators: {
notEmpty: {
message: 'Quantity is required'
}
}
},
priceValidators = {
row: '.col-xs-2',
validators: {
notEmpty: {
message: 'Invoice Number is required'
},
numeric: {
message: 'The invoice number must be a numeric number'
}
}
},
bookIndex = 0;
$('#bookForm')
.formValidation({
framework: 'bootstrap',
icon: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
'product[0].title': titleValidators,
'product[0].qty': isbnValidators,
'product[0].price': priceValidators
}
})
// Add button click handler
.on('click', '.addButton', function() {
bookIndex++;
var $template = $('#bookTemplate'),
$clone = $template
.clone()
.removeClass('hide')
.removeAttr('id')
.attr('data-book-index', bookIndex)
.insertBefore($template);
// Update the name attributes
$clone
.find('[name="title"]').attr('name', 'product[' + bookIndex + '].title').end()
.find('[name="qty"]').attr('name', 'product[' + bookIndex + '].isbn').end()
.find('[name="price"]').attr('name', 'product[' + bookIndex + '].price').end();
// Add new fields
// Note that we also pass the validator rules for new field as the third parameter
$('#bookForm')
.formValidation('addField', 'product[' + bookIndex + '].title', titleValidators)
.formValidation('addField', 'product[' + bookIndex + '].qty', isbnValidators)
.formValidation('addField', 'product[' + bookIndex + '].price', priceValidators);
})
// Remove button click handler
.on('click', '.removeButton', function() {
var $row = $(this).parents('.form-group'),
index = $row.attr('data-book-index');
// Remove fields
$('#bookForm')
.formValidation('removeField', $row.find('[name="product[' + index + '].title"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].qty"]'))
.formValidation('removeField', $row.find('[name="product[' + index + '].price"]'));
// Remove element containing the fields
$row.remove();
});
});
This is my controller
function OrderNow(){
$this->load->model('Out_m');
$this->Out_m->outs();
$this->session->set_flashdata('done','Your Order Submitted Successfully');
redirect('Order', 'refresh');
}
Just validate your form input however you see necessary:
$this->load->library('form_validation');
$this->form_validation->set_rules('branch', 'Branch', 'required|trim');
Make sure your form validation doesn't fail.
if ($this->form_validation->run() === FALSE) {
// Throw some error or whatever
} else {
$form_data = array('branch'=>set_value('branch');
}
Then chuck that over to the model:
$this->Out_m->handling_function($form_data);
Once you get it over there, you can do whatever you want with it.

My ajax function failed to store data into sql server

I have a JQuery login/register modal in my mvc web application and I'm trying to store the new user in the simplest form at this stage, so now I know that I must use Ajax to send the information to the server but something is wrong and it is not working
so here is my modal:
<!--Signin/Signup container-->
<div id="modal" class="popupContainer" style="display:none;">
<section class="popupBody">
<!-- Social Login -->
<div class="social_login">
<div class="">
<a href="#" class="social_box fb">
<span class="icon"><i class="fa fa-facebook"></i></span>
<span class="icon_title">سجل عن طريق الفيس بوك</span>
</a>
<a href="#" class="social_box google">
<span class="icon"><i class="fa fa-google-plus"></i></span>
<span class="icon_title">سجل عن طريق كوكل</span>
</a>
</div>
<div class="centeredText">
<span>أو استخدم الايميل الخاص بك</span>
</div>
<div class="action_btns">
<div class="one_half">سجل دخول</div>
<div class="one_half last"> انضم</div>
</div>
</div>
<!-- Username & Password Login form -->
<div class="user_login">
<form>
<label>الايميل / اسم المستخدم</label>
<input type="text" />
<br />
<label>كلمة السر</label>
<input type="password" />
<br />
<div class="checkbox">
<input id="remember" type="checkbox" />
<label for="remember">احفظ معلومات الدخول على هذا الجهاز</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> رجوع</div>
<div id="login_btn" class="one_half last">Login</div>
</div>
</form>
هل نسيت كلمة المرور؟
</div>
<!-- Register Form -->
<div class="user_register">
<form>
<label>اسم المستخدم</label>
<input id="txtUserName" type="text" />
<br />
<label>عنوان البريد الألكتروني</label>
<input id="txtEmail" type="email" />
<br />
<label>كلمة المرور</label>
<input id="txtPass" type="password" />
<br />
<div class="checkbox">
<input id="send_updates" type="checkbox" />
<label for="send_updates">أرسل لي رسائل في حال وجود أي تحديثات</label>
</div>
<div class="action_btns">
<div class="one_half"><i class="fa fa-angle-double-left"></i> Back</div>
<div id="register_btn" class="one_half last">Register</div>
</div>
</form>
</div>
</section>
</div>
<!--Signin/Signup End-->
and this is my script
<script>
//login code
$(document).ready(function () {
$("#register_btn").click(function () {
// Do something
$.ajax({
url: '#Url.Action("Register", "Account")',
type: 'POST',
data: {//passing data
userName:$("#txtUserName").val(),
email:$("#txtEmail").val(),
password: $("#txtPass").val()
},
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
});
</script>
and here is my controller code
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(UserModel user)
{
AddDetails(user);
return View();
}
private void Connection()
{
string constr = ConfigurationManager.ConnectionStrings["NerdsContext"].ToString();
con = new SqlConnection(constr);
}
//Add records to database
private void AddDetails(UserModel user)
{
Connection();
SqlCommand com = new SqlCommand("AddUser", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#userName", user.userName);
com.Parameters.AddWithValue("#email", user.email);
com.Parameters.AddWithValue("#password", user.password);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
I checked my sql procedure it is working fine but I don't know why I'm getting failure alert.

Angular Nested Comments - Values undefined when submitting form

I am trying to get a dynamic script for nested comments to work.
My first problem is that I don't know how I can do endless nesting. For now I planned to do 3 layers, cause I don't know how to make it work dynamicly.
The second problem is that when i submit the form, the values of the models is not submitted to the JS-script. The values are just undefined.
I guess my approach is just wrong - The ng-model elements are not bound inside of the ng-repeat, also the values of all forms would be bound to the same element... Maybe someone has some tips. If it is important, my backend runs with Laravel 4. Here is my code
var commentsApp = angular.module('commentsApp', []);
function CommentsCtrl($scope, $http, $compile) {
var url_segments = window.location.host.split('.');
var section = url_segments[0];
$http.get('/api/' + section + window.location.pathname + '/comments').success(function (comments) {
$scope.comments = comments;
});
$scope.toggleForm = function (id) {
var container = document.getElementById(id);
var html = '<br/><input name="category" type="text" ng-model="person.category" placeholder="Category" required/><span class="alert alert-error ng-show="add-bro.input.$error.required">Required</span>';
var elem = $compile(html)($scope);
angular.element(container).append(elem);
}
$scope.addComment = function () {
var comment = {
body: $scope.body,
commentable_id: $scope.commentable_id,
commentable_type: $scope.commentable_type
};
$scope.comments.push(comment);
};
}
commentsApp.controller('CommentsCtrl', CommentsCtrl);
<div class="content-row basic" ng-controller="CommentsCtrl" class="comments">
<form ng-submit="addComment()">
<input type="text" placeholder="Add Comment" ng-model="body">
<input type="hidden" value="#{{c.id}}" ng-model="commentable_id">
<input type="hidden" value="Player" ng-model="commentable_type">
<button type="submit">Add Comment</button>
</form>
<div ng-repeat="c in comments" class="comment">
<span>#{{c.author.username}}</span>
<p>#{{c.body}}</p>
<a href class="reply-link" ng-click="showForm = !showForm">Answer</a>
<div class="reply-container" ng-show="showForm">
<form ng-submit="addComment()">
<input type="text" placeholder="Add Comment" ng-model="body">
<input type="hidden" value="#{{c.id}}" ng-model="commentable_id">
<input type="hidden" value="Comment" ng-model="commentable_type">
<button type="submit">Add Comment</button>
</form>
</div>
<div ng-repeat="cc in c.comments" class="s-comment">
<span>#{{cc.author.username}}</span>
<p>#{{cc.body}}</p>
<a href class="reply-link" ng-click="showForm = !showForm">Answer</a>
<div class="reply-container" ng-show="showForm">
<form ng-submit="addComment()">
<input type="text" placeholder="Add Comment" ng-model="body">
<input type="hidden" value="#{{c.id}}" ng-model="commentable_id">
<input type="hidden" value="Comment" ng-model="commentable_type">
<button type="submit">Add Comment</button>
</form>
</div>
<div ng-repeat="ccc in cc.comments" class="ss-comment">
<span>#{{ccc.author.username}}</span>
<p>#{{ccc.body}}</p>
<a href class="reply-link" ng-click="showForm = !showForm">Answer</a>
<div class="reply-container" ng-show="showForm">
<form ng-submit="addComment()">
<input type="text" placeholder="Add Comment" ng-model="body">
<input type="hidden" value="#{{c.id}}" ng-model="commentable_id">
<input type="hidden" value="Comment" ng-model="commentable_type">
<button type="submit">Add Comment</button>
</form>
</div>
</div>
</div>
</div>
</div>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
//Comments object having reply oject
$scope.comments = [{ comment: 'hi', reply: [{ comment: 'hi inside commnet' }, { comment: 'hi inside commnet' }] }];
//push reply
$scope.insertReply = function (index, reply) {
$scope.comments[index].reply.push({ comment: reply });
}
//push commnet
$scope.newComment = function (comment) {
$scope.comments.push({ comment:comment, reply: [] });
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<!--Comment section-->
<ul ng-repeat="comment in comments track by $index" style="background: skyblue; padding: 10px;">
<li>
<b>Comment {{$index}} : </b>
<br>
{{comment.comment}}
<!--Reply section-->
<ul ng-repeat="reply in comment.reply track by $index">
<li><i>Reply {{$index}} :</i><br>
{{reply.comment}}</li>
</ul>
<!--End reply section-->
<input type="text" ng-model="reply" placeholder=" Write your reply." />Reply
</li>
</ul>
<!--End comment section -->
<!--Post your comment-->
<b>New comment</b>
<input type="text" placeholder="Your comment" ng-model="comment" />
Post
</div>

Resources