How to get array from localstorage in Firebase Cloud Functions? - javascript

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.

Related

javascript to filter json and return another value

I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]

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 nested JSON data values with a "data-" attribute?

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>

Creating multidimensional array inside each

I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

Categories

Resources