The following is the code sample I have written. I would like to get the data from REST services and print it on the screen. I could get the response from REST in the JSON format. But, I could not find the way to use store it in the JSONStore and use it. Please help me to resolve this issue.
dojo.provide("index.IndexService");
dojo.require("dojo.parser");
dojo.require("dijit.Editor");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.data.JsonRestStore");
var xhrArgs = {
url: "http://localhost:8080/RestApp/service/customers",
handleAs: "json",
contentType : "application/json",
load: function(data){
alert(data);
},
error: function(error){
alert(error);
}
}
dojo.ready(function(){
// Create a button programmatically:
var button = new dijit.form.Button({
label: "View Transactions...",
onClick: function(){
// Do something:
dojo.byId("result1").innerHTML += "Functionality yet to be implemented! ";
}
}, "progButtonNode");
alert('hi');
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
alert(store);
store.get(1).when(function(object){
alert(object);
// use the object with the identity of 3
});
//var deferred = dojo.xhrGet(xhrArgs);
//compliantStore = new dojox.data.JsonRestStore({deferred});
alert(deferred);
});
Returned JSON value is
{"employees":{"customers":[{"city":null,"accountNo":null,"name":"Name
1","id":1},{"city":null,"accountNo":null,"name":"Name
2","id":2}],"count":2}}
How would I retrive the values?
JsonRestStore items are actually simple JavaScript objects, therefore you can always directly read properties from items. Like
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
myValue = recipeStore.getValue(item,"foo"); //stored in myValue
get = store.getValue;
set = store.setValue;
save = store.save;
// then fetch an item
var myGetValue = get(item,"foo");
var setMyValue = set(item,"foo","bar");
In synchronous mode, one can fetch without providing a callback, by directly accessing the results property from the request object that is returned from the fetch operation:
var queryResults = store.fetch({query:"?tastes='good'"}).results;
var firstItem = queryResults[0];
Did you meant something like that.. Hope it helps
Related
I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location
After looking for other answers to make a variable global I am struggeling for some time now, it looks quite simple but it just doesn't seem to work.
My code is getting data from a CSV file and returning a variable called 'chart' containing an Array. This Array variable is to be used outside the function in a Highchart graph. (The local returned Array is correct)
I am trying to make the variable inside the function "global" by attaching it as a property of the window. Like this: turn javascript local variable into global variable
But in my code this doesn't work out:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data/data.csv",
async: false,
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(data) {
var table = data.split("\n").map(line => line.split(","));
var categories = table[0].slice(2).map(e=>e*1);
data = table.slice(1).map(a => ({"name": a[0], "id": parseInt(a[1]), "data": a.slice(2).slice(0).map(e=>e*1)}));
var lengthdata = data.length - 1;
var chart = data.splice(0, lengthdata);
window.chartglobal = chart;
console.log(chart);
};
console.log(chartglobal);
What am I missing here or are there better ways than the window option for mmy specific situation?
EDIT:
The code is used in leaflet where the data is connected to leaflet markers using map.on and a marker id. That way is doesn't matter that the call ajax request is a pseudo ready event which is fired after trying to get the global value. I don't know what changing the async to 'true' alters but it works either way.
The variable is used in a map.on like this:
map.on('popupopen', function(e) {
var marker = e.popup._source.feature.id;
var search = function(name) {
for(var key in chartglobal) {
if(chartglobal[key].id === name) {
return chartglobal[key];
}}};
var outputhighchart = search(marker);
var chartdef = [];
chartdef.push(outputhighchart);});
The console.log was not logging because of the ajax call, the problem was somewhere in the map.on, which I overlooked because focusing on the global variable. Thanks for helping me out and directing in the right way.
why dont you declare your variable outside your function and give a dummy val
var chartglobal = "dummy";
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data/data.csv",
async: false,
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(data) {
var table = data.split("\n").map(line => line.split(","));
var categories = table[0].slice(2).map(e=>e*1);
data = table.slice(1).map(a => ({"name": a[0], "id": parseInt(a[1]), "data": a.slice(2).slice(0).map(e=>e*1)}));
var lengthdata = data.length - 1;
var chart = data.splice(0, lengthdata);
chartglobal = chart;
console.log(chart);
};
//as #Artur Filipiak sais at this point variable is not setted yet. so should print "dummy"
console.log(chartglobal);
How do i get list items from different lists in SharePoint using javascript. Given that all my list are stored in an array. And I need to loop through the array and execute similar functions on each list.
function initializePage() {
listcollections.forEach(function (value, index) { // listcollections is the array that contains the list url for different lists
var listtitle = value.listTitle;
var siteUrl = value.siteURL;
getItemsWithCaml(siteUrl, listtitle,
function (camlItems) {
var listItemEnumerator = camlItems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var EventsItem = new Events();
var listItem = listItemEnumerator.get_current();
EventsItem.eventTitle = listItem.get_item('Title');
EventsItem.eventDate = listItem.get_item('EventDate');
EventsItem.eventId = listItem.get_id();
EventsItem.eventSite = siteUrl;
EventsItem.eventList = listtitle;
EventsCollection.push(EventsItem);
}
},
function (sender, args) {
alert('An error occurred while retrieving list items:' + args.get_message());
});
})
};
function getItemsWithCaml(siteUrl, listtitle, header, success, error)
{
var hostWebContext = new SP.ClientContext(siteUrl);
var list = hostWebContext.get_web().get_lists().getByTitle(listtitle);
var caml = new SP.CamlQuery();
//Create the CAML that will return only items expiring today or later
caml.set_viewXml("<View><Query><Where><Geq><FieldRef Name=\'Expires\'/><Value Type=\'DateTime\'><Today /></Value></Geq></Where> </Query></View>");
var camlItems = list.getItems(caml);
hostWebContext.load(camlItems);
hostWebContext.executeQueryAsync(
function () {
success(camlItems);
},
error
);
};
//need to execute certain functions to format each list item
// I am not able to retrieve all list items in a single variable to be able to display data from all lists together
In the example below, I create a JavaScript object named ListDataCollection that contain a property Lists that is an array of objects.
Each of those contain a Url property whit the url of the lists I want to get the content.
Then I loop trough the array of objects and call the Sharepoint REST api for each Url.
Each time a call is complete :
I create a Data property on the current object with the data received
by the ajax call to the REST api.
I also update the current object Completed property to true.
Then I call a function named ifAllCompleted that check if all ajax calls are ended.
When all data is received, I log the word Completed on the browser console.
At this point, you have an array of objects. Each object contains the data of one Sharepoint list.
For example :
ListDataCollection.Lists[0].Data.d.results[0].Title
will contain the value of the Title Column of the first element in the first list.
If you want, you can merge all data in one array using the concat function in JavaScript.
Look at the 4 lines of code following the word Completed.
Hope this can help!
<script>
var ListDataCollection = {
Lists:[{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List1')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List2')/Items",
Completed:false
},{
Url:"http://Url.Of.Your.Site.Collection/_api/web/lists/getbytitle('List3')/Items",
Completed:false
}]
};
function ifAllCompleted() {
for (var i=0;i<ListDataCollection.Lists.length;i++) {
if (!ListDataCollection.Lists[i].Completed) {
return false;
}
}
console.log('Completed');
var arrayOfAllData = ListDataCollection.Lists[0].Data.d.results;
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[1].Data.d.results);
arrayOfAllData = arrayOfAllData.concat(ListDataCollection.Lists[2].Data.d.results);
console.log('Total elements : ' + arrayOfAllData.length);
}
$(document).ready(function(){
for (var x=0;x<ListDataCollection.Lists.length;x++) {
$.ajax({
url:ListDataCollection.Lists[x].Url,
indexValue:x,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data, status, xhr) {
ListDataCollection.Lists[this.indexValue].Data = data;
ListDataCollection.Lists[this.indexValue].Completed = true;
ifAllCompleted();
},
error: function (xhr, status, error) {
console.log('error');
}
});
}
});
</script>
I'm trying to merge two objects I receive as JSON via Ajax, but I can not access the variable and declaring it global. What am I doing wrong?
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
post.done(function( data ) {
postdata = jQuery.parseJSON(data);
});
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
postwatch.done(function( data ) {
postwatchdata = jQuery.parseJSON(data);
});
var postmerge = $.extend(postdata,postwatchdata);
console.log(postmerge);
The answer of postdata = jQuery.parseJSON(data) should be:
{"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be:
{"respwatch":"needlogin"}.
But to access the console, instead of getting postdata and postwatchdata merged, I get an empty object.
Object {} product.js:61
Edit:
I want when post and postwatch done, use data in product function.
The answer of postdata = jQuery.parseJSON(data) should be: {"resplike":"needlogin"}.
And the answer of postwatchdata = jQuery.parseJSON(data) should be: {"respwatch":"needlogin"}.
function product(data){
var obj = jQuery.parseJSON(data);
if (obj.resplike=='like'){
var respuesta = 'No te gusta';
}
else if(obj.resplike=='dislike'){
var respuesta = 'Te gusta';....blabla
I want to get in obj: {"resplike":"needlogin", "respwatch":"needlogin"}
You cannot handle the result of an asynchronous call like that. All operations done on a async function call must be done within the callbacks of that async method. read more about this in answer
var parametroswatcher = {
// asinid: $('#rate').attr('data-id'),
asinid: GetURLParameter('asin'),
mod: '0'
};
var post = $.post("../../likes/like.php", parametros, 'json');
var postwatch = $.post("../../watcher/watch.php", parametroswatcher, 'json');
$.when(post, postwatch).then(function(arg1, arg2){
var postmerge = $.extend(arg1[0], arg2[0]);
console.log(postmerge);
})
Also since you need to wait for the responses from two different requests you can use $.when() which will back the success handlers once all the passed promises are resolved.
I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);