PHP laravel and JQuery AJAX append form input - javascript

Hey guys I am just wondering how I can append a view within Laravel to my page using AJAX.
How can I append just input nema="result" and insert data into the database with laravel.
Error: [HTTP/1.1 422 Unprocessable Entity 323ms]
My blad file
<form id="repeater_form" class="row" action="{{route('agreement.store')}}" method="post" enctype="multipart/form-data">
#csrf
<div class="col-sm-3 form-group">
<label>Year</label>
<select class="form-control select2" name="year" >
<option value="">--select--</option>
#foreach ($years as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>target</label>
<input type="text" name="target" id="target" class="form-control" />
</div>
<div id="repeater">
<div class="repeater-heading" align="right">
<button type="button" class="btn btn-primary repeater-add-btn">Add More Skill</button>
</div>
<div class="clearfix"></div>
<div class="items" data-group="programming_languages">
<div class="item-content">
<div class="form-group">
<div class="row">
<input type="text" name="result[]" id="result" class="form-control" required />
<div class="col-md-3" style="margin-top:24px;" align="center">
<button id="remove-btn" class="btn btn-danger" onclick="$(this).parents('.items').remove()">Remove</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12 form-group">
<button name="insert" type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Submit</button>
backe
</div>
</form>
Js File
<script>
$(document).ready(function(){
$("#repeater").createRepeater();
$('#repeater_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '{{route('agreement.store')}}',
method:"POST",
data:$(this).serialize(),
success:function(data)
{
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
}
});
});
});
</script>
I am new in laravel Here what am I doing I am going to insert a simple form value into database. Now, what happen when I click on submit button it is not insert data. I have no idea about that. So, How can I do this? Please help me.
Thank You.
My Contoroller
public function store(CreateAgreement $request)
{
$agreements = new Agreement;
$agreements->target = $request->target;
$agreements->result = $request->result;
$agreements->years()->attach(request('year'));
$agreements->save();
return redirect()->route('agreement.index');
}
CreateAgreement Request
public function rules()
{
return [
'year' => ['required'],
'code' => ['required'],
'target' => ['required'],
'result' => ['required'],
];
}
Repeater js
jQuery.fn.extend({
createRepeater: function () {
var addItem = function (items, key) {
var itemContent = items;
var group = itemContent.data("group");
var item = itemContent;
var input = item.find('input,select');
input.each(function (index, el) {
var attrName = $(el).data('name');
var skipName = $(el).data('skip-name');
if (skipName != true) {
$(el).attr("name", group + "[" + key + "]" + attrName);
} else {
if (attrName != 'undefined') {
$(el).attr("name", attrName);
}
}
})
var itemClone = items;
/* Handling remove btn */
var removeButton = itemClone.find('.remove-btn');
if (key == 0) {
removeButton.attr('disabled', true);
} else {
removeButton.attr('disabled', false);
}
$("<div class='items'>" + itemClone.html() + "<div/>").appendTo(repeater);
};
/* find elements */
var repeater = this;
var items = repeater.find(".items");
var key = 0;
var addButton = repeater.find('.repeater-add-btn');
var newItem = items;
if (key == 0) {
items.remove();
addItem(newItem, key);
}
/* handle click and add items */
addButton.on("click", function () {
key++;
addItem(newItem, key);
});
}
});

Related

How to reset the counter to 0 after Ajax Refresh or Submistion to database,

