How to get value of json web API using VueJS - javascript

I am new to Vue.JS. Actually I am trying to get Name of bank by typing routing number.
API: https://www.routingnumbers.info/api/name.json?rn=011103093
export default {
data: function () {
return {
picker: new Date().toISOString().substr(0, 7),
resultsArray: {
'name' : '',
'message' : '',
'code' : '',
'rn' : ''
},
}
}
}
methods: {
/* searchBasedOnMonthAndType() {
let app = this;
app.modeldailog = false
app.rows = [];
app.renderInvoicesBasedOnMonth(app.picker);
},*/
getBankName() {
let app = this;
app.rows = [];
var rn = '011103093';
$.ajax({
url: 'https://www.routingnumbers.info/api/name.json?rn=' + rn,
success(res) {
if (res.results != null) {
app.resultsArray = res.results;
} else {
// console.log(app.resultsArray);
// console.log("test after");
alert("data not fetched");
}
}
});
},
}
<label>Routing Number</label>
<input type="text" name="routingNo" v-validate="'required|numeric'" v-model="paymentinfo.routing_no" class="form-control input-sm" v-on:keyup="getBankName();">
<label>Bank Name</label>
<input type="text" name="chck_bank_name" v-validate="'required'" class="form-control input-sm" v-bind:value="resultsArray.name">
I am getting Ajax response null. Everytime else part is being executed.

Maybe you typo in options for $.ajax method. Try this:
getBankName() {
let app = this;
app.rows = [];
var rn = '011103093';
$.ajax({
url: 'https://www.routingnumbers.info/api/name.json?rn=' + rn,
success: (res) => {
if (res != null) {
app.resultsArray = res;
} else {
// console.log(app.resultsArray);
// console.log("test after");
alert("data not fetched");
}
}
});
},
FYI: result of that api call is not array. it's like so:
{"name": "TD BANK NA", "message": "OK", "code": 200, "rn": "011103093"}

Looks like you should use something like this:
$.ajax(...).done(data => {
console.log(data)
}).fail(() => {
console.log('fail')
})
P.S. It's better to use const vm = this; instead of let app = this;. It's de-facto standart in Vue.js

Related

Getting Error on Two Events happening on same time

I'm having the activiti Bpmn file, in that there is having transition of task. While transition I need to create the due date for that new task. my problem is due date and new task happening on same time. because of that I'm getting error.
onClose: function (date) {
if (valid) {
date = Date.parse(date);
if (oldDate !== date) {
var tasks = getSet(context, 'task') || getSet(context, 'tasks'),
trans = Ember.get(context, 'transition') || Ember.get(context, 'propertyMap.transition'),
requestData = [];
if (!tasks.length) {
resolve();
return;
}
if (!trans) {
trans = 'Done';
}
tasks.forEach(function (task) {
requestData.push({ name: 'id', value: (Ember.get(task, 'id') || Ember.get(task, 'currentTask.id') )});
requestData.push({ name: 'transition', value: trans || '' });
});
if (context.get('serviceParams')) {
Object.asAjaxData(context.get('serviceParams')).forEach(function (param) {
requestData.push(param);
});
}
return (Core.services({
type: 'post',
service: 'workflow/task/transition',
data: requestData,
json: true
})
.done(function (res) {
Core.Action('Core:updateTask', context, { dtDue: date });
Core.model.ingestResources(res);
var inspected = Core.controller.detailsObject,
wf = res.workflows || {};
if (inspected) {
Object.keys(wf).forEach(function (w) {
var hist = wf[w].historicalTaskIds;
if (hist.contains(inspected.currentTaskId)) {
inspected.set('currentTaskId', wf[w].openTaskIds[0]);
}
});
}
resolve();
})
.fail(function (xhr, status, error) {
Core.Error.show(error);
})
.always(function () {
tasks.forEach(function (task) {
if (Ember.get(task, 'isClip')) {
Core.model.clip.clear();
}
});
var wfController = Core.Tab.Workflow.getController();
var sel = wfController.get('selection');
wfController.reloadResultSet();
var rs = wfController.get('resultSet');
rs && rs.done(function () {
var s = Ember.Set.create();
rs.get('content').forEach(function (item) {
if (!item) { return; }
s.addObject(item);
});
sel.forEach(function (item) {
if (!s.contains(item)) {
sel.remove(item);
}
});
});
sel.clear();
resolve(tasks);
})
);
}
}
}
In that Core.Action('Core:updateTask', context, { dtDue: date }); is using for updating the duedate. If I use on the top If statement Due Date is updated, but Transistion is not happening. If I'm using on the done function, the transistion is happened and moved to the new Task Id. Because of that it searching Task Id and showing error.
Please provide me suggestion on this. I need to create both the Transistion and meanwhile update the date.

