Integrating a VIN Decoder API - javascript

I have never integrated an API into any of my app's before. I want to integrate a basic VIN decoder API, that will provide basic vehicle information after a vehicle's VIN is submitted. I want to use the NHTSA Vehicle API as it is free and simple. I am most familiar with Javascript and they provide a code example which I will provide below. How do I integrate this API into my simple HTML form? Thanks for your help!
Link to VIN Decoder: NHTSA VIN Decoder API
HTML:
<!DOCTYPE html>
<html>
<head>
<title>VIN Decoder API Test</title>
<style type="text/css">
input {width: 200px;}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<table align="center">
<tr>
<td align="center">
<input type="text" id="b12" placeholder="VIN - 17 Digits" name="name" maxlength="100">
</td>
</tr>
<tr>
<td align="center">
<button>Submit</button>
</td>
</tr>
<tr>
<td>
<textarea rows="15" cols="100" placeholder="Vehicle Data Presented Here"></textarea>
</td>
</tr>
</table>
</body>
</html>
"Javascript with jQuery, Get Example":
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/GetModelsForMakeId/440?format=json",
type: "GET",
dataType: "json",
success: function(result)
{
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
"Javascript with jQuery, Post Example":
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: "3GNDA13D76S000000;5XYKT3A12CG000000;"},
dataType: "json",
success: function(result)
{
console.log(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});

HTML:
<table align="center">
<tr>
<td align="center">
<input type="text" id="b12" placeholder="Enter VINs-separated by ;" name="b12" maxlength="100"/>
</td>
</tr>
<tr>
<td align="center">
<button id="submit_btn">Submit</button>
</td>
</tr>
<tr>
<td>
<textarea rows="15" cols="100" id="results" placeholder="Vehicle Data Presented Here"></textarea>
</td>
</tr>
</table>
Javascript:
$("#submit_btn").click(function () {
var val = $("#b12").val();
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: val},
dataType: "json",
success: function(result)
{
$("#results").val(JSON.stringify(result));
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
})
I'll leave it up to you to parse the results into what you want to present...

A few different things here. You should read up on how to use APIs using jQuery. Here's a quick but effective example I found elsewhere:
https://www.yogihosting.com/example-jquery-ajax-call-api/
First, set up your HTML to be easy to interact with JavaScript by adding an id to your button and your textarea elements:
<button id="btn_submit">Submit</button>
<textarea id="txt_results" rows="15" cols="100" placeholder="Vehicle Data Presented Here"></textarea>
Next, add an event listener for when the Submit button is clicked:
document.getElementById("btn_submit").onclick = function () {
var vin;
vin = document.getElementById("b12").value;
if (vin.length === 17) {
getNHTSADataByVIN(vin);
}
};
Now the fun part. In jQuery's AJAX calls, you get to decide what happens with the data you recieve from the call in the success parameter. In the API's example usage, you are able to do whatever you want with the result parameter once it is returned. Here is a function that will pass the result object into a function that will display the results (that we are about to write):
function getNHTSADataByVIN (param_vin) {
$.ajax({
url: "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/",
type: "POST",
data: { format: "json", data: param_vin },
dataType: "json",
success: function(result)
{
console.log(result);
displayNHTSAResults(result);
},
error: function(xhr, ajaxOptions, thrownError)
{
console.log(xhr.status);
console.log(thrownError);
}
});
};
Finally, we create a function that takes the properties inside of the result objects and writes them out to the text area if the property isn't empty:
function displayNHTSAResults (param_data) {
var output_text = "";
for (var i = 0; i < param_data.Results.length; i++) {
var result = param_data.Results[i];
for (var prop in result) {
if (result.hasOwnProperty(prop) && result[prop] !== "") {
output_text += prop + ": " + result[prop] + "\n";
}
}
}
document.getElementById("txt_results").value = output_text;
};
Of course, there are many ways to do this, but hopefully this serves as a good simple demonstration of API usage.

async function CheckVin(vin) {
var response = await fetch(`https://vpic.nhtsa.dot.gov/api/vehicles/decodevin/${vin}?format=json`);
let result = await response.json();
result = result.Results.reduce((accumulator, crr) => {
if (crr.Value && crr.Value != 'Not Applicable') {
accumulator[crr.VariableId] = {
variable: crr.Variable,
value: crr.Value
}
}
return accumulator;
}, {})
if(result['143'].value !== '0'){
throw result['191'].value;
}
return result;
}

Related

Post Data from MCV is not calling JS function

Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);

How to update the Model value and reload a div in Razor view in MVC

This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}

MVC Javascript table reload issue

