I want to retrieve some data from Weather.asmx and wrote below code to get some data. There was no error from Javascript as I have seen but when the program runs it always go to groupPropertiesErrorHandler function. Any idea?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#butCallAjax').click(function() {
jQuery.support.cors = true;
$.ajax({
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP?ZIP=10007",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
success: groupPropertiesSuccessHandler,
error: groupPropertiesErrorHandler
});
});
function groupPropertiesSuccessHandler(data) {
var jsonObject = JSON.parse(data.body);
var properties = 'Group Properties:\n';
alert(properties);
}
// Error Handler
function groupPropertiesErrorHandler(data, errorCode, errorMessage) {
alert("Could not get the group properties: " + errorMessage);
}
});
</script>
Related
I need to make recursive RestAPI calls to overcome the 5000 view threshold of SharePoint online. Below code goes into a loop after generating the first 5000 entries. It generates the datatable and then increments into displaying the same data in a loop. I totally have only 8800 entries in my SharePoint list.
I just need to generate the 1st batch of 5000 entries and then the second batch of 3800 entries using recursive calls and display the concat data in Jquery Datatables.
$(document).ready(function() {
var table = $('#table_id').DataTable({
"pageLength": 100,
"dom": 'Bfrtip',
"buttons": [searchBuilder, copy],
"aoColumns": [{"mData": "Created"}, {"mData": "EncodedAbsUrl"}]
});
var response = response || [];
var listURL = "SPO_Site/_api/web/lists/getbytitle('List_Name')/items?$top=5000&$select=Created,EncodedAbsUrl";
GetListItemsRecursive(listURL);
function GetListItemsRecursive() {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
response = response.concat(data.d.results);
console.log(data);
if (data.d.__next) {GetListItemsRecursive(data.d.__next);}
try {table.rows.add(response).draw();}
catch (e) {alert(e.message);}
}
function myErrHandler(data, errMessage) {alert("Error");}
});
My test cide for your reference:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
var response = response || [];
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('testn')/items?$top=5000&$select=ID,Title";
GetListItemsRecursive(listURL);
function GetListItemsRecursive(listURL) {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
async: false,
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
console.log(data)
response = response.concat(data.d.results.map(e=>[e.ID,e.Title]));
console.log(response);
if (data.d.__next) { GetListItemsRecursive(data.d.__next); }
// try { table.rows.add(response).draw(); }
// catch (e) { alert(e.message); }
}
function myErrHandler() {
}
$('#table_id').DataTable({
data: response,
columns: [
{ title: "ID" },
{ title: "Title" }
]
});
})
</script>
<table id="table_id" class="display"></table>
Test result:
Good day, I have a SharePoint form the has a Originator Completed Dropdown with Yes or No as options. If the dropdown is yes, I would like to use JavaScript to set the OriginatorSignature (Text Field) to the loginName or current user. Can someone assist with this function?
<script src="/SiteAssets/jquery-3.2.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
GetUserLogin();
});
var userid = _spPageContextInfo.userId;
function GetUserLogin() {
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 : QuerySuccess,
error : QueryError
});
}
function QuerySuccess(data, request){
var loginName = data.d.LoginName.split('|')[1];
$("input[title='Originator Signature']").val(loginName);
}
function QueryError(error) {
alert(error);
}
</script>
The following code for your reference.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if($("select[title='Originator Completed Dropdown']").val()=="Yes"){
GetUserLogin();
}
$("select[title='Originator Completed Dropdown']").change(function(){
if($(this).val()=="Yes"){
GetUserLogin();
}else{
$("input[title='Originator Signature']").val("");
}
});
});
function GetUserLogin(){
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + _spPageContextInfo.userId + ")",
type: "GET",
headers: {
"Accept": "application/json;odata=verbose",
},
success: function (data) {
var loginName = data.d.LoginName;
if(loginName.indexOf("|")!=-1){
loginName = loginName.split('|')[1];
}
$("input[title='Originator Signature']").val(loginName);
},
error: function (data) {
//alert("Error");
}
});
}
</script>
I'm trying to get the profile image from delve and display it on a Sharepoint page using Javascript,the problem i'm getting is that the image isn't loading always
var profileimage="https://eur.delve.office.com/mt/v3/people/profileimage?userId="+userInfo["SPS-ClaimID"]+"&size=L";
If you want to display the profile image, we can use the url as below.
var profileimage="/_layouts/15/userphoto.aspx?size=L&username=lz#tenant.onmicrosoft.com";
Example code:
<script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/siteusers?$select=Id,Title,Email";
$.ajax({
url: url,
method: "GET",
async: false,
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var items=data.d.results;
var options="<option>--select a user--</option>";
for(var i=0;i<items.length;i++){
if(items[i].Email!=""){
options+="<option value='"+items[i].Email+"'>"+items[i].Title+"</option>";
}
}
$("#SiteUsers").html(options);
},
error: function (data) {
}
});
$("#SiteUsers").change(function(){
var html="";
if($(this).val()!=null&&$(this).val()!=""){
html+="<img src='/_layouts/15/userphoto.aspx?size=L&username=" + $(this).val() + "'/>";
}
if($(this).children(':selected').text()!=""){
html+="<p><span>Name:"+ $(this).children(':selected').text()+"</span></p>";
}
$("#UserInfomation").html(html);
});
});
</script>
<select id="SiteUsers"><option>--select a user--</option></select>
<div id="UserInfomation"></div>
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA
Here I'm trying to use jquery auto complete in asp.net, I'm trying to retrieve the data from sql data source and use that for auto fetch. while I running the code auto complete have not worked.
my code
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('txtPartno').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
textbox field
<asp:TextBox ID="txtPartno" CssClass="Textboxbase" class="autosuggest" runat="server"></asp:TextBox>
and my c# code
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=MYPC-GN\\KASPLDB;Integrated Security=False;User ID=sa;Password=*****;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT PART_NO from Inventory where UserName LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["UserName"].ToString());
}
return result;
}
}
}
One problem which I can see is your javascript call is little wrong. You cannot get the value of textbox which is created by asp itself with document.getElementById('txtPartNo'). To get this value, you will have to get it's client id which you can get using-
txtPartNo.ClientID so finally this will become-
data: "{'username':'" + document.getElementById('<%= txtPartno.ClientID %>').value + "'}",
If you don't try this way then you will not get the actual value of that textbox and undefined will be sent to the C# method which will not return anything.
First you should check if the JavaScript function it's getting called.
If it's getting called then you should check if the url is correct.
You can check in developer tools/ firebug etc. to see what request are you sending.
I did as follows:
ajaxCallSetting.js
var ajaxCallSetting = function (element, message, req) {
var baseInfo = {
baseUrl: "http://localhost:10266/"
};
var buildUrl= function() {
return baseInfo.baseUrl + message;
};
var callApi = function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: buildUrl(),
data: JSON.stringify(req),
dataType: "json"
}).success(function(data) {
response(data.d);
});
};
return {
init: function() {
$(element).autocomplete({
source: callApi
});
}
};
};
The head tag:
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
<script src="ajaxCallSetting.js"></script>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function () {
var req = {
username: $('#txtPartno').val()
};
apiSettings('#txtPartno', "Default.aspx/GetAutoCompleteData", req).init();
});
</script>
</head>
As far as possible,
Keeping separate Html code with the code in JavaScript is useful.
I don't think your TextBox is being hooked up properly. Try this:
<asp:TextBox ID="txtPartno" CssClass="Textboxbase autosuggest" runat="server"></asp:TextBox>
And try this in your JavaScript:
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Inventory.aspx/GetAutoCompleteData",
data: "{'username':'" + request.term + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});