KendoUI: MVVM Autocomplete Events - events

I was searching all over but couldn't find an answer to my question. I'm initializing an autocomplete widget as the following:
This code is loaded into my DOM as a result of an Ajax request:
<div id="view_ticketCreate">
<form id="jar_ticketing_create"action="" class="k-block jar-container">
<fieldset class="login">
<legend>Kontaktinformationen</legend>
<p class="notice">Definieren Sie hier die Kontaktinformationen zu diesem Ticket.</p>
<p>
<label>Kunde</label>
<input data-role="autocomplete" data-bind="source: customers, events{click: inject}" data-text-field="CName" placeholder="Suchen Sie nach dem Kunde" type="text" id="jtc_cID" class="k-textbox sourced">
</p>
<p>
<label>Kontakt</label>
<input type="text" name="jtc_cName" class="k-textbox">
</p>
<p>
<label>E-Mail</label>
<input data-bind="value: cMail" type="text" name="jtc_cMail" class="k-textbox">
</p>
<p>
<label>Telefon</label>
<input data-bind="value: cPhone" type="text" name="jtc_cPhone" class="k-textbox">
</p>
<p>
<label>Gerät</label>
<select name="dID" class="k-textbox sourced">
<option value="000">Nicht geräte spezifisch</option>
<option value="001">CFBS01</option>
<option value="002">CFBS02</option>
<option value="003">CFBS03</option>
<option value="004">CFBS04</option>
</select>
</p>
<p>
<label>Login</label>
<input type="text" name="cLogin" class="k-textbox">
</p>
</fieldset>
</form>
</div>
<script>
kendo.bind($("#view_ticketCreate"), view_ticketCreate);
</script>
in my main (an always loaded) JS file i got:
var view_ticketCreate = kendo.observable({
customers: new kendo.data.DataSource({
transport: {
read: {
url: "http://server/API/customers/search/",
dataType: "jsonp",
contentType: "application/json; charset=utf-8"
},
parameterMap: function(options, operation) {
return {
SearchTag: options.filter.filters[0].value
}
}
},
schema: {
data: "data"
},
serverFiltering: true,
dataTextField: "CName",
select: function(e){
if (e.item == null) return;
var DataItem = this.dataItem(e.item.index())
cPhone: DataItem.Telefon
}
}),
inject: function(e){
alert('ok')
},
cPhone: "0123456789",
cMail: "asd#asd.de"
});
However, the autocomplete search works perfect. But now I want to populate the fields jtc_cMail and jtc_cPhone with values from my autocomplete request. But either the select: Function is working (not allowed here (guess because MVVM?), also the custom event inject is fireing.
I couldn't find anything how I need to go on. Please help me out.
Greetings

Just have to use e.sender.dataItem function and pass in the index of the item selected.
selectPerson: function(e) {
var item = e.sender.dataItem(e.item.index());
viewModel.set("selectedPerson", item);
}
See jsbin http://jsbin.com/iLaK/3/edit

Related

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

How to create drop down

I want to generate a list on items in a drop down based on a previous choice from another select. All items ar in the database.
Here is what I did:
Javascript:
$(document).ready(function () {
$(document).on('change', '#province_name', function() {
var province_id = $(this).val();
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('admin/findIDProvince')!!}',
data: {'id':province_id},
success: function(data){
for (var i = 0; i < data.length; i++){
op += '<option value="'+data[i].id+'">'+data[i].city_name+'</option>';
}
div.find('#city').html(" ");
div.find('#city').append(op);
},
error: function(){
console.log('success');
},
});
});
});
Routes (web.php):
Route::namespace('Admin')->prefix('admin')->middleware('auth', 'CheckAdmin')->group(function (){
$this->get('/findIDProvince', 'SchoolsListController#findIDProvince');
});
Controller (Admin/SchoolsListController.php):
public function findIDProvince(Request $request)
{
$data = City::select('name', 'id')->where('province_id', $request->id)->take(100)->get();
return response()->json($data);
}
HTML (view.blade.php)
<div class="form-group">
<label class="col-md-3" for="province_name">province_name</label>
<div class="col-md-9">
<select id="province_name" name="province_name" class="form-control col-md-12" required>
#foreach($province_names as $province_name)
<option value="{{ $province_name->id }}">{{ $province_name->province_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3" for="city_name">city_name</label>
<div class="col-md-9">
<select id="city_name" name="city_name" class="form-control col-md-12" required>
</select>
</div>
</div>
What am I doing wrong?
First, create a hidden filed with the value for which the option that need to be selected.
<input type="hidden" value="{{ $yourOptionValueToSelect }}" id="selectThis">
Then with jQuery find the matching value from your option and change the corresponding attribute as selected.
$('option').each(function() {
if (this.value == $('#selectThis').val()) {
this.setAttribute('selected', 'selected');
}
});
Example:
<input type="hidden" value="2" id="selectThis">
<select>
<option value="1">Hello</option>
<option value="2">World</option>
</select>
Here Option 2 will be selected by default with the above jQuery Code.
In your view it will be changed to:
<option value="2" selected="selected">World</option>
// prepend : attach default value to the begining of the dropdown for region
// $('.region').prepend('<option value="default" selected="selected">Please select</option>');
$('.region').on('change', function(e) {
$('.select2-selection__placeholder').css("font-size", '11px'); // change the font size of the select box
var region = e.target.value;
$.ajax({
url: "{{ url('/dropdown/station?region')}}=" + region, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#station').empty();
// define default value
$('#station').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#station').append($('<option>').text(index).attr('value', index));
$('#station').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
$('.station').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/kv-station?station')}}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data) {
// empty the option before we populate the dropdown
$('#kvStation').empty();
// define default value
$('#kvStation').append('<option value="default" selected="selected" disabled hidden></option>');
$.each(data, function(index, subCatObj) {
// alert(subCatObj.substation_name);
$('#kvStation').append($('<option>').text(index).attr('value', index));
$('#kvStation').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
});
// kv station dropdown event
$('.kvStation').on('change', function(e) {
var station = e.target.value;
$.ajax({
url: "{{ url('/dropdown/ring?station') }}=" + station, // value.id refers to ring_id
type: "get",
cache: false,
beforeSend: function() {
$('.ajax-loader').css("visibility", "visible");
},
complete: function() {
$('.ajax-loader').css("visibility", "hidden");
},
dataType: 'json',
success: function(data, jqXHR) {
// remove the previous data ferom select
$('#ring').empty();
// checking the status code; if 204: no content, then
if (jqXHR.status === 204) {
$('#ring').append('<option value="default" selected="selected">No data</option>');
} else {
$('#ring').append('<option value="default" selected="selected" disabled hidden></option>');
}
// empty the option before we populate the dropdown
$.each(data, function(index, subCatObj) {
$('#ring').append($('<option>').text(subCatObj).attr('value', index));
$('#ring').append('' + index + '');
});
},
error: function(error) {
console.log(error);
}
});
// ring dropdown event
$('.ring').on('change', function(e) {
var id = e.target.value;
window.open('{{url(' / ring ')}}/' + id, '_blank');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="bottom">
<ul>
<li>
<label>Region
<select id="region-select" class=" form-control select2 region" name="region">
<option></option>
#foreach($regions as $region)
<option value="{{$region->region}}">
{{$region->region}}
</option>
#endforeach
</select>
{{--        {!! Form::select('region', $regions,'Please select ...', ['class' => 'region form-control select2', 'id' => 'region-select']) !!}--}}
</label>
</li>
<li>
<label>Station
<select id="station" class=" selectpicker station form-control input-sm" name="station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>KV Station
<select id="kvStation" class="kvStation form-control input-sm" name="kv-station">
<option value=""></option>
</select>
</label>
</li>
<li>
<label>Ring
<select id="ring" class="ring form-control input-sm" name="ring">
<option value=""></option>
</select>
</label>
</li>
</ul>
<i id="loading-image" hidden class="livicon" data-name="spinner-three" data-size="50" data-c="#fff" data-hc="#fff" data-loop="true"></i>
<div class="ajax-loader">
<img id="loading-image" class="loading-image img-responsive" src="{{ asset('images/ajax-loader.gif') }}">
</div>
</div>

Refreshing Kendo UI viewModel

I have a very simply page at the moment. It has a first name input, last name input, and a list of names added. You can add your first and last name to the text box, press add. It adds it the peopleList I have and adds a new listItem with their name.
My issue is when I add to the peopleList in my code, it does not update the listView. I think I need to use observable, but I am not exactly sure how to do it. My list shows it has 25 items added to it after I click btnMany, which is how many it show have.
here is the body of my code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="ViewModel"
data-layout="default">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<a data-bind="click: setValues" data-role="button" id="btnMany">Add Many</a>
<div style="margin-top: 10px">
People List:
<ul data-template="people-l-template" data-bind="source: peopleList" id="pList"></ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
<li>
FirstName: <span data-bind="text: first"></span>
LastName: <span data-bind="text: last"></span>
<a data-bind="click: removeName" data-role="button" id="btnRemoveName">X</a>
</li>
</script>
And here is my script to go along with it
<script>
var ViewModel = {
firstName: '',
lastName: '',
peopleList: [],
addName: function (e) {
this.get("peopleList").push({
first: this.get("firstName"),
last: this.get("lastName"),
});
this.set("firstName", '');
this.set("lastName", '');
},
removeName: function (e) {
this.set("peopleList", jQuery.grep(this.peopleList, function (item, i) {
return (item.firstName != e.data.firstName && item.lastName != e.data.lastName);
}));
},
setValues: function (e) {
GetValueFromServer();
}
};
var GetValueFromServer = function () {
$.ajax({
type: "GET",
url: "GetPeopleService.svc/GetPersonById/",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.forEach(function (person) {
ViewModel["peopleList"].push({
first: person.firstName,
last: person.lastName
});
});
alert(ViewModel.peopleList.length);
},
error: function (response) {
console.log(response);
}
});
};
var application = new kendo.mobile.Application(document.body);
</script>
There were a few things wrong with the code you provided, the most notably being that you didn't set the role for your <ul> element. You need to change it to have the attribute data-role="listview". You also can't use an <li> element as the root element for a listview template (KendoUI automatically takes care of this for you), otherwise you'll get an error when the list is bound.
Here's an example on JS Bin.
And here's the code:
<!--Load Some Data-->
<div id="peopleDefaultView"
data-role="view"
data-model="viewModel"
data-layout="flat">
<!--View-->
<input type="text" data-bind="value: firstName" id="fName" />
<input type="text" data-bind="value: lastName" id="lName" />
<a data-bind="click: addName" data-role="button" id="btnOne">Add</a>
<div style="margin-top: 10px">
People List:
<ul id="pList"
data-role="listview"
data-template="people-l-template"
data-bind="source: peopleList">
</ul>
</div>
</div>
<!-- Kendo Template-->
<script id="people-l-template" type="text/x-kendo-template">
FirstName: <span>#:first#</span>
LastName: <span>#:last#</span>
<a id="btnRemoveName"
data-role="button"
data-bind="click: removeName"
data-first="#:first#" data-last="#:last#">
X
</a>
</script>
...
var viewModel = {
firstName: null,
lastName: null,
peopleList: [],
addName: function (e) {
var me = this;
me.get('peopleList').push({
first: me.get('firstName'),
last: me.get('lastName')
});
me.set('firstName', '');
me.set('lastName', '');
},
removeName: function (e) {
var me = this;
me.set('peopleList', $.grep(me.peopleList, function (item, i) {
return item.first != e.target.data('first')
&& item.last != e.target.data('last');
}));
}
};
var application = new kendo.mobile.Application(document.body);

Kendo UI: Update transport doesn't trigger after calling datasource sync

Im struggling on this in hours now, I cant find a good documentation on how to implement simple ajax UPDATE on server using forms and Kendo MVVVM and datasource.
KENDO MVVM
$(function() {
var apiUrl = "http://a31262cd2f034ab8bcda22968021f3b8.cloudapp.net/api",
meetingDatasource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "/meetings/4",
dataType: "jsonp"
},
update: {
type: "PUT",
url: apiUrl + "/meetings",
contentType: "application/json; charset=utf-8",
dataType: 'json',
},
parameterMap: function(options, operation) {
return kendo.stringify(options);
}
},
batch: true,
change: function() {
},
schema: {
model: {
id: "Id",
fields: {
Title: { editable: true },
StartTime: { type: "date" },
EndTime: { type: "date" }
}
}
}
});
meetingDatasource.fetch(function () {
var viewModel = kendo.observable({
description: result.Description,
title: result.Title,
venue: result.Location,
startDate: result.StartTime,
endDate: result.EndTime,
saveChanges: function (e) {
//im not sure with this line
this.set("Title", this.Title);
meetingDatasource.sync();
e.preventDefault();
}
});
kendo.bind($("#view"), viewModel);
});
});
THE UI
<ul class="forms" id="ul-meeting">
<li>
<label for="title" >Title:</label>
<input data-bind="value: title" class="k-textbox" style="width:350px;"/>
</li>
<li>
<label for="description" >Description:</label>
<textarea data-bind="value: description" id="description" rows="6" cols="80" class="k-textbox" style="width:350px;"></textarea>
</li>
<li>
<label for="location">Venue:</label>
<textarea data-bind="value: venue" id="location" rows="4" cols="80" class="k-textbox" style="width:350px;"></textarea>
</li>
<li>
<p>
<label for="start-datetime">Start:</label>
<input data-bind="value: startDate" id="start-datetime" style="width:200px;" />
</p>
<p>
<label for="end-datetime">Finish:</label>
<input data-bind="value: endDate" id="end-datetime" style="width:200px;" />
</p>
</li>
</ul>
The problem is, the TRANSPORT READ triggers but the TRANSPORT UPDATE never triggers even if I explicity call the Datasource.sync(). Is is something I am missing here?
Your code is not complete (you are not showing what is result or how you trigger saveChanges but from what I see the problem is that you are not updating the content of the DataSource (meetingDataSource).
In your code that you copy the fields from result into and ObservableObject but you never update the content of the DataSource. When you do this.set, in that context this is not the DataSource so when you call sync you are doing nothing.
Try doing:
meetingDatasource.data()[0].set(`Title`, this.Title);
meetingDatasource.sync();
This should do the trick!

issue with ajax event

i am using an ajax event which is triggered when i hit the submit button to add data to the database but since when i orignally created this page they were all in seprate files for testing purposes so now when i have put all the code together i have notice that 4 submit buttons i was using to refresh the page and then change the data being seen by filtering it are triggering the ajax query i have placed the code bellow.. i am quite stumped in what is the only way to go about this...
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var process= $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php',
data: {
'uname': checkVal,
'id': userid
},
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
});
$('form').bind('submit', function(){ // it is triggering this peice of code when the submit buttons are clicked ???
$.ajax({
type: 'POST',
url: "requestadd.php",
data: $("form").serialize(),
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
return false;
});
$("#claim").change(function(){
$("#area").find(".field").remove();
//or
$('#area').remove('.field');
if( $(this).val()=="Insurance")
{
$("#area").append("<input class='field' name='cost' type='text' placeholder='Cost' />");
}
});
});
</script>
</head>
<body>
<div id="add">
<form name="form1aa" method="post" id="form1a" >
<div id="area">
<input type=text name="cases" placeholder="Cases ID">
<select id="claim" name="claim">
<option value="">Select a Claim</option>
<option value="Insurance">Insurance</option>
<option value="Warranty">Warranty</option>
</select>
</div>
<select name="type" onChange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="">Select One</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<br />
<input type=text name="comment" placeholder="Comments Box">
<input type="submit" value="Submit" name="Submit">
</form>
</div>
<?
$sql="SELECT * FROM $tbl_name ORDER BY cases ASC";
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%' ORDER BY cases ASC";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%' ORDER BY cases ASC";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%' ORDER BY cases ASC";
}
$result=mysql_query($sql);
?>
<!-- Filter p1 (Start of) !-->
<form action="ajax-with-php.php" target="_self">
<input type="submit" name="all" value="All" /> // the issue is mainly occuring here when i click any of thesse meant to refesh the page and change the query with the if statements but is trigger the other code i commented
<input type="submit" name="tpc" value="TPC" />
<input type="submit" name="drc" value="DRC" />
<input type="submit" name="bsc" value="BSC" />
</form>
$('form').bind('submit', function(){ ...
will bind to all forms. Change it to
$('form#form1a').bind('submit', function(){ ...
and it will only bind to the first form, not the second.
$('form').bind('submit', function(event){
event.preventDefault();
$.ajax({...
Try making the changes above 1) adding the event argument to your callback 2) executing the .preventDefault() method. When using AJAX with the submit event this is neccessary to stop the page from reloading and interrupting your async request.
There may be more issues than that, but hopefully that will get you on the right track.

Resources