I was hoping that someone may be able to give me a pointer on how to achieve the following.
Currently, I have:
A JS function: A jQuery AJAX query that will get items from a SharePoint custom list.
A JS function: it will put the list results in to a datatable.
A JS function, that can turn an InitatorId into the real name of a user (GetDisplayName).
function GetDisplayName(userid) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : GetDisplayNameSuccess,
error : GetDisplayNameFail
});
}
function populateMyOutstandingItems() {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function() {
SP.SOD.executeFunc("sp.runtime.js", "SP.ClientContext", function() {
var context = SP.ClientContext.get_current();
var queryUrl = "https://companyname.sharepoint.com/subsite/_api/Web/Lists/getbytitle('Read%20Requests')/GetItems"; //change the Url
var camlXML = "<Query><Where><And><Eq><FieldRef Name='ReaderId' LookupId='True' /><Value Type='Integer'>" + _spPageContextInfo.userId + "</Value></Eq><Neq><FieldRef Name='Read' /><Value Type='Text'>YES</Value></Neq></And></Where></Query>"
var requestData = { "query" :
{"__metadata":
{ "type": "SP.CamlQuery" }
, "ViewXml": camlXML
}
};
return jQuery.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
},
success: onQuerySuccessMyOutstandingItems,
error: onQueryErrorMyOutstandingItems
});
});
});
}
function onQuerySuccessMyOutstandingItems(data) {
var jsonData = data.d.results
console.log(jsonData)
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
{ data: "Document_x0020_Name" },
{ data: "Document_x0020_Library_x0020_Nam" },
{ data: "Request_x0020_Made_x0020_Date" },
{ data: "InitatorId" },
{ data: "Request_x0020_ReadBy_x0020_Date" }, ],
order: [[3, "asc"]]
} ); }
At the moment, in the datatable, I have the InitatorID (ie. 30) but I would like to have the real name of the user in the table.
I understand some type of recursive AJAX query will be needed, but I'm not sure what the best way forward would be to achieve this, and was hoping that someone would be able to point me in the right direction.
After reading a bit about chained requests, I tried the code below, but it's wrong I guess, since Chrome complains of an 'unexpected ending':
var request = $.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
}
}),
chained = request.then(function( data ) {
return $.ajax( spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + data.InitatorId + ")",
{ data: { user: data.Title }} )
});
chained.done(function( data ) {
console.log(data)
});
In short, what is the best to achieve what I'm trying to do?
Many thanks
Glen
I am not sure I completely understand what you're asking, so here's my best guess at the scenario (please correct me if I am wrong)
Make an AJAX call to get a list of items from a SharePoint custom
list, but alas, one of the columns in this list has an InitatorID instead of a user name.
To fix this, we want to make another AJAX call that will get a list of usernames for a matching set of InitatorIDs we just retrieved.
Once we have that, we want to put the data in a dataTable for display.
Without knowing the details, I would just do nested AJAX calls. Basically, once the first call is done, call the second AJAX function. Once that one is done, update the dataTable. Something like:
$.ajax({
url: MY_FIRST_URL,
data: myFirstData
}).done(function (data) {
// The first call gets completed after some time and the 'done' function is called.
// here, extract the various InitatorID values, and pass them to the
// second AJAX call, so you can then get the usernames for those Ids
var initatorIds = // ... do data massaging here to get the initatorIds
// into the format you want from the 'data' variable
// passed in the done function...
$.ajax({
url: MY_SECOND_URL,
data: initatorIds
}).done(function (data2) {
// once the SECOND call is complete, populate the dataTables
var jsonData = // ... some manipulation of data and data2 results
// to get the combined output you want.
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
....
....
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the second call fails
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the first call fails
});
And at the risk of over-complicating the solution, I'd personally look to load the data directly into the table via the ajax functionality found within the dataTable plugin (read more about that here). But definitely if it minimizes confusion to lay it out as above, do that first!
Related
I have created a WCF project where i am trying to display some information in a listbox. I want when i click on a button, it will call my method and display it in a listbox. My method works fine but i am unable to display it in my listbox. Here's the code i am trying:
$('#btnListBlob').click(function () {
$.ajax({
type: "POST",
url: 'http://localhost:50525/BlobService.svc/ListBlob',
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
$(data).appendTo('#blobList')
alert('listed');
},
error: function (data) {
alert('Some error Occurred!');
}
});
});
I want the method i call in my URL to be displayed in my #blobList.
You may want to look at the data which you are appending. Data should be in the form of following:
<option value="5">item 5</option>
remember you are appending an HTML rather than appending just a data.
I would say put a console.log and try debugging the data received from server.
$('#btnListBlob').click(function () {
$.ajax({
type: "POST",
url: 'http://localhost:50525/BlobService.svc/ListBlob',
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
console.log(data)
$(data).appendTo('#blobList')
alert('listed');
},
error: function (data) {
alert('Some error Occurred!');
}
});
});
Just a few suggestions that you might find useful:
// only update the dom on click
// also use the new on() method
$('#btnListBlob').on("click", function () {
$("#blobList").html(processData())
});
// separate the call and data processing
var serverData = {"fakeServerData":[
{"data": "test data 1"},
{"data": "test data 2"}
]};
function processData(){
var options ="";
for( var i = 0 ; i < serverData.fakeServerData.length ; i++){
options += "<option>" + serverData.fakeServerData[i].data + "</option>";
}
return options;
}
Hope it helps, good luck!
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
I have a script that makes two ajax calls - the second being contained within the success handler of the first.
However I need to use the data captured within the first success handler as a further variable to pass in the second ajax call and then use that variable within the php file that is undertaking the server side processing.
This is all very new to me, so I hope this makes some sort of sense. If anyone could assist that would be great.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id'+lead_id,
data: $('form').serialize(),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I think you lose a "=" sign in the code:
url: 'processtwo.php?lead_id='+lead_id,
You're going to want to split these into two separate functions and allow for a parameter to be passed to the second. Not really part of your question, but should make it much easier to read. The second process seems to be missing an equals sign in the url parameter which will cause it to not work
function processOne() {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function(data) {
//alert("success data from processone is " + data);
//console logs are better to use when debugging data
console.log('SUCCESS DATA', data);
var lead_id = data;
processTwo(lead_id);
}
});
}
function processTwo(lead_id) {
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processtwo.php?lead_id=' + lead_id,
data: $('form').serialize(),
success: function(data2) {
alert("success data from processtwo is " + data2);
}
});
}
If you're still not getting anything make sure the data is directly returning the lead_id. AJAX calls commonly return JSON data, so it very well might be something like data.lead_id or something like that. Alerts aren't useful for showing this so you could use the console log, console.log('SUCCESS DATA', data) to dig into the return data.
Given the reply to my comment, and making the assumption that the data returned from the first AJAX call is a simple string value (if it's not, you can still use the code here to see how you need to do what you need to do). jQuery's serialize() returns a string (see https://api.jquery.com/serialize/) so you can just append to that.
Also, you are missing your = sign when making your URL, so if you are trying to get the lead_id as a GET var, that's why it's not working.
$.ajax({
type: 'POST',
timeout: 500000,
url: 'processone.php',
data: $('form').serialize(),
success: function (data) {
alert("success data from processone is " + data);
var lead_id = data;
$.ajax({
type: 'POST',
timeout: 500000,
// you are missing the equals sign here, which is why this doesn't work as a GET
url: 'processtwo.php?lead_id'+lead_id,
// here we tack on a lead_id variable to the serialized form and give
// it the value you got back from query 1
data: ($('form').serialize() + "&lead_id=" + lead_id),
success: function (data2) {
alert("success data from processtwo is " + data2)
}
});
}
});
I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.
This is the syntax :
$loadingBay.load(href, settings.data, function (data, status) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});
Many Thanks
You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :
$.ajaxSetup({
'headers':{
'header1':'value1',
'header2':'value2',
}
}
);
//give the load call here
$('selector').load('url',function(){
//do things
})
Disclaimer From jquery doc:
Its use is not recommended.
The best way is do the is thing using $.ajax() :
$.ajax({
url: "test.html",
headers : {header1 : "header1"}
}).done(function(data) {
$('selector').html(data);
});
You can use beforeSend option in jquery ajax , like as follows :
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
success: function() { alert('Success!' + authHeader); }
});
or can also use headers like,
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
headers:{ "X-TOKEN": 'xxxxx'},
success: function() { alert('Success!' + authHeader); }
});
I'm trying to understand how to build a JSON object in JavaScript. This JSON object will get passed to a JQuery ajax call. Currently, I'm hard-coding my JSON and making my JQuery call as shown here:
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{"comments":"test","priority":"1"}',
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
This approach works. But, I need to dynamically build my JSON and pass it onto the JQuery call. However, I cannot figure out how to dynamically build the JSON object. Currently, I'm trying the following without any luck:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
$.ajax({
url: "/services/myService.svc/PostComment",
type: "POST",
contentType: "application/json; charset=utf-8",
data: json,
dataType: "json",
success: function (res) {
alert("Thank you!");
},
error: function (req, msg, obj) {
alert("There was an error");
}
});
Can someone please tell me what I am doing wrong? I noticed that with the second version, my service is not even getting reached.
Thank you
You may want to look at the JSON JavaScript library. It has a stringify() function which I think will do exactly what you need.
Your code:
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { "comments":comments,"priority":priority };
Take out the quotes ( line 3 ):
var comments = $("#commentText").val();
var priority = $("#priority").val();
var json = { comments: comments, priority: priority };
Remove the quotes
data: '{"comments":"test","priority":"1"}',
becomes
data: {"comments":"test","priority":"1"},
JSONs are objects not strings.
This should work
var json = { comments: "comments",priority: "priority" };
this works for me.
var json = "{ 'comments': '" + *comments* +"','priority:' '" + *priority* +"' }";
italics are the variables.