passing json array to ajax call in Javascript - javascript

guys i know its dummy questions but i spent hours on this and cant reach .. I am trying to pass a JSON array to JSP via an AJAX call in another JS file. It is giving me a 404 error. Any help would be appreciated. Here is my code:
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
setFileName : function(fileName) {
this.fileName = fileName;
},
getFileName : function() {
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url : this.getFileName(),
dataType: "json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
alert("found");
}
});
};
var Json = [{
"id": 1,
"name": "name1",
"age" : 10,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age" : 90,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age" : 30,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age" : 50,
"feedback": "feedback4"
}];
new GridLibrary(Json).display();

You need to have a valid url to send the values to the backend:
function GridLibrary(url, data) {
this.url = url;
this.data = data;
}
GridLibrary.prototype = {
setData: function(data) {
this.data = data;
},
getData: function() {
return this.data;
},
setUrl:function(url){ this.url = url; },
getUrl:function(){ return this.url; },
display : function() {
$.ajax({
url: this.getUrl, // <----the url where you want to send the data
data:this.getData, //<----should be the array data
dataType: "json",
contentType:"application/json", // <----add this contentType
error: function(that, e) {
console.log(e);
},
success: function(data) {
alert("found");
}
});
}
};
var url = '/url/to/send',
data = [{}....];
new GridLibrary(url, data).display();

Related

Retrieving data from db.json file and adding it into an array using javascript

I'm using ajax and javascript for a game and I created a server using json-server where I keep a db.json file with words that the user can input and become available in the game.
db.json
This is what the json file looks like
{
"words": [
{
"cuvant": "cuvant",
"id": 1
},
{
"cuvant": "masina",
"id": 2
},
{
"cuvant": "oaie",
"id": 3
},
{
"cuvant": "carte",
"id": 4
},
{
"cuvant": "fmi",
"id": 5
},
{
"cuvant": "birou",
"id": 6
},
{
"cuvant": "birou",
"id": 7
},
{
"cuvant": "canapea",
"id": 8
},
{
"cuvant": "pasare",
"id": 9
I managed to get the POST request (adding the words to the db.json) using this:
function addWord() {
var word = document.getElementById("input-name").value;
var info = {
cuvant: word
}
$.ajax({
url:'http://localhost:3000/words',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(info),
succes: function(info) {
console.log(info)
},
error: function(error) {
console.log(error);
}
})
}
This is what I tried for the GET request
But I'm not sure if it's correct.
And I also need a way to get only the value hold by the cuvant key and add it into an array.
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
contentType: "application/json",
succes: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}
I think your code is correct. It was just missing the "s" on "success":
window.onload = function() {
function gett() {
$.ajax({
url: 'http://localhost:3000/words',
type: 'GET',
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data)
}
})
.done(function(){
console.log("Over")
})
}
}

Cannot set property 'values' of undefined

I'm using zingchart gauges in my code. My problem is that I can't change the gauge value dynamically.
I'm getting this error:
Cannot set property 'values' of undefined
I'm using flask API. How can I change this variable value with flask API? Do you have any idea what can I use for dynamic gauge?
function fetchData() {
$.ajax({
url: "api/read",
method: "GET",
success: function(data, status, xhr) {
//var array = data.split(",").map(Number);
a = JSON.parse(data);
$('#myChart').series.values = 20;
//console.log(a);
},
error: function(xhr, status, error) {
$("#dataHeader").html("Error: \n" + error);
}
});
}
var myConfig4 = {
"type": "gauge",
"scale-r": {
"aperture": 200,
"values": "0:100:10",
"center": { //Pivot Point
"size": 6,
"background-color": "#66CCFF #FFCCFF",
"border-color": "#000000"
}
},
"plot": {
"csize": "5%",
"size": "85%",
"background-color": "#000000"
},
"series": [{
"values": [] // i need to change this value
}]
};
zingchart.render({
id: 'myChart',
data: myConfig4,
height: "75%",
width: "75%"
});
setInterval(fetchData, 1000);
you can use setseriesvalues and use array as value.
success: function(data, status, xhr) {
a = JSON.parse(data);
zingchart.exec('myChart', 'setseriesvalues', {
plotindex: 0,
'values': [20]
});
//console.log(a);
}

dataTables Change Data for ajax call

I'm using the following function to load a DataTables table with data from the server. I would like to reload the table with different parameters on a click event only i cant work out how to do this. If i call reload it just reloads with the original parameters if i reinitialise the whole table it throws an error as the table already exists.
I have been looking into fnServerParams but cant work out if it would help or not.
If anyone can point me in the correct direction that would be great.
function LoadRiskProfileModalTable(userId, teamId, riskProfileClass) {
var params = {
userId: userId,
teamId: teamId,
riskProfileClass: riskProfileClass
};
var data = JSON.stringify(params);
//if (!$.fn.DataTable.isDataTable("#riskProfileTable")) {
var table = $("#riskProfileTable").DataTable({
"bProcessing": true,
"sAjaxSource": "WFMHome.aspx/GetRiskProfileDrillThroughDatatable",
"fnServerData": function (sSource, aoData, fnCallback) {
//aoData.push(JSON.stringify(params));
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": sSource,
"data": data,
"success": function (msg) {
var json = jQuery.parseJSON(msg.d);
fnCallback(json);
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},
error: function (xhr, textStatus, error) {
if (typeof console == "object") {
appendAlert("errorAlertPlaceholder", xhr.responseText, 1, "danger");
console.log(xhr.status + "," + xhr.responseText + "," + textStatus + "," + error);
}
}
});
},
"columns": [
{ "data": "CaseHandler" },
{ "data": "caseAreaText" },
{ "data": "RiskProfileText" },
{ "data": "PassChecks" },
{ "data": "F1Checks" },
{ "data": "F2Checks" },
{ "data": "F3Checks" },
{ "data": "CurrentChecks" }
]
});
//}
//else {
// $('#riskProfileTable').DataTable().ajax.reload();
// }
};
If you just want to replace the data you have now by the data coming from the server, try to replace the success method by:
"success": function (msg) {
var json = jQuery.parseJSON(msg.d); //I assume it's the data set
var table = $("#riskProfileTable").DataTable();
table.rows.clear(); //clear the current data
table.rows.add(json).draw();
$("#riskProfileTable").show("fast", function () { $('#riskProfileTableLoading').hide("fast") });
},

