How to get nested JSON data values with a "data-" attribute? - javascript

I'm trying to create an elegant way of binding json data to html using data-attributes without having to write a bunch of custom code or using an external library/framework.
I can get this to work just fine without nested data and re-writing my function a little.
The problem is that it's reading my data-api-value as a string..so I'm trying to find the correct way to convert it. I'm open to other suggestions/ work-arounds though.
Here's the code in a (codepen)
Here's a dumb'd down version of the code
function getApiData(apiUrl, callback) {
apiData = $.ajax({
type: 'GET',
url: apiUrl,
dataType: 'json',
success: function(json) {
callback(json.data);
},
error: function(req, err) {
console.log(err);
},
contentType: "application/json; charset=utf-8"
});
}
function dataAPIrealtime() {
const url = 'https://someapi/v1/exchange/getinstrument/bitmex/XBTUSD';
getApiData(url, function(apidata){
$('[data-api]').each(function() {
let api = $(this).data("api");
let value = $(this).data("apiValue");
let data = apidata + value;
if (data || data != data) {
$(this).html(data);
}
});
});
}
/* Run Functions
*********************************/
$(document).ready(function() {
dataAPIrealtime();
setInterval(dataAPIrealtime, 1000); // Refresh data every 1 second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-api="exchange/getinstrument" data-api-value="[instrument][symbol]"></span>

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

jQuery autocomplete ajax not working for autocorrection when wrong input is given

I'm trying to make a project similar to Google's search bar using Flask, Elasticsearch and jQuery that will automatically suggest based on input given and also automatically give correct suggestions when a wrong input is given. I've had success with the autosuggestion with correct spellings but when giving a wrong input, the correct suggestion data from Elasticsearch comes up in browser console but doesn't appear in the autocomplete drop-down. I inserted data into Elasticsearch using PySpark. I think the problem is related to the JS file but don't know if it's my JS file or the jquery-ui file. What am I doing wrong?
JS:
$(document).ready(function () {
const $source = document.querySelector('#source');
const $result = document.querySelector('#result');
const typeHandler = function (e) {
$result.innerHTML = e.target.value;
console.log(e.target.value);
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: { 'data': e.target.value },
success: function (html) {
var data = html.aggregations.auto.buckets
var bucket = []
$.each(data, (index, value) => {
bucket.push(value.key)
});
console.log(bucket)
$("#source").autocomplete({
source: bucket
});
}
});
}
$source.addEventListener('input', typeHandler)
});
Correct Input:
Incorrect Input:
Correct data for Incorrect Input
Consider the following example.
$(function() {
const $source = $('#source');
const $result = $('#result');
$source.autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax_call",
type: 'POST',
dataType: 'json',
data: {
'data': request.term
},
success: function(html) {
var data = html.aggregations.auto.buckets;
var bucket = [];
$.each(data, (index, value) => {
bucket.push(value.key);
});
console.log(bucket);
response(bucket);
}
});
}
});
});
See More:
https://jqueryui.com/autocomplete/#remote-jsonp
https://api.jqueryui.com/autocomplete/#option-source

How to get array from localstorage in Firebase Cloud Functions?

After sending the localStorage to server the const arrayOrders is showing up as empty even it contains values in client side.
I've tried to do that with this way but it not works.
Here is my code from server side and client side for requests handle.
What's wrong?
In server side :
exports.wip = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const url = `${req.protocol}://${req.get('host')}/work-in-process`;
const tokenId = req.get('Authorization').split('Bearer ')[1];
const arrayOrders = req.headers['service']; // {}
const wipReq = JSON.stringify({
operator: req.body.uid,
conditions: req.body.status,
service_list: {
orders: [arrayOrders]
}
})
return admin.auth().verifyIdToken(tokenId)
.then((decoded) => {res.redirect(302, url.href)})
.catch((err) => res.status(401).send(err));
});
});
In client side :
$(function() {
'a long time ago user recorded a' localStorage.setItem("service_array", array);
$('.SubForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/wip',
data: $(this).serialize(),
success: function(data) {
if (data.status) {
$.ajax({
type: 'get',
url: 'http://localhost:3000/wip',
beforeSend: function(xhr) {
xhr.setRequestHeader('service', localStorage.getItem("service_array"));
},
success: location.href = "http://localhost:3000/wip"
})
}
}
});
e.preventDefault();
});
});
Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads. The keys and the values are always strings (note that, as with objects, integer keys will be automatically converted to strings). You can access these values like an object, or with the Storage.getItem() and Storage.setItem() methods.
From: https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
So storing an array in localStorage may have mixed results. I would suggest:
$(function() {
var data = [];
var storeData = JSON.stringify(data);
localStorage.setItem("service_array", storeData);
$('.SubForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'http://localhost:3000/wip',
data: $(this).serialize(),
success: function(data) {
if (data.status) {
$.ajax({
type: 'get',
url: 'http://localhost:3000/wip',
beforeSend: function(xhr) {
xhr.setRequestHeader('service', localStorage.getItem("service_array"));
},
success: function(){
location.href = "http://localhost:3000/wip";
}
});
}
}
});
e.preventDefault();
});
});
It was not clear from your example where array was defined. Basically, you can use JSON.stringify() or $.param() to convert the Array data into String that can be stored to localStorage. Depending on your needs, you can convert it when you get the String back into an Array.
Hope that helps.

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

how to serve data from multiple urls (languages) from wikipedia API

Some data I need is only available in the es (spanish version) of wikipedia and this is breaking my script I am using this tidbit to call the data as you can see it calls from https://en.wikipedia.org/w/api.php but this particular data is only available from https://es.wikipedia.org/w/api.php
However I still need the english data as well
So how can i convert this to fetch from both api urls my knowledge of JS is minimal so please bear that in mind when replying thanks
$.ajax({
url: 'https://en.wikipedia.org/w/api.php',
data: {
format: 'json',
action: 'parse',
page: this_target,
prop:'text',
section:0,
},
dataType: 'jsonp',
success: function (data) {
//console.log(data)
$(id_target).find('.o-modal__inner').html('');
$(id_target).find('.o-modal__title').html('').hide();
$(id_target).find('.o-modal').addClass('isOpen');
if(!$(id_target).find('.a-more').hasClass('isActive')){
$(id_target).find('.a-more').trigger('click');
}
var markup = data.parse.text['*'];
var i = $('<div></div>').html(markup);
i.find('a').each(function() { $(this).replaceWith($(this).html()); });
i.find('sup').remove();
i.find('.mw-ext-cite-error').remove();
setTimeout(function() {
$(id_target).find('.o-modal__title').html( data.parse.title).fadeIn(300);
$(id_target).find('.o-modal__inner').html($(i).find('p'));
$(id_target).find('.a-loader').hide();
}, 1000);
}
});
});
You could check for data.error in top of success callback and if so for english page, resend ajax request just by replacing the subdomain:
if (data.error && new URL(this.url).hostname === "en.wikipedia.org") {
this.url = this.url.replace('en', 'es')
$.ajax(this);
return;
} else if(data.error) {
console.log('No data to display from both english & spanish wiki');
return;
}

Categories

Resources