I have this code that sends multiple data in MySQL Database using JQuery Ajax, all works fine but when i try to refresh the page using ajax and add new record, Its populated the number of times equivalent to the last counter.
Below is my index.php page;
<div id="sample_table_data">
<div class="row">
<div class="panel border-cyan-dark">
<div class="panel-heading bg-cyan text-white border-cyan-dark">
<div class="panel-title">
<h4>PHP - Sending multiple forms data through jQuery Ajax</h4>
</div>
</div>
<div class="panel-body">
<div style="padding-bottom: 10px;" align="right">
<button name="add" id="add" class="btn btn-success btn-sm">
<i class="fa fa-plus-square"></i>Add Measures
</button>
</div>
<form method="POST" id="user_form">
<div class="row">
<div class="table-responsive margin-bottom-20" >
<table class="table table-striped table-bordered table-condensed table-hover" id="user_data">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Details</th>
<th>Remove</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<input type="submit" name="insert" id="insert" class="btn btn-primary btn-sm" value="Insert">
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Form Dialogue Box -->
<div id="user_dialog">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control input-sm">
<span id="error_first_name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control input-sm">
<span id="error_last_name" class="text-danger"></span>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input type="hidden" name="row_id" id="hidden_row_id">
<button type="button" name="save" id="save" class="btn btn-info btn-sm">Save</button>
</div>
</div>
</div>
</div>
<!-- Alert Box -->
<div id="action_alert" title="Action"></div>
<script>
$(document).ready(function(){
var count = 0;
$('#user_dialog').dialog({
autoOpen:false,
width:800
});
$('#add').click(function(){
$('#user_dialog').dialog('option', 'title', 'Add Data');
$('#first_name').val('');
$('#last_name').val('');
$('#error_first_name').text('');
$('#error_last_name').text('');
$('#first_name').css('border-color', '');
$('#last_name').css('border-color', '');
$('#save').text('Save');
$('#user_dialog').dialog('open');
});
$('#save').click(function(){
var error_first_name = '';
var error_last_name = '';
var first_name = '';
var last_name = '';
if($('#first_name').val() == '') {
error_first_name = 'First Name is required';
$('#error_first_name').text(error_first_name);
$('#first_name').css('border-color', '#cc0000');
first_name = '';
} else {
error_first_name = '';
$('#error_first_name').text(error_first_name);
$('#first_name').css('border-color', '');
first_name = $('#first_name').val();
}
if($('#last_name').val() == '') {
error_last_name = 'Last Name is required';
$('#error_last_name').text(error_last_name);
$('#last_name').css('border-color', '#cc0000');
last_name = '';
} else {
error_last_name = '';
$('#error_last_name').text(error_last_name);
$('#last_name').css('border-color', '');
last_name = $('#last_name').val();
}
if(error_first_name != '' || error_last_name != '') {
return false;
} else {
if($('#save').text() == 'Save')
{
count++;
output = '<tr id="row_'+count+'">';
output += '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+count+'" class="first_name" value="'+first_name+'" /></td>';
output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+count+'" value="'+last_name+'" /></td>';
output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+count+'">View</button></td>';
output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+count+'">Remove</button></td>';
output += '</tr>';
$('#user_data').append(output);
}
else
{
var row_id = $('#hidden_row_id').val();
output = '<td>'+first_name+' <input type="hidden" name="hidden_first_name[]" id="first_name'+row_id+'" class="first_name" value="'+first_name+'" /></td>';
output += '<td>'+last_name+' <input type="hidden" name="hidden_last_name[]" id="last_name'+row_id+'" value="'+last_name+'" /></td>';
output += '<td><button type="button" name="view_details" class="btn btn-warning btn-xs view_details" id="'+row_id+'">View</button></td>';
output += '<td><button type="button" name="remove_details" class="btn btn-danger btn-xs remove_details" id="'+row_id+'">Remove</button></td>';
$('#row_'+row_id+'').html(output);
}
$('#user_dialog').dialog('close');
}
});
$(document).on('click', '.view_details', function(){
var row_id = $(this).attr("id");
var first_name = $('#first_name'+row_id+'').val();
var last_name = $('#last_name'+row_id+'').val();
$('#first_name').val(first_name);
$('#last_name').val(last_name);
$('#save').text('Edit');
$('#hidden_row_id').val(row_id);
$('#user_dialog').dialog('option', 'title', 'Edit Data');
$('#user_dialog').dialog('open');
});
$(document).on('click', '.remove_details', function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to remove this row data?")) {
$('#row_'+row_id+'').remove();
} else {
return false;
}
});
$('#action_alert').dialog({
autoOpen:false
});
$('#user_form').on('submit', function(event){
event.preventDefault();
var count_data = 0;
$('.first_name').each(function(){
count_data = count_data + 1;
});
if(count_data > 0)
{
var form_data = $(this).serialize();
$.ajax({
url:"pages/insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#user_data').find("tr:gt(0)").remove();
count =0;
$('#action_alert').html('<p>Data Inserted Successfully</p>');
$('#action_alert').dialog('open');
}
})
}
else
{
$('#action_alert').html('<p>Please Add atleast one data</p>');
$('#action_alert').dialog('open');
}
});
});
</script>
and this is my insert.php code
<?php
//insert.php
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "****");
$query = "
INSERT INTO tbl_sample
(first_name, last_name)
VALUES (:first_name, :last_name)
";
for($count = 0; $count<count($_POST['hidden_first_name']); $count++)
{
$data = array(
':first_name' => $_POST['hidden_first_name'][$count],
':last_name' => $_POST['hidden_last_name'][$count]
);
$statement = $connect->prepare($query);
$statement->execute($data);
}
?>
Kindly help me how I can reset the counter to 0 after Ajax refresh. Thanks.
put the var count ouside the $(document)
var count = 0;
$(document).ready(function(){
and in your submit function
$('#user_form').on('submit', function(event){
event.preventDefault();
var count_data = 0;
$('.first_name').each(function(){
count_data = count_data + 1;
});
if(count_data > 0)
{
var form_data = $(this).serialize();
$.ajax({
url:"pages/insert.php",
method:"POST",
data:form_data,
success:function(data)
{
$('#user_data').find("tr:gt(0)").remove();
$('#action_alert').html('<p>Data Inserted Successfully</p>');
$('#action_alert').dialog('open');
}
count =0;
})
}
else
{
$('#action_alert').html('<p>Please Add atleast one data</p>');
$('#action_alert').dialog('open');
}
});
and in additional, you should be using .prop instead of .attr

create a new function

I have a new Order page, in this page, user should select the category, then, select the service and then, fill quantity field for the order.
I want create a change, I want to define a function with #if and #else
In this function, let's say if the service is not selected, the quantity field is not displayed
But if it was selected, the quantity field would appear
But I do not know how to define this function.
this is my code:
#extends('user.layouts.master')
#section('site_title', 'New Order')
#section('page_title')
<i class="fa fa-first-order"></i>New Order
#endsection
#section('body')
<div class="row">
<div class="col-md-6 offset-md-3">
#include('user.layouts.flash')
<div class="card">
<div class="card-header d-flex align-items-center">
<h3 class="h4">Submit new order</h3>
</div>
<div class="card-body">
<form action="{{ route('newOrder.store') }}" method="post">
#csrf
<div class="form-group">
<label class="form-control-label"><b>category</b></label>
<select class="form-control" id="category" name="category" required>
<option>Select category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="form-control-label"><b>Service</b></label>
<select class="form-control input-lg" id="service" name="service" required>
</select>
</div>
#if ($item->service)
<div class="form-group">
<label for="details" class="control-label">Details</label>
<textarea name="details"
id="details"
rows="5"
style="height: 150px"
class="form-control" readonly></textarea>
<div class="form-group">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
<div class="row">
<div class="col-md-6">
<label style="color: #080B6A"><b>Min:</b><span id="min">0</span></b></label>
</div>
<div class="col-md-6">
<label style="color: #080B6A"><b>Max: </b><span id="max">0</span></b></label>
</div>
</div><br>
<div class="row">
<div class="col-md-6">
<label class="btn btn-success">Total price: <span
id="price">0</span> {{ $general->base_currency }}</label>
</div>
</div><br>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
// fetch Service
$(document).on('change', '#category', function () {
var serId = $('option:selected', this).val();
$.ajax({
type: 'POST',
url: '{{ route('get.pack') }}',
data: {id: serId},
success: function (data) {
$('#service').html('');
$('#service').append('<option>Select service</option>');
$.each(data, function (index, value) {
$('#service').append('<option value="' + value.id + '">' + value.name + '</option>');
});
var total = 0;
$('#details').text();
$('#min').text(0);
$('#max').text(0);
$('#price').text(total.toFixed(2))
},
})
});
//package price and quantity
var price = 0;
var quantity = 0;
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});
$(document).on('keyup', '#quantity', function () {
quantity = $(this).val();
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
});
});
</script>
#endsection
you can do this using javascript
// first we hide what we want using style="display:none" and add a calss or attribute to the hidden elements ex: hidden-elements
<div class="form-group hidden-elements" style="display:none">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
// when we change the value of the service
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
// here we show the hidden elements after we choose the service
$('.hidden-elements').show();
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});

