jquery autocomplete not insert id - autocomplete

here is my code
$(this).ready( function() {
$("#id").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>autocomplete/lookup",
dataType: 'json',
type: 'POST',
data: req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select:
function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
});
i the id for selected label not inserting will , so how to retrive id to insert in a form

Related

how can I parse this javascript array using Map function?

I want to parse the below JavaScript array for using in Autocomplete control.
The requirement is to display the value field in autocomplete textbox and store the key field as itemID.
{"Key":9886,"Value":"xxx"},{"Key":9887,"Value":"yyy"},{"Key":5634,"Value":"zzz"},{"Key":9888,"Value":"abcd"}
I tried the below code to map this array as source for my textbox:
var itemID;
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data:JSON.stringify({'term' :request.term}),
dataType: 'json',
contentType: 'application/json',
success: function(data) {
response(
$.map(data,
function(object) {
return {
label: object.value,
value: object.key
}
})
)
},
error: function(xhr, status, error) {
alert(error);
}
});
},
minLength: 2,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.value);
itemID = ui.item.key;
}
});```
Appreciate any help on this.
The below code worked to map autocomplete source to dictionary array:
$("#txtbox").autocomplete({
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'controller/Getdata',
data: JSON.stringify({ 'term': request.term }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var parsedData = JSON.parse(data);
var arr = $.map(parsedData,
function (item) {
return {
label:item.Value,
value:item.Key
}}
);
response(arr);
},
error: function (xhr, status, error) {
alert('here');
var array = [];
response(array);
}
});
},
minLength: 3,
select: function (e, ui) {
e.preventDefault();
$("#txtbox").val(ui.item.label);
userID = ui.item.value;
}
});
The controller code which returns dictionary was this:
public ActionResult Getdata(string term)
{
var itemList= Provider.GetAllItems();
var filteredItems = itemList.Where(x => x.Value.Contains(term));
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string result = javaScriptSerializer.Serialize(filteredItems );
return Json(result, JsonRequestBehavior.AllowGet);
}

make a path that increments the count

I'm trying to make a post request that will increment my schema using express and mongoose,
which is :
const ItemSchema = new Schema({
formName: String,
inputs: [
{
inputLabel: {
type: String,
required: true
},
inputType: {
type: String,
required: true,
enum: ['text', 'color', 'date', 'email', 'tel', 'number']
},
inputValue: {
type: String,
required: true
}
}
],
numOfSubs: { type: Number, default: 0 }
});
for my code purposes I want to make a route that will increase by 1 the numOfSubs everytime I use it,since there are a few listings, I have the ID so I need to search it, and I'm not sure how to write the path
router.post('/increase', (req, res) => {
"find and increase by 1 "
});
and I will use the fetch like so:
fetch('/api/items/increase', {
method: 'POST',
body: JSON.stringify({ _id }),//the ID I of the collection I want to increment
headers: {
'content-type': 'application/json'
}
});
try this using mongo $inc operator
router.post('/increase', (req, res, next) => {
const _id = req.body._id;
MyModel.findByIdAndUpdate(_id , { $inc: {numOfSubs: 1} }, { new: true }, (err,updateRes)=>{
if(err) return next(err);
return res.json({sucess: true});
});
});

JqxScheduler Customization dialog

I want to customize the dialog box in jqx scheduler dialog box title. Instead of 'Create new appointment' i want to display "Create a new business schedule".
I work with python django so in the code there are some elements from django template code. So far i create , edit, delete appointments with ajax and django as backend.
var items;
function setAvailability(price_data,persons_data,start_date,end_date, id, a_type, description){
availability_data = {
pk : "{{form.instance.pk}}",
csrfmiddlewaretoken: "{{ csrf_token }}",
price:price_data,
persons:persons_data,
from_date:start_date,
to_date:end_date,
a_type_data:a_type,
av_description:description
}
if(id) {
availability_data['event'] = id;
}
$.ajax({
url: "{% url 'set-availability' %}",
method: "POST",
data: availability_data,
dataType: "json",
success: function(response){
var source = {
datatype: "json",
dataFields: [
{ name: 'id', type: 'integer' },
{ name: 'description', type: 'string' },
{ name: 'location', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'price', type: 'number' },
{ name: 'persons', type: 'number' },
{ name: 'subject', type: 'integer' },
{ name: 'start', type: 'date', format: "yyyy-MM-dd"},
{ name: 'end', type: 'date', format: "yyyy-MM-dd"}
],
id: 'id',
url: "{% url 'get-availability' %}?pk={{form.instance.pk}}"
};
var adapter = new $.jqx.dataAdapter(source);
$("#scheduler").jqxScheduler({
source: adapter
})
return response;
}
})
}
$.ajax({
url: "{% url 'get-availability' %}",
method: "GET",
data: { pk : "{{form.instance.pk}}" },
dataType: "json",
success: function(response){
items = response;
var source = {
datatype: "array",
dataFields: [
{ name: 'id', type: 'integer' },
{ name: 'description', type: 'string' },
{ name: 'location', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'price', type: 'number' },
{ name: 'persons', type: 'number' },
{ name: 'subject', type: 'integer' },
{ name: 'start', type: 'date', format: "yyyy-MM-dd"},
{ name: 'end', type: 'date', format: "yyyy-MM-dd"}
],
id: 'id',
localData: items
};
var adapter = new $.jqx.dataAdapter(source);
$("#scheduler").jqxScheduler({
date: new $.jqx.date(2018, 02, 01),
width: 850,
height: 600,
source: adapter,
editDialogDateTimeFormatString: 'yyyy-MM-dd',
editDialogDateFormatString: 'yyyy-MM-dd',
showLegend: false,
localization: { editDialogStatuses: {
available: "Available",
booked: "Booked"
}},
renderAppointment: function(data)
{
if (data.appointment.status == "available") {
data.style = "#B8E6A3";
}
else if (data.appointment.status == "booked") {
data.style = "#FF0013";
}
return data;
},
ready: function () {
$("#scheduler").jqxScheduler('ensureAppointmentVisible', 'id1');
},
resources:
{
colorScheme: "scheme05",
dataField: "id",
source: new $.jqx.dataAdapter(source)
},
appointmentDataFields:
{
id: "id",
description: "description",
location: "location",
subject: "subject",
price: "price",
persons: "persons",
status: "status",
calendar: 'calendar',
from: "start",
to: "end",
},
view: 'monthView',
views:
[
'monthView'
],
renderAppointment: function (dialog, fields, renderAppointment) {
console.info('render appointment:', dialog);
},
editDialogCreate: function (dialog, fields, editAppointment) {
fields.repeatContainer.hide();
fields.subjectContainer.hide();
fields.timeZoneContainer.hide();
fields.colorContainer.hide();
fields.resourceContainer.hide();
fields.allDayContainer.hide();
fields.locationContainer.hide();
fields.fromContainer.hide();
fields.toContainer.hide();
fields.fromLabel.html("Start");
fields.toLabel.html("End");
var priceField = ''
var personsField = ""
priceField += "<div>"
priceField += "<div class='jqx-scheduler-edit-dialog-label'>Price</div>"
priceField += "<div class='jqx-scheduler-edit-dialog-field'><input type='number' id='price' step='0.01' /></div>"
priceField += "</div>"
personsField += "<div>"
personsField += "<div class='jqx-scheduler-edit-dialog-label'>Persons</div>"
personsField += "<div class='jqx-scheduler-edit-dialog-field'><input type='number' id='persons' /></div>"
personsField += "</div>"
var i = 0;
$('#dialogscheduler').children('div').each(function () { // loop trough the div's (only first level childs) elements in dialogscheduler
i += 1;
if (i == 2) { // places the field in the third position.
$(this).after(priceField);
$(this).after(personsField);
};
});
},
editDialogOpen: function (dialog, fields, editAppointment) {
console.info(dialog);
fields.repeatContainer.hide();
}
});
$('#scheduler').on('editDialogOpen', function (event) {
var args = event.args;
var appointment = args.appointment;
if(appointment){
$('#dialogscheduler > div').find('#price').val(appointment.price);
$('#dialogscheduler > div').find('#persons').val(appointment.persons);
}
else {
$('#dialogscheduler > div').find('#price').val(0);
$('#dialogscheduler > div').find('#persons').val(0);
$('#dialogscheduler > div').find('#from').val('');
$('#dialogscheduler > div').find('#to').val('');
$('#dialogscheduler > div').find('#description').val('');
$('#dialogscheduler > div').find('#status').val();
}
});
$('#scheduler').on('appointmentAdd', function (event) {
var price_data = $('#dialogscheduler > div').find('#price').val();
var persons_data = $('#dialogscheduler > div').find('#persons').val();
var a_type = event.args.appointment.status;
var description = event.args.appointment.description;
var start_date = event.args.appointment.from.toString();
var id = null;
var end_date = event.args.appointment.to.toString();
var availability = setAvailability(price_data,persons_data,start_date,end_date,id, a_type, description);
});
$('#scheduler').on('appointmentDelete', function (event) {
var id = event.args.appointment.id;
deleteEvent(id);
});
$('#scheduler').on('appointmentChange', function (event) {
var id = event.args.appointment.id;
var price_data = $('#dialogscheduler > div').find('#price').val();
var persons_data = $('#dialogscheduler > div').find('#persons').val();
var description = event.args.appointment.description;
var a_type = event.args.appointment.status;
var start_date = event.args.appointment.from.toString();
alert(start_date);
var end_date = event.args.appointment.to.toString();
var availability = setAvailability(price_data,persons_data,start_date,end_date,id, a_type,description);
});
}
})
function deleteEvent(pk) {
$.ajax({
url: "{% url 'delete-availability' %}",
method: "GET",
data: { pk : pk, business_pk:'{{form.instance.pk}}'},
dataType: "json",
success: function(response){
console.info(response)
}
})
}
I think you need to put the below code snippet in the editDialogOpen() function. This is working for me.
setTimeout(function() {
dialogRef.find("div").first().find("div").first().html("Create a new business schedule");
}, 10);
You can use the localization to do it. I'm using jqxScheduler with Angular, so:
Add [localization]="localization" into the component definition that should looks like:
<jqxScheduler #scheduler [editDialogCreate]="editDialogCreate" [localization]="localization">
Add a localization property into the component class. jqxScheduler has different titles for create and edit appointents:
localization = {
editDialogTitleString: 'Edit a business schedule',
editDialogCreateTitleString: 'Create a new business schedule'
};
jQWidgets has implementation examples to other languages. JQuery here.
$("#scheduler").jqxScheduler({
localization: {
editDialogCreateTitleString: "Create a new business schedule",
},
});

Share custom story with staged image on Facebook using FB.ui no working

I have the following code that stage the canvas image and then create object to share it using FB.ui. Staging the image and create the object are working without problem but the share dialog not displayed. If I replaced the image parameter in create object with an image url it is working.
is there any wrong in my code:
var userAccessToken = $("#user_access_token").val();
var appAccessToken = $("#app_access_token").val();
try {
blob = dataURItoBlob(dataURL);
} catch (e) {
console.log(e);
}
var fd = new FormData();
fd.append("access_token", userAccessToken);
fd.append("file", blob);
try {
var imageURI;
$.ajax({
url: "https://graph.facebook.com/me/staging_resources",
type: "POST",
data: fd,
processData: false,
contentType: false,
cache: false,
success: function (data) {
console.log("success " + data['uri']);
imageURI = data['uri'];
},
error: function (shr, status, data) {
console.log("error " + data + " Status " + shr.status);
},
complete: function () {
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:true
},
description: ""
}
},
function(response) {
var objectId = response['id'];
FB.ui({
method: 'share_open_graph',
action_type: 'myappnamespace:myaction',
action_properties: JSON.stringify({
myobject:objectId
})
}, function(response){});
}
);
}
});
} catch (e) {
console.log(e);
}
finally I found the solution by changing user_generated parameter from true to false
now the code for creating object looks like below:
FB.api(
'https://graph.facebook.com/app/objects/myappnamespace:myobject',
'post',
{
access_token : appAccessToken,
object:{
app_id: myappid,
url: "myappurl",
title: "Sample Photo",
image: {
url:imageURI,
user_generated:false
},
description: ""
}
}

Multiple routing urls for single service AngularJS

I have multiple URL paths that I would like to map to a single resource. However I am unsure how to change the URL based on the function called. For example the :dest mapping for query would be /allProducts, however destroy would be something along the lines of /delete/:id
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/:dest', {}, {
query: {method: 'GET', params: {}, isArray: true },
save: {method: 'POST'},
show: { method: 'GET'},
edit: { method: 'GET'},
update: { method: 'PUT'},
destroy: { method: 'DELETE' }
});
}]);
For each action you can override the url argument.
Specially for this is the url: {...} argument.
In your example:
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/', {}, {
query: {method: 'GET', params: {}, isArray: true },
save: {method: 'POST', url: 'service/products/modifyProduct'},
update: { method: 'PUT', url: 'service/products/modifyProduct'}
});
}]);
I just needed to put the url in as the param.
service.factory('ProductsRest', ['$resource', function ($resource) {
return $resource('service/products/:dest', {}, {
query: {method: 'GET', params: {dest:"allProducts"}, isArray: true },
save: {method: 'POST', params: {dest:"modifyProduct"}},
update: { method: 'POST', params: {dest:"modifyProduct"}},
});
}]);