I have a table that is being populated dynamically, and a reload script that refreshes it ever 60 seconds.
<script type="text/javascript" language="javascript">
window.setInterval(function () {
$('#divGrid').load('Home/Index #divGrid>table');
}, 60000);
</script>
I also have a Javascript that calls a partial view on table row click:
<script type="text/javascript" language="javascript">
function showOpenTrData() {
$('#OpenTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetails/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
function showClosedTrData() {
$('#ClosedTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetailsClosed/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
I had it at first without an onclick function but then upon reload it would stop working so I changed it to onclick function, however first time after reload I have to double click the row and after that for the period of 60 seconds till next reload its all fine, after it reloads I have to double click the first time again. Its driving me up the wall.
Please help!
HTML
<table class="table" id="OpenTickets" style="overflow-y:scroll;width:70%;float:left; margin-top:-25px; display:block;">
<tbody>
#foreach (var item in Model.ticketModel.OrderByDescending(x => x.ticket.ID).Where(x => x.ticket.StatusID == 1))
{
<tr onclick="showOpenTrData()">
<td class="columnID" id="ticketID">
#Html.DisplayFor(modelItem => item.ticket.ID)
</td>
<td class="columnSummary">
#Html.DisplayFor(modelItem => item.ticket.Summary)
</td>
<td class="columnAssignee" id="ajaxTest">
#if (item.ticket.Assigned_to_UserID == null || item.ticket.Assigned_to_UserID == 0)
{
#Html.Label("Unasigned")
}
else
{
#Html.DisplayFor(modelItem => item.assignedUser.First_name)
<text> </text>
#Html.DisplayFor(modelItem => item.assignedUser.Last_name)
}
</td>
<td style="font-size:11px; width:10%" class="columnUpdated">
#if ((item.ticket.updated_at == null))
{
#Html.DisplayFor(modelItem => item.ticket.Created_at)
}
else
{
#Html.DisplayFor(modelItem => item.ticket.updated_at)
}
</td>
</tr>
}
</tbody>
</table>
i got it - if anyone else struggles here is the breakdown.
.load method renders any javascript useless as its not part of the same instance any more, hovever on click is a solution but how do you get the object reference?
you pass this in the on click function.
onclick="showTableData(this)"
then you can use the passed event to acquire data from it
cheers
The basic problem here is that you are mixing onclick=... with jQuery bindings .click(...). It is possible to use both on the same page but it becomes confusing and is harder to maintain: Pick one.
The easiest thing (based on your current code) is to kill the jQuery bindings. Try this:
<script type="text/javascript" language="javascript">
function showOpenTrData(ptr) {
$.ajax({
url: 'Home/TicketDetails/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
function showClosedTrData(ptr) {
$.ajax({
url: 'Home/TicketDetailsClosed/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
</script>
Each time the showOpenTrData or showClosedTrData was running, it was adding another jquery bind. If you open your console and check the networks tab you'll see that the ajax functions are then being run multiple times with one click (after the second click).
If you want to just use jQuery, then use this:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#OpenTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetails/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
$('#ClosedTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetailsClosed/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
Also, delete the onclick=... section in the html or you'll get javascript errors because it is looking for a function that doesn't exist.
EDIT:
I added in the ticketId you needed.

How to validate data in an AJAX call

I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});

Angular js Button click

I have created a button which on click gives an ajax call and the server response obtained through ajax is binded to table using angular js. The issue is according to me on first click of the button itself the data must appear on the webpage.But this happens on second click of the button.I am able to sort and filter data properly but the problem is i need to click button two times separately before it fetches the table
<script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
// enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div>
Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>
You problem is, you are using $.ajax. which won't running digest cycle resultant the binding will not update on html/scope. You must use $http instead of $.ajax, If you use $http angular will run digest cycle when the ajax completed.
Code
$http({ //<-- make sure you have added $http dependency on controller
method: "POST",
url: "ASSIGN.aspx/OnDataFetch",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).
success(function(response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
}).
error(function(response) {
alert(response.d);
})
Use jQuery ajax while angular provided you $http is problematic
and considered as bad practice.
Define you controller like this:
fooddata.controller("myCtrl", function ($scope, $http) {
And then do this do run ajax
$scope.binddata = function(){
var request = $http({
method: "post",
url: "yourAjaxFile.php",
data: {
//data
},
//contentType,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
$scope.foods = data;
});
}
In case of Async calls like $.ajax(), the angular scope is no longer updated on inside events. So you need to do $apply manually to apply the updates or you can go forward with any of the other solutions provided by others. They too work well.
<html><head><script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
if(!$scope.$$phase)
$scope.$apply();
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div> Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>
</html>

Categories