Pull external JSON URL labels and values to new Array - javascript

In my fiddle http://jsfiddle.net/UGYzW/319/ data is from local source at the moment and is simply called 'data'. How would I pull back data from external values? Please use either http://echo.jsontest.com/key/value/one/two and pull back the value 'mralexgray' from the first login item. Do we need to push out the items to a new array or not?
Finally is it better to use JSONP, JSON or .AJAX?
var data =[
{'label':'Core','value':1},
{'label':' Selectors','value':2},
{'label':'Events' ,'value':3}];
var nameArray = data.map(function(item){
return {value: item.value, label: item.label};
});
$("#meta-area").autocomplete({
source:nameArray,
select: function(e, ui) {
e.preventDefault() // <--- Prevent the value from being inserted.
$("#meta_search_ids").val(ui.item.label);
$(this).val(ui.item.value);
}
});
//alert("this loaded");

Since you created your data variable as an Array, after your ajax response push all the variables to an array. Later on same script will work with the map function
jsfiddle example here
$.ajax({
url:'https://api.github.com/users/mralexgray/repos',
success:function(data) {
var dataArray = [];
for(var i=0;i<data.length;i++){
dataArray.push(data[i]);
console.log(data[i]);
}
var nameArray = dataArray.map(function(item){
return {value: item.owner, label: item.name};
});
$("#meta-area").autocomplete({
source:nameArray,
select: function(e, ui) {
e.preventDefault();
$("#meta_search_ids").val(ui.item.label);
$(this).val(ui.item.value);
}
});
}
});

Related

how can i filtering data from Firebase rt-db using javascript

I need to print in console value of key temp but no things displayed
var database=firebase.database();
var ratingRef = firebase.database().ref("sensors/temp/");
ratingRef.orderByValue().on("value", function(data) {
data.forEach(function(data) {
console.log( data.val());
});
});
There's no need for using orderByValue. You have direct reference to the temp child so the data (which is a DataSnapshot) contain the value of temp only.
var ratingRef = firebase.database().ref("sensors/temp");
ratingRef.on("value", function(data) {
console.log(`Temp: ${data.val()}`)
});

jQuery Post not posting multidimentional array data

I have a variable amount of tabs with custom forms on them I am trying to post the data from.
my solution was to make an array containing another array for each tab. then post that multidimensional array to my controller.
$("#savetabs").click(function()
{
$("body").addClass("loading");
var $alltabdata = [];
$("#customtabs-holder").children().each(function() {
$tablename = $(this).attr('id');
$thistabdata = [];
$inputs = $(this).find("input");
$.each($inputs, function( index, value ) {
$thistabdata[$(this).attr("name")] = $(this).val();
});
$selects = $(this).find("select");
$.each($selects, function( index, value ) {
$thistabdata[$(this).attr("name")] = $(this).val();
});
$alltabdata[$tablename] = $thistabdata;
});
console.log($alltabdata);
posting = PostTabData($client_id, $alltabdata);
posting.done(function( data ) {
$("body").removeClass("loading");
console.log(data);
alert(data);
});
posting.fail(function() {
$("body").removeClass("loading");
alert( "Failed to post tab info" );
});
});
function PostTabData($client_id, $tabdata) {
console.log($tabdata);
debugger;
return $.post("/CustomTables/Contents/Save",
{
client_id: $client_id,
alltabdata: $tabdata,
});
}
the console.log before the post displays the correct info, But the tab data doesn't end up in my controller and when i check chromes developer tools under the network option it shows the sent data as only consisting of the client_id field
Change your variables to objects:
from [] to {}
In javascript exist only Array with numeric keys. Associative Arrays not exists in javascript.
Check this snippet to fill the difference:
//array
var arr=[];
arr["name"]="Example name";
console.log("Here array log:");
console.log(arr);
//object
var obj={};
obj["name"]="Example name";
console.log("Here object log:");
console.log(obj);

Retrieve data from Chrome localStorage

I have an Array storing objects each with another array inside. I'm using the Chrome Storage API to store these objects (for an extension). Writing data works fine, but I can't seem to extract the data I need:
Write to storage:
function writeToStorage(form) {
var formObjectsArr = [];
var data = [];
var formData;
$(':input', '#' + form)
.each(function() { data.push(this.value); })
.promise()
.done(function() {
var formData = new Form(data);
formObjectsArr.push(formData);
chromeStorage(formObjectsArr);
});
}
function chromeStorage(formObjectsArr) {
chrome.storage.sync.set({list:formObjectsArr}, function() {
console.log('Settings saved');
});
}
function Form(data) { this.data = data; }
Read from storage (not sure what to do here - the current function simply returns an object which contains an array which contains the object that contains the array I want to access):
function getFromStorage() {
chrome.storage.sync.get({list:[]}, function(test) {
console.log(data)
});
}
You can specify a string, array of strings, or a object dictionary to retrieve data stored in chrome extension's local or sync storage. Since you only want to retrieve the list keyed data, you can just use a string for the first argument of the sync.get method.
function getFromStorage() {
chrome.storage.sync.get("list", function(data) {
console.log(data);
});
}

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

Loop through a JSON responseText array using the keys with Javascript

Using Javascript. I'm trying to loop through an array encoded with JSON. Here is a sample of the array:
{"test1":"some info","test2":"more info","test3":"more stuff"}
Inside each loop I am checking to see if a DIV id exists with the name of the keys.
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
I'm using a for() loop, but I can't get it to work. If I remove the for() loop it works just fine if I search for only 1 DIV id.
for(var key in responseText)
Here is the script. Does anyone know how I can loop through the array from responseText using the array keys as the names of the DIV id's?
<script>
function loadInfo() {
var req = new Request({
method: 'get',
url: 'getinfo.php,
noCache: true,
onRequest: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', 'Loading');
}
}
},
onComplete: function(responseText, responseHtml) {
if (JSON.decode(responseText) != null) {
var data = JSON.decode(responseText);
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', data[key]);
}
}
}
},
onFailure: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', '-');
}
}
}
}).send();
}
window.addEvent('domready', function() {
loadInfo();
});
</script>
You have to decode the JSON before you iterate over the keys. So, where you say:
for(var key in responseText) {
replace that with:
for(var key in data) {
assuming
var data = JSON.decode(responseText);
Also, some of your callback functions don't specify responseText as a parameter. If you want to access this for each callback, you have to explicitly include responseText as a parameter. Example:
onRequest: function(){
should be:
onRequest: function(responseText){
I think the problem is that you're using the wrong variable name.
var data = JSON.decode(responseText);
for(var key in responseText) {
Should read
var data = JSON.decode(responseText);
for(var key in data) {
Note that instead of responseText after in, it reads data.
Are you sure you don't want JSON.parse? This would parse the JSON response into a javascript object that you can use the for/in against.
var data = JSON.parse(responseText);
Also, you're missing a closing quotation mark after the url:
url:'getinfo.php', // Closed the quote

Categories

Resources