How to search a single cell with multiple values

I'm trying to search a JSON. Right now it functions with an exact match. I want to add multiple data to one cell - it'll look like this: "data, data2, nope, nope2". If a user searches 'data' it needs to match for data and data2.
this is the json:
[
{"car":"Mercedes, Toyota, KIA", "state":"SA", "groupName":"AHG"},
{"car":"BMW","state":"NSW","groupName":"Brighton BMW"},
{"car":"Tesla","state":"VIC","groupName":"JAMES F"},
{"car":"Audi","state":"WA","groupName":"Audi CBD","groupPhone":"1300 04"},
{"car":"Mercedes","state":"SA","groupName":"AHG","groupPhone":"1300 05"}
]
eg the 1st string of- "car":"Mercedes, Toyota, KIA" I need to return results if a user searches for Toyota. Right now it only works if the string is only "car":"Toyota"
var app = new Vue({
el: '#app',
data: {
addCar: false,
cars: [],
loading: false,
searchCar: "",
searchState: ""
},
methods: {
search: function () {
app.loading = true;
var searchQuery = {
car: encodeURIComponent(app.searchCar)
};
if (app.searchState) {
searchQuery.state = app.searchState;
};
Sheetsu.read("https://sheetsu.com/apis/v1.0su/a4d7192e71fd", {
search: searchQuery
}).then(function (data) {
console.log(data);
app.cars = data;
app.loading = false;
},
function (err) {
console.log(err);
app.cars = [];
app.loading = false;
});
},
}
})
Would be amazing if a user can search for Toyota and be delivered results for any string containing Toyota as a car :)
Simple client-side search can be implemented by passing a regular expression object to the String#match method, where the pattern of the regular expression is your query/search string:
/* Returns non-null result is "query" matches any part of item.car string */
return item.car.match(new RegExp(query, "gi"))
You could combine this with Array#filter() to aquire only items for your JSON where the car field contains the query string:
const json = [
{"car":"Mercedes, Toyota, KIA", "state":"SA", "groupName":"AHG"},
{"car":"BMW","state":"NSW","groupName":"Brighton BMW"},
{"car":"Tesla","state":"VIC","groupName":"JAMES F"},
{"car":"Audi","state":"WA","groupName":"Audi CBD","groupPhone":"1300 04"},
{"car":"Mercedes","state":"SA","groupName":"AHG","groupPhone":"1300 05"}
]
const findItem = (data, query) => {
return data.filter(item => {
return item.car.match(new RegExp(query, "gi"))
});
}
console.log("Search for Toyota", findItem(json, "Toyota"));
console.log("Search for Mercedes", findItem(json, "Mercedes"));
console.log("Search for Tesla", findItem(json, "Tesla"));
console.log("Search for Honda", findItem(json, "Honda"));
Update
To integrate the code snippet shown above with your Vue component, try this:
var app = new Vue({
el: '#app',
data: {
addCar: false,
cars: [],
loading: false,
searchCar: "",
searchState: ""
},
methods: {
search: function() {
app.loading = true;
var searchQuery = {
car: encodeURIComponent(app.searchCar)
};
if (app.searchState) {
searchQuery.state = app.searchState;
};
Sheetsu.read("https://sheetsu.com/apis/v1.0su/a4d7192e71fd", {
search: searchQuery
}).then(function(data) {
/*
Add code here
*/
data = data.filter(item => {
return item.car.match(new RegExp(app.searchCar, "gi"))
});
app.cars = data;
app.loading = false;
},
function(err) {
console.log(err);
app.cars = [];
app.loading = false;
});
},
}
})
You can use filter and includes
let arr = [{"car":"Mercedes, Toyota, KIA", "state":"SA", "groupName":"AHG"},{"car":"BMW","state":"NSW","groupName":"Brighton BMW"},{"car":"Tesla","state":"VIC","groupName":"JAMES F"},{"car":"Audi","state":"WA","groupName":"Audi CBD","groupPhone":"1300 04"},{"car":"Mercedes","state":"SA","groupName":"AHG","groupPhone":"1300 05"},{"car":"Toyota, Testing function", "state":"SA", "groupName":"AHG"}]
let selectedKey = 'car'
let selectedValue = 'Toyota'
let op = arr.filter(({[selectedKey]:key})=> key && key.includes(selectedValue))
console.log(op)