Get the the in time and out time of employee in Full Calendar according to the user id selected in drop down list

I want to display in time and out time of the user in full calendar. Each and every user has different in time and out time. And the user id is selected in drop down. Right now I'm getting the drop down which is binded with the user name and user id so I have to bind the login time and logout time of the user to the calendar.This is my code where i bind the drop down with data. This is my controller code for binding the drop down with the user id and user name.
public ActionResult AttendanceScreen()
{
List<SelectListItem> userList = Getuser();
return View(userList);
}
[HttpPost]
public ActionResult AttendanceScreen(string ddlCustomers)
{
List<SelectListItem> userList = Getuser();
if (!string.IsNullOrEmpty(ddlCustomers))
{
SelectListItem selectedItem = userList.Find(p => p.Value == ddlCustomers);
ViewBag.Message = "Calender for Name: " + selectedItem.Text;
ViewBag.Message += "\\nID: " + selectedItem.Value;
}
return View(userList);
}
private static List<SelectListItem> Getuser()
{
RegMVCEntities entities = new RegMVCEntities();
List<SelectListItem> customerList = (from p in entities.tblRegistrations.AsEnumerable()
select new SelectListItem
{
Text = p.FName,
Value = p.UserId.ToString()
}).ToList();
//Add Default Item at First Position.
customerList.Insert(0, new SelectListItem { Text = "--Select Employee--", Value = "" });
return customerList;
}
This is my view for displaying the user id and user name as alert.
#using (Html.BeginForm("AttendanceScreen", "Home", FormMethod.Post))
{
#Html.DropDownList("ddlCustomers", Model)
<br />
<br />
<input type="submit" value="Submit" />
}
#if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("#ViewBag.Message");
};
For displaying the calendar the controller code is
public JsonResult GetEvents()
{
using (RegMVCEntities dc = new RegMVCEntities())
{
var events = dc.User_LogTime.ToList();
dc.Configuration.ProxyCreationEnabled = false;
dc.Configuration.LazyLoadingEnabled = false;
return new JsonResult { Data = events, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
For displaying the calendar the code of my view is
<h2>Calender</h2>
<div id="calender"></div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span id="eventTitle"></span></h4>
</div>
<div class="modal-body">
<button id="btnDelete" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-remove"></span> Remove
</button>
<button id="btnEdit" class="btn btn-default btn-sm pull-right" style="margin-right:5px;">
<span class="glyphicon glyphicon-pencil"></span> Edit
</button>
<p id="pDetails"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div id="myModalSave" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Save Event</h4>
</div>
<div class="modal-body">
<form class="col-md-12 form-horizontal">
<input type="hidden" id="hdEventID" value="0" />
#*<div class="form-group">
<label>Subject</label>
<input type="text" id="txtSubject" class="form-control" />
</div>*#
<div class="form-group">
<label>LoginTime</label>
<div class="input-group date" id="dtp1">
<input type="text" id="txtStart" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
#*<div class="form-group">
<div class="checkbox">
<label><input type="checkbox" id="chkIsFullDay" checked="checked" /> Is Full Day event</label>
</div>
</div>*#
<div class="form-group" id="divEndDate" style="display:none">
<label>LogoutTime</label>
<div class="input-group date" id="dtp2">
<input type="text" id="txtEnd" class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
#*<div class="form-group">
<label>Description</label>
<textarea id="txtDescription" rows="3" class="form-control"></textarea>
</div>*#
<div class="form-group">
<label>Theme Color</label>
<select id="ddThemeColor" class="form-control">
<option value="">Default</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="green">Green</option>
</select>
</div>
<button type="button" id="btnSave" class="btn btn-success">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.css" rel="stylesheet" />
<link href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.print.css" rel="stylesheet" media="print" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
#section Scripts{
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.4.0/fullcalendar.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<script>
$(document).ready(function () {
debugger;
var event_array = [];
var selectedEvent = null;
FetchEventAndRenderCalendar();
function FetchEventAndRenderCalendar() {
events = [];
$.ajax({
url: "/Home/GetEvents",
data: "",
type: "GET",
dataType: "json",
async: false,
cache: false,
success: function (data) {
alert("success");
$.each(data, function (i, v) {
event_array.push({
userid: v.UserId,
start: moment(v.LoginTime),
end: moment(v.LogoutTime),
//start: moment(v.start),
//end: v.end != null ? moment(v.end) : null,
//color: v.themecolor,
//allday: v.isfullday
});
})
GenerateCalender(event_array);
},
error: function (error) {
alert('failed');
}
})
}
function GenerateCalender(event_array) {
debugger;
//$('#calender').fullCalendar('destroy');
$('#calender').fullCalendar({
contentHeight: 400,
defaultDate: new Date(),
timeFormat: 'h(:mm)a',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay,agenda'
},
eventLimit: true,
eventColor: '#378006',
events: event_array,
eventClick: function (calEvent, jsEvent, view) {
selectedEvent = calEvent;
$('#myModal #eventTitle').text(calEvent.userid);
var $description = $('<div/>');
$description.append($('<p/>').html('<b>LoginTime:</b>' + calEvent.logintime.format("DD-MMM-YYYY HH:mm a")));
$description.append($('<p/>').html('<b>LogoutTime:</b>' + calEvent.logouttime.format("DD-MMM-YYYY HH:mm a")));
//$description.append($('<p/>').html('<b>Description:</b>' + calEvent.description));
//$('#myModal #pDetails').empty().html($description);
$('#myModal').modal();
},
//selectable: true,
//select: function (logintime, logouttime) {
// selectedEvent = {
//// userid: 0,
//// logintime: logintime,
//// logouttime: logouttime
//// };
//// openAddEditForm();
//// $('#calendar').fullCalendar('unselect');
////},
////editable: false,
eventDrop: function (event) {
var data = {
UserId: event.userid,
LoginTime: event.logintime.format('DD/MM/YYYY HH:mm A'),
LogoutTime: event.logouttime.format('DD/MM/YYYY HH:mm A')
};
SaveEvent(data);
}
});
}
this is the screenshot of my current page
The attendance screen
Right I'm just getting the in time and out time in the database as you can see in screenshot but that is for all the user in Database.I just need to update the calendar with in time and out time of the user id selected in drop down.
I have done it. It was simple I just needed to use session for getting the user id.This is my code:
public ActionResult AttendanceScreen(string ddlCustomers)
{
Session["userid"] = ddlCustomers;
List<SelectListItem> userList = Getuser();
if (!string.IsNullOrEmpty(ddlCustomers))
{
SelectListItem selectedItem = userList.Find(p => p.Value == ddlCustomers);
ViewBag.Message = "Calender for Name: " + selectedItem.Text;
ViewBag.Message += "\\nID: " + selectedItem.Value;
}
return View(userList);
// return RedirectToAction("Index", "Nome", new { userid: userid });
}
public JsonResult GetEvents()
{
string username = User.Identity.Name;
int isessionid = Convert.ToInt32(Session["userid"]);
List<SelectListItem> userList = Getuser();
if (isessionid == 0)
{
return null;
}
else
{
//int userid = int.Parse(username);
RegMVCEntities svc = new RegMVCEntities();
svc.Configuration.ProxyCreationEnabled = false;
svc.Configuration.LazyLoadingEnabled = false;
// var oCampaigns = svc.User_LogTime;
var oReturn =
(from c in svc.User_LogTime.AsEnumerable()
where c.UserId == isessionid
select new
{
LoginTime = c.LoginTime,
Logouttime = c.LogoutTime
}).ToList();
//var events = dc.User_LogTime.ToList();
//dc.Configuration.ProxyCreationEnabled = false;
// dc.Configuration.LazyLoadingEnabled = false;
return new JsonResult { Data = oReturn.ToList(), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}

Unable to load a Knockout Component - Unknown template value: [object Object]

This is how I am using the component and sending the parameters using a Custom Element:
<div class="container" data-bind="with: DevoteeList">
<div class="row" style="padding: 10px;">
<div class="col-md-8"></div>
<div class="col-md-4">
<ko-pager params="Data: Devotees,
Modifier: $parent.DevoteeModifier,
PageCount: DevoteesPageCount(),
Url: '#Url.Action("SelectDevotees", "Devotee", new { a = 1 })'"></ko-pager>
</div>
</div>
This is how I am defining a Knockout Component. It is a Pager that I want to use at few places. But, I am receiving the error: Uncaught Error: Unable to process binding "with: function (){return SelectDevotees }"
Message: Unable to process binding "with: function (){return DevoteeList }"
Message: Unable to process binding "component: function () { return l }"
Message: Component 'ko-pager': Unknown template value: [object Object]
ko.components.register('ko-pager', {
viewModel: function (params) {
var self = this;
self.currentPage = ko.observable(1);
self.pages = ko.observableArray([]);
self.PageCount = ko.observable(params.PageCount);
//self.currentPage.subscribe(function (nv) {
// self.GetPage(self.parent);
//});
self.GetPages = function () {
for (var i = 1; i <= params.PageCount ; i++) {
self.pages.push(i);
}
return self.pages;
};
self.FirstPage = function () {
self.GetPage(1);
};
self.PrevPage = function () {
if (self.currentPage() > 1) {
var pn = self.currentPage() - 1;
self.GetPage(pn);
}
};
self.LastPage = function () {
self.GetPage(params.PageCount);
};
self.NextPage = function () {
if (self.currentPage() < params.PageCount) {
var pn = self.currentPage() + 1;
self.GetPage(pn);
}
};
self.GetPage = function (pg) {
if (pg == null)
pg = self.currentPage();
else
self.currentPage(pg);
var url = params.Url + '&pageNumber=' + pg;
$.get(url, function (data) {
var t = ko.mapping.fromJS(data);
if (params.Modifier) {
params.Modifier(t);
}
params.Data(t());
});
};
},
template: { element: document.getElementById('ko-ajax-pager') }
});
<div id="ko-ajax-pager" style="display: none;">
<div class="row" style="padding: 10px;" data-bind="visible: PageCount > 1">
<div class="col-md-1"></div>
<div class="col-md-2">
<input type="button" value="First" class="btn" data-bind="click: FirstPage" />
</div>
<div class="col-md-2">
<input type="button" value="Prev" class="btn" data-bind="click: PrevPage" />
</div>
<div class="col-md-2">
<select data-bind="options: GetPages(), value: currentPage, event: { change: GetPage(null) }">
</select>
</div>
<div class="col-md-2">
<input type="button" value="Next" class="btn" data-bind="click: NextPage" />
</div>
<div class="col-md-2">
<input type="button" value="Last" class="btn" data-bind="click: LastPage" />
</div>
<div class="col-md-1"></div>
</div>
</div>
Can someone please figure out, what is wrong?

$parent.myFunction not returning row as parameter in KnockoutJs

I'm using knockoutjs for the first time in an attempt to have a list of tasks and then to be able to click on one to show it in a popup form. The issue I'm having is with data-bind="click: $parent.edit", which calls ToDoListViewModel/edit.
When I first started writing the list code, it would pass in the current row's todo object as the first parameter into the edit function. After adding the second view model for my add/edit popup form, it no longer behaves this way. Calling $parent.edit still calls the edit function, however now it passes in an empty object { }.
It seems like I'm running into some sort of conflicting bindings issue, any ideas?
Here is the to do list html:
<table class="table table-striped table-hover" data-bind="visible: isVisible">
<thead>
<tr>
<th>To-Do</th>
<th>Estimate</th>
<th>Deadline</th>
#if (Model == null) { <th>Property</th> }
<th>Tenant</th>
<th style="display: none;">Assigned To</th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: todos">
<tr data-bind="visible: isVisible()">
<td><a class="pointer" title="Edit To-Do" data-bind="click: $parent.edit, text: Task"></a></td>
<td data-bind="text: FormattedAmount"></td>
<td data-bind="text: FormattedDueDate"></td>
<td data-bind="visible: $parent.showPropertyColumn, text: PropertyName"></td>
<td data-bind="text: TenantName"></td>
<td>
<div class="btn-group pull-right">
<a class="btn btn-primary pointer default-click-action" data-bind="click: $parent.markComplete">Mark Complete</a>
<button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"><span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a class="pointer" data-bind="click: $parent.edit">Edit To-Do</a></li>
<li><a class="pointer" data-bind="click: $parent.remove">Delete To-Do</a></li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
And here is the popup html:
#model Housters.Schemas.Models.Property.Listing
<div id="popup" class="modal fade" style="display: none;" data-bind="with: form">
#using (Html.BeginForm("SaveTodo", "Properties", FormMethod.Post, new { Id = "form", #class = "form-horizontal" }))
{
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>To-Do Information</h3>
</div>
<div class="modal-body">
<input id="id" name="id" type="hidden" data-bind="value: todo().Id" />
<input id="originalListingId" type="hidden" value="#(Model != null ? Model.IdString : "")" />
<div class="control-group #(Model != null ? " hide" : "")">
<label class="control-label" for="listingId">Property</label>
<div class="controls">
#Html.DropDownList("listingId", ViewBag.Listings as SelectList, "None",
new Dictionary<string, Object> { { "data-bind", "value: todo().ListingId" } })
</div>
</div>
<div class="control-group">
<label class="control-label" for="tenantId">Tenant</label>
<div class="controls">
<select id="tenantId" name="tenantId" class="span11" data-bind="value: todo().TenantId">
<option value="">None</option>
</select>
<p class="help-block">Is this task related to a certain tenant?</p>
</div>
</div>
<div class="control-group">
<label class="control-label" for="amount">Estimate to Complete</label>
<div class="controls">
<div class="input-prepend"><span class="add-on">$</span><input type="text" id="amount" name="todo.Amount" maxlength="10"
class="span11 number" data-bind="value: todo().Amount" /></div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="dueDate">Due Date</label>
<div class="controls">
<input type="text" id="dueDate" name="todo.DueDate" maxlength="10"
class="span11 date" data-bind="value: todo().DueDate" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="task">Task<span class="required-asterisk">*</span></label>
<div class="controls">
<textarea id="task" name="todo.Task" rows="4" class="span11 required" data-bind="value: todo().Task"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn pointer" data-dismiss="modal">Close</a>
<a id="mark-complete-popup" class="btn btn-primary" data-dismiss="modal" data-bind="visible: (todo().Id && !todo().IsComplete), click: markComplete">Mark Complete</a>
<button type="button" class="btn btn-primary" data-bind="click: save">Save</button>
</div>
}
</div>
And lastly, here is the javascript defining the view models:
function ToDoList () {
if(!(this instanceof arguments.callee))
return new arguments.callee();
var parent = this;
this.showCompleted = ko.observable(false);
this.tenantFilter = new PropertyTenantFilter();
this.viewModel = {
list: new ToDoListViewModel(),
form: new ToDoFormViewModel()
};
this.init = function () {
//get all tenants.
utils.block($("#grid-content"), "Loading");
this.tenantFilter.init(function () {
//initialize view model.
ko.applyBindings(this.viewModel);
//setup controls & events.
$("#dueDate").datepicker();
$("#listingId").change(this.tenantFilter.getByListing.bind(this.tenantFilter)).change();
} .bind(this));
};
function ToDoListViewModel() {
//init.
var self = this;
self.todos = ko.observableArray([]);
//computed.
self.showPropertyColumn = ko.computed(function () {
return $("#originalListingId").val().length == 0;
});
self.isVisible = ko.computed(function () {
return _.find(self.todos(), function (todo) { return todo.isVisible(); }) != null;
});
//operations.
self.add = function () {
//set form field values.
parent.viewModel.form.fill(new schemas.ToDo({}, parent));
//show popup.
$("#popup").modal("show");
};
self.edit = function (todo) {
console.debug("edit: " + JSON.stringify(todo));
//set form field values.
parent.viewModel.form.fill(todo);
//update tenants dropdown for selected listing.
parent.tenantFilter.getByListing();
//show popup.
$("#popup").modal("show");
};
self.markComplete = function (todo) {
parent.markComplete(todo);
};
self.remove = function (todo) {
var result = confirm("Are you sure that you want to delete this To-Do?");
if (result) {
//save changes.
utils.ajax(basePath + "properties/deletetodo",
{ id: todo.Id },
function (success) {
//refresh results.
self.todos.remove(todo);
//show result.
utils.showSuccess('The To-Do has been deleted successfully');
}
);
}
};
self.toggleShowCompleted = function () {
parent.showCompleted(!parent.showCompleted());
$("#showCompletedTodos").text(parent.showCompleted() ? "Show Active" : "Show Completed");
};
self.update = function (todo) {
var existingToDo = _.find(self.todos(), function (item) { return item.Id() == todo.Id(); });
existingToDo = todo;
};
//load todos from server.
utils.ajax(basePath + "properties/gettodos",
{ id: $("#originalListingId").val(), showCompleted: parent.showCompleted() },
function (results) {
var mappedTodos = $.map(results, function (item) { return new schemas.ToDo(item, parent); });
self.todos(mappedTodos);
$("#grid-content").unblock();
}
);
}
function ToDoFormViewModel() {
//init.
var self = this;
self.todo = ko.observable({});
utils.setupPopupForm(self.saved);
//operations.
self.fill = function (todo, isEdit) {
//set form field values.
self.todo = todo;
if (todo.Id()) {
//update tenants dropdown for selected listing.
parent.tenantFilter.getByListing();
}
//show popup.
$("#popup").modal("show");
};
self.save = function (todo) {
self.todo = todo;
$("#form").submit();
};
self.saved = function (result) {
var todo = new schemas.ToDo(result.todo, parent);
if (result.isInsert)
parent.viewModel.list.todos().push(todo);
else
parent.viewModel.list.update(todo);
utils.showSuccess("Your To-Do has been saved successfully.");
};
self.markComplete = function (todo) {
parent.markComplete(todo);
};
}
this.markComplete = function (todo) {
var result = confirm("Are you sure that you want to mark this To-Do complete?");
if (result) {
//save changes.
utils.ajax(basePath + "properties/marktodocomplete", {
id: todo.Id()
},
function () {
todo.IsComplete(true);
//show success.
utils.showSuccess('Your To-Do has been marked completed');
} .bind(this)
);
}
}
this.init();
}
One possible solution is to replace:
data-bind="click: $parent.edit"
with
data-bind="click:$root.viewModel.list.edit"

Categories

Resources