Using jquery to filter out duplicate data in a json populated select box

I have a select box that I am populating with data from a json file using the code below:
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: {
take: 100,
skip: 0
},
}).done(function (data) {
$.each(data, function (i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
})
})
};
getType();
The problem is that the returned value type.name has loads of duplicates in it, I would like to filter out these duplicates to only show each unique value one time. Im a bit stuck on where to start with this though so help would be greatly appreciated :)
Using Array.prototype.filter and creating an array to track unique names, you can build up a filtered data array to then iterate over to display your unique datasets.
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: { take: 100, skip: 0 },
})
.done(function(data) {
var filteredData = [];
var uniqueNames = [];
data.filter(function (data) {
if (uniqueNames.indexOf(data.type.name) < 0) {
uniqueNames.push(data.type.name);
filteredData.push(data);
}
});
$.each(filteredData, function(i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
})
})
};
getType();
You can write a condition to append options only if options with same text does not exist in the #choose select, using selector [text="someText"].
function getType(str) {
$.ajax({
url: 'xxx',
type: 'GET',
format: 'json',
data: {
take: 100,
skip: 0
},
}).done(function (data) {
$.each(data, function (i, item) {
if($("#choose").children('option[text="' + item.type.name + '"]').length == 0){
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
}
})
})
};
getType();
You can use filter like this :
var unique=data.filter(function(item,i,a){
return i==data.indexOf(item.type.name);
});
All you need to do is to filter out the value that's already been found. Please find comments inline for more info.
//Sample data
var data = [
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 1" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 4" },
},
{
"type": { "id": 1, "name": "sample string 2" },
},
{
"type": { "id": 1, "name": "sample string 3" },
}
]
//Create an empty object
var $items = $();
$.each(data, function(i, item) {
//Construct the option
var $option = $('<option/>', {text: item.type["name"]});
//Add it to the bucket only if it's not already added!
if (!$items.filter(":contains(" + item.type["name"] + ")").length) {
$items = $items.add($option);
}
});
//Always append outside the loop!
$("#choose").append($items);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="choose"></select>
Try this code snippets.
.done(function(data) {
var records=[];
$.each(data, function (i, el) {
if ($.inArray(el, records) === -1) records.push(el); //filters the duplicate elements
});
$.each(records, function(i, item) {
var option = $('<option>').text(item.type.name)
option.appendTo("#choose");
});
});
Update:
Try this code snippet if you want to filter out the name from the json data variable.
.done(function(data) {
var records=[], nameList = [];
$.each(data, function (i, elem) {
nameList.push(elem.type.name);
});
$.each(nameList, function (i, el) {
if ($.inArray(el, records) === -1) records.push(el);
});
$.each(records, function(i, item) {
var option = $('<option>').text(item)
option.appendTo("#choose");
});
});

Populating the AJAX url in a JSTree with model information

I am populating a JSTree view with ajax commands. My current JS code is as follows
$(document).ready(function() {
$("#navigation").jstree({
"json_data": {
"ajax": {
"url": function (node) {
var nodeId = "";
var url = "";
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
nodeId = node.attr('id');
url = "#Url.Action("EventTreeItems", "Events")" +"?selectedYear=" + nodeId;
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0 }; },
"success": function() {
}
}
},
"themes": {
"theme": "classic"
},
"plugins": ["themes", "json_data", "ui"]
});
});
I would like to eliminate the if statement from the "ajax" property and fill it with the JSON data that is coming from the server. The JSON data looks like this
[{"data":{"title":"2012","attr":{"href":"/Events/EventList?selectedYear=2012"}},"attr":{"id":"2012","selected":false,"ajax":"/Events/EventTreeItems?selectedYear=2012"},"children":null,"state":"closed"},.....]
How can I feed the "ajax" property from the json into the "ajax" property in the JSTree?
For future reference I fixed it by doing the following
.jstree({
"json_data": {
"ajax": {
"url": function (node) {
var url;
if (node == -1) {
url = "#Url.Action("BaseTreeItems", "Events")";
} else {
url = node.attr('ajax');
}
return url;
},
"dataType": "text json",
"contentType": "application/json charset=utf-8",
"data": function(n) { return { id: n.attr ? n.attr("id") : 0, ajax: n.attr ? n.attr("ajax") : 0 }; },
"success": function() {
}
}
},

Categories