Customizing easyAutoComplete

var options = {
url: function (phrase) {
return "location/autoComplete?key=" + phrase;
},
getValue: "cityName",
template: {
type: "custom",
method: function (value, item) {
return value + ", " + item.stateName;
}
},
list: {
onClickEvent: function () {
var selectedLongitude = $("#autoCompleteSearch").getSelectedItemData().longitude;
var selectedLatitude = $("#autoCompleteSearch").getSelectedItemData().latitude;
userPos = {
lat: Number(selectedLatitude),
lng: Number(selectedLongitude)
};
map.setCenter(userPos);
map.setZoom(17)
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 400,
callback: function () {
}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 400,
callback: function () {
}
}
}
};
This is the code I am using right now to fetch a remote webservice data. Now I need to get the data and remove the duplicate "city names". Also I need to show "Data not available" or some custom method when there is no data from the webservice. I am kind of stuck. Would be great if someone could point me on how to achieve this.
You can get rid of duplicates using a helper function:
function removeDuplicates(input) {
if (!input) { //Falsy input
return input;
}
var isArray = Array.isArray(input) ? [] : {};
var items = [];
var output = {};
for (var key in input) {
if (items.indexOf(input[key]) < 0) {
items.push(input[key]);
if (!isArray) {
output[key] = input[key];
}
}
}
return isArray ? items : output;
}
You can show your custom text if Array.isArray(input) ? (input.length === 0) : (Object.keys(input).length === 0 && input.constructor === Object).

Using AutoComple ngTagsInput in Angular JS

In my project, i use ngTagsInput for tagging. I have a problem, I did loadTags. I got from API and I tried to change structure like {text : sometag}. And then my autocomplete tag is not working. even though I use return like tutorial in http://mbenford.github.io/ngTagsInput/demos.
LoadTags to get Data from API
$scope.loadTags = function(query) {
var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
data = {
username: "newshubid",
data: {
orderby: {
field: "label",
type: "DESC"
}
}
};
args = {
"data": JSON.stringify(data)
};
param = $.param(args);
HttpService("POST", url, param, function(response) {
res = angular.fromJson(response.data);
angular.forEach(res, function(item) {
$scope.get_cat = {
text: item.label
};
return $scope.get_cat;
});
});
};
HTML
<tags-input ng-model="tag" class="bootstrap"
replace-spaces-with-dashes="false"
on-tag-added="AttachTag($tag)"
on-tag-removed="RemovedTag($tag)">
<auto-complete source="loadTags($query)"></auto-complete>
</tags-input>
Please help me and give me solution where I find my mistakes. Thank you.
You are using wrong ng-model binding for the tag data
Try, taking $scope.get_cat as an array and push each tag into it.
$scope.loadTags = function(query) {
var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
data = {
username: "newshubid",
data: {
orderby: {
field: "label",
type: "DESC"
}
}
};
args = {
"data": JSON.stringify(data)
};
param = $.param(args);
HttpService("POST", url, param, function(response) {
res = angular.fromJson(response.data);
$scope.get_cat = []
angular.forEach(res, function(item) {
$scope.get_cat.push({
text: item.label
});
});
return $scope.get_cat;
});
};
If you have read the documentation of the ngTagsInput properly.It is written that it expects a promise in return. I have made little change for you in your code. $q service is responsible for promise in angular. Now for this you need to inject $q in your controller. Hope it works.
$scope.loadTags = function(query) {
var url = "http://192.168.0.253:81/agnes/ruang-vemale/api/v1/category/get/3c8dd5e26e7e653c9823728f90fcbadf39c2651e/";
data = {
username: "newshubid",
data: {
orderby: {
field: "label",
type: "DESC"
}
}
};
args = {
"data": JSON.stringify(data)
};
param = $.param(args);
var deferred = $q.defer();
HttpService("POST", url, param,
function(response) {
res = angular.fromJson(response.data);
$scope.get_cat = []
angular.forEach(res, function(item) {
$scope.get_cat.push({
text: item.label
});
});
deferred.resolve($scope.get_cat);
return deferred.promise;
});
};

