Creating multidimensional array inside each - javascript

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.

Related

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.

How to use element name when initializing object in javascript?

I'm trying to get data using ajax function, but my code returns :
Uncaught SyntaxError: unexpected string..
Javascript :
var myParams = {
$('#csrf').attr('name') : $('#csrf').val(),
'module' : 'culinary',
'id' : '12',
}
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
success: function(response) {
reponse = $.parseJSON(response);
console.log(response);
}
});
One of my friends suggested to use this:
var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';
But if I use the second method, the PHP function can't recognize the parameters.
What's the correct way to send parameters to an ajax function?
The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:
var myParams = {
'module': 'culinary',
'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();
The second example you have doesn't work because you create an array, ie. [], not an object, {}.
Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
You should define new object {} and not new array [] :
var myParams = [];
Should be :
var myParams = {};
Hope this helps.

Dynamically send parameter in ajax-chosen

I am new to Jquery world.
I have these following codes:
$target.ajaxChosen({
type: 'GET',
url: '<s:url action="getFilterValueJSON" namespace="/cMIS/timetable"></s:url>?filterKey='+keyword,
dataType: 'json',
jsonTermKey: 'filterWord'
}, function (data) {
var terms = [];
mydata = data.valueMap;
$.each(mydata, function (i, val) {
terms.push({ value: i, text: val });
});
return terms;
});
It seems the variable 'keyword' does not dynamically changed its value. The value for 'keyword' comes from an element with on change event. Would someone enlighten me about this on how to solve this? Thanks in advance.
its better you compose your url object just before call
function onclick(keyword)
{
var url = '<s:url action="getFilterValueJSON" namespace="/cMIS/timetable"></s:url>?
filterKey='+keyword;
ajaxCall(url);
}
function ajaxCall(url)
{
$target.ajaxChosen({
type: 'GET',
url: url,
dataType: 'json',
jsonTermKey: 'filterWord'
}, function (data) {
var terms = [];
mydata = data.valueMap;
$.each(mydata, function (i, val) {
terms.push({ value: i, text: val });
});
return terms;
});
}

Passing an array of Javascript classes to a MVC controller?

I am trying to pass an array of services to my controller.
I've tried a bunch of different ways to get it work, serializing the data before going to controller, serializing each service, only thing that seems to work is changing the controller parameter to string and serializing array, then using JsonConvert, but I'd rather not do that.
With the specified code, I am getting the correct number of items in the List, but they all contain a service id with an empty guild, and service provider id is null.
Any ideas?
Javascript
function ServiceItem() {
this.ServiceProviderID = 'all';
this.ServiceID = '';
}
var selecteditems= (function () {
var services = new Array();
return {
all: function() {
return services;
},
add: function(service) {
services.push(service);
}
};
})();
var reserved = [];
$.each(selecteditems.all(), function(index, item){
reserved.push({ ServiceID: item.ServiceID, ServiceProviderID: item.ServiceProviderID});
});
getData('Controller/GetMethod', { items: reserved }, function(result) {
});
var getData = function (actionurl, da, done) {
$.ajax({
type: "GET",
url: actionurl,
data: da,
dataType: "json",
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});
};
Controller
public JsonResult GetMethod(List<CustomObject> items)
{
}
Custom Object
public class CustomObject
{
public Guid ServiceID {get;set;}
public Guid? ServiceProviderID {get;set;}
}
Set the content-type and use POST instead of GET (as it is a list of complex type objects). mark your action with HttpPost attribute too.
See if this works:-
$.ajax({
type: "POST",
url: actionurl,
data: JSON.stringify(da),
dataType: "json",
contentType: 'application/json',
async: true,
success: function (d) {
if (typeof (done) == 'function') {
var str = JSON.stringify(d);
done(JSON.parse(str));
}
}
});

Categories

Resources