printing all records using only one alert

I have the following code with the JSFiddle for the same here:
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
$.each(result, function(i, item) {
alert(result[i].PageName);
});
In order to see all the results, I have to click Ok in alert window two times. How can I display the contents using one alert only?
//f1.js ---
var PatientReviewPage = (function () {
var cls = function () { }
var self = cls.prototype;
self.urlKey = "showmrn";
self.getData = function (mrn_) {
/*
if (isEmpty(mrn_)) { alert("Invalid mrn in getData()"); return false; }
// Lookup the AJAX web service URL
var url = regman.getWebServiceURL(self.urlKey);
if (isEmpty(url)) { alert("Invalid URL in getData()"); return false; }
var ajaxRequest = jQuery.ajax({
//beforeSend: TODO: show spinner!
data: {
registry_id: regman.registry.id,
mrn: mrn_
},
dataType: "json",
method: "GET",
url: url
})*/
//Some code related to ajax reques
this.done(function (data_, textStatus_, jqXHR_) {
// Validate the web service and retrieve the status.
if (typeof (data_) === "undefined" || data_ === null) {
alert("Invalid data returned from web service");
return false;
}
if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) {
alert("Invalid web service status");
return false;
}
if (data_.webservice_status.status != "SUCCESS") {
alert(data_.webservice_status.message);
return false;
}
self.processdataDocuments(data_.data_document_list);
});
this.fail(function (jqXHR_, textStatus_, errorThrown_) {
alert("Error in getData(): " + errorThrown_);
return false;
});
};
// Initialize the page
self.initialize = function () {
var mrn = regman.selectedData["mrn"];
if (isEmpty(mrn)) {
alert("Invalid MRN provided by calling page");
return false;
}
self.getData(mrn);
};
self.processdataDocuments = function (collection_) {
if (isEmpty(collection_) || collection_.length < 1) {
// Populate the count and exit
jQuery("#nlpDocumentCount").html("(0)");
return true;
}
var source =
{
localdata: collection_,
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
$("#nlpDocumentPanel").jqxGrid(
{
source: dataAdapter,
width: '1000',
height: 150,
columns: [
{
text: 'Type', datafield: 'nc_type'
},
{
text: 'SubType', datafield: 'nc_subtype'
},
{
text: 'Concept', datafield: 'concept_text'
},
{
text: 'Date', datafield: 'nc_dos'
}
]
});
// For getting the contents of a row, I am using jqxgrid approach as mentioned in their doc here :
// http://www.jqwidgets.com/getting-the-clicked-grid-row/
$("#nlpDocumentPanel").on('rowclick', function (event) {
var row = event.args.rowindex;
var datarow = $("#nlpDocumentPanel").jqxGrid('getrowdata', row);
response = JSON.stringify(datarow, null, 10)
//alert(jsonStringify); // This alert displays the JSON data in a formatted manner
var obj = jQuery.parseJSON(response);
//alert("display Subtype "+obj.nc_subtype) // Works fine
self.mySubtype = obj.nc_subtype;
});
};
//I added this line for the demo to show 'f2' accessing this property from 'f1'. You should remove it if copying this code into your application
self.mySubtype = "Foo";
return cls;
})();
var f1 = new PatientReviewPage();
//f2.js ---
var DocumentDetailsDialog = (function () {
var cls = function () { }
var self = cls.prototype;
alert(f1.mySubtype);
/*this.getData = function (IDNumber_) {
// some code will be here
var ajaxRequest = jQuery.ajax({
// some code will be here
})
.done(function (data_, textStatus_, jqXHR_) {
// some code will be here
})
.fail(function (jqXHR_, textStatus_, errorThrown_) {
// some code will be here
});
};*/
return cls;
})();
var f2 = new DocumentDetailsDialog();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use map() and join() and return string with page names.
var result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
var r = result.map(function(e) {
return e.PageName;
}).join(' ');
alert(r);
Build a string with the results and alert the string:
alert(result.map( _ => _.PageName).join(', '))

Categories

Resources