Facing issue as 404 while Ajax call in typo3 - typo3

I am new in typo3 and used the ajaxselectlist extension but while the time usage I am facing 404 not found an error.
Below code is fetch from ajaxselectlist/Resources/Templates/OptionRecord/List.html
<script>
jQuery(document).ready(function ($) {
var form = $('#ajaxselectlist-form');
var selectForm = $('.ajaxFormOption');
var controllerpath = $("#uri_hidden").val();
var resultContainer = $('#ajaxCallResult');
var service = {
ajaxCall: function (data) {
console.log("---->"+data.serialize());
$.ajax({
url: controllerpath,
cache: false,
data: {'uid':'1'},
success: function (result) {
resultContainer.html(result).fadeIn('slow');
},
error: function (jqXHR, textStatus, errorThrow) {
resultContainer.html('Ajax request - ' + textStatus + ': ' + errorThrow).fadeIn('fast');
}
});
}
};
form.submit(function (ev) {
ev.preventDefault();
service.ajaxCall($(this));
});
selectForm.change(function () {
resultContainer.fadeOut('slow');
form.submit();
});
selectForm.trigger('change');
});
</script>

Related

Sharepoint list item using Api Rest

I need to get a list's items, so I created this function
export function retrieveSPItems(spToken, alias) {
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/ItemCount`;
var myHeaders = new Headers({
Accept: "application/json;odata=nometadata",
Authorization: spToken,
});
return fetch(url, {
method: "get",
headers: myHeaders,
}).then((response) => response.json());
}
As a output I get 3000.
when I change the url to
var url = `{path_to_my_site}/_api/web/Lists/getByTitle('Briefs')/Items`;
I get an empty list!
PS :
It's work in Postman with no problem
The token is generated by adaljs :
Get Token
authContext.acquireToken(SP_BASE_URL, function (error, token){....})
Adal config
export const adalConfig = {
tenant: CURRENT_TENANT,
clientId: CURRENT_APP_ID,
endpoints: {
api: CURRENT_APP_ID,
graph: GRAPH_BASE_URL,
sharepoint: SP_BASE_URL,
},
cacheLocation: "localStorage",
validateAuthority: true,
};
So I need to know :
what the reason fot this issue?
How can I fix it?
It's too general information, you need debug and figure out the detailed error information.
My test demo:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="Scripts/adal.js"></script>
<script type="text/javascript">
var authContext = null;
var user = null;
(function () {
window.config = {
instance: 'https://login.microsoftonline.com/',
tenant: 'xxx.onmicrosoft.com',
clientId: '9afc37cb-x-x-x-xxx',
postLogoutRedirectUri: window.location.origin,
endpoints: {
graphApiUri: "https://graph.microsoft.com",
sharePointUri: "https://xxx.sharepoint.com/",
},
cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
};
authContext = new AuthenticationContext(config);
var isCallback = authContext.isCallback(window.location.hash);
authContext.handleWindowCallback();
//$errorMessage.html(authContext.getLoginError());
if (isCallback && !authContext.getLoginError()) {
window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
}
user = authContext.getCachedUser();
if (!user) {
authContext.login();
}
//authContext.acquireToken(window.config.clientId, function (error, token) {
// console.log('---');
//})
authContext.acquireToken(window.config.endpoints.sharePointUri, function (error, token) {
alert(token);
if (error || !token) {
console.log("ADAL error occurred: " + error);
return;
}
else {
var listUri = window.config.endpoints.sharePointUri + "sites/lee/_api/web/lists/GetByTitle('mylist')/items?$select=Title";
$.ajax({
type: "GET",
url: listUri,
headers: {
"Authorization": "Bearer " + token,
"accept": "application/json;odata=verbose"
}
}).done(function (response) {
console.log("Successfully fetched list from SharePoint.");
var items = response.d.results;
for (var i = 0; i < items.length; i++) {
console.log(items[i].Title);
$("#SharePoint").append("<li>" + items[i].Title + "</li>");
}
}).fail(function () {
console.log("Fetching list from SharePoint failed.");
})
}
})
}());
</script>

Protractor/Jasmine send REST Call when a test failed

I am using Protractor and Jasmine to test my hybrid mobile app, which works fine. I'd like to create an incident on my Team Foundation Server (TFS), when a test fails. Therefore, I have to send an REST-Call to the Api, which also works fine in my Angular App. But it does not work, when I am inside my test environment.
My Code:
var BrowsePage = require('./browse.page');
var tfsIncident = require('./tfsIncident_service');
var request = require('request');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var specsArray = [];
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
var mappedResult = tfsIncident.create(result);
console.log(mappedResult); //This works so far, but then it crashes
var options = {
method: 'PATCH', //THis Method requiered the API
url: 'MY_COOL_API_ENDPOINT',
headers: {
'Authorization': 'Basic ' + btoa('USERNAME' + ':' + 'PASSWORD'),
'Content-Type': 'application/json-patch+json'
},
body: mappedResult
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body);
console.log(response);
console.log(info);
}
}
request(options, callback);
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec);
//This test passes
it('should be able to take display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
// Test is supposed to fail
it('should be able to fail', function () {
expect(browsePage.headline).toBe(1);
});
// Test is supposed to fail as well
it('should be able to fail too', function () {
expect(browsePage.headline).toBe(2);
});
});
So the problem is, that my only console output is (after the console.log(mappedResult)): E/launcher - BUG: launcher exited with 1 tasks remaining
So I have no idea, why this does not work.
Any help appreciated.
Edit
Protractor: 5.0.0
Appium Desktop Client: 1.4.16.1
Chromedriver: 2.27
Windows 10 64 Bit
Jasmine: 2.4.1
I finally got my problem solved. The problem was caused by ignoring the promises by jasmine. I had to add a .controllFlow().wait() to my protractor.promise
The following code works fine:
var BrowsePage = require('./browse.page');
describe('Testing the browse state', function () {
var browsePage = new BrowsePage();
var reporterCurrentSpec = {
specDone: function (result) {
if (result.status === 'failed') {
//Mapping of the result
var incident = [
{
op: 'add',
path: '/fields/System.Title',
value: 'Test: ' + result.fullName + ' failed'
},
{
op: 'add',
path: '/fields/System.Description',
value: result.failedExpectations[0].message
},
{
op: 'add',
path: '/fields/Microsoft.VSTS.Common.Priority',
value: '1'
},
{
op: 'add',
path: '/fields/System.AssignedTo',
value: 'Name Lastname <e#mail.com>'
}
];
protractor.promise.controlFlow().wait(create(incident)).then(function (done) { //The magic happens in this line
console.log("test done from specDone:" + done);
});
}
}
};
jasmine.getEnv().addReporter(reporterCurrentSpec); //Add new Jasmine-Reporter
function create(incident) {
var request = require('request');
var defer = protractor.promise.defer(); //new promise
request({
url: 'https://MY_COOL_ENDPOINT.COM',
method: "PATCH",
json: true, // <--Very important!!!
headers: {
'Authorization': 'Basic ' + new Buffer('USERNAME' + ':' + 'PASSWORD').toString('base64'),
'Content-Type': 'application/json-patch+json'
},
body: incident
}, function (error, response, body) {
console.log(error);
console.log(response.statusCode);
console.log(body.id); //Id of created incident on TFS
defer.fulfill({
statusCode: response.statusCode
}); //resolve the promise
});
return defer.promise; //return promise here
}
it('should be able to display the heading', function () {
expect(browsePage.headline.isPresent()).toBe(true);
});
it('should be able to fail', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
it('should be able to fail 2', function () {
expect(browsePage.headline.isPresent()).toBe(false);
});
});
Attention
When the test suite is done and the last promise is not resolved at this moment, the last incident is not created. I'll try to work around by adding to the last test a browser.sleep(5000); so that the create(incident) function gets more time to finish.
Thanks to this StackOverflow answer for helping me.

Query multiple SharePoint lists Using REST API and angular JS

I have a scenario of fetching data from multiple SharePoint 2013 lists using REST API and Angularjs. I am able to fetch the data successfully from one of the SharePoint list but my requirements is to fetch the data from multiple lists on the page load. I am using a provider hosted app to fetch the data from host web. I have 2 methods for calling 2 separate lists. I am getting the results from first method successfully but when the second method is called after the execution of 1st method. I am getting a time out error. It seems like i cannot call the 2 methods one after the other. Below is my code, could anyone please help me if i am missing something or if there is any other way to fetch the data from multiple SharePoint lists.
Method 1: fetch Data from List 1
var query = listEndPoint + "/getbytitle('CandidateList')/items?$select=ID,FirstName,MiddleInitial,LastName,EmailAddress,PrimaryPhoneNo,ProfileImage,Address,State,Country,CurrentTitle,CurrentCompany,LastActivityModifiedBy,LastActivityModifiedDate,DeletedStatus&#target='" + hostweburl + "'";
var getCandidates = function (query, queryCandidateNotes)
{
alert('getRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {`enter code here`
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase +"SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject1 = JSON.parse(data.body);
deferred.resolve(jsonObject1);
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error1:' + errorMessage + data.body);
}
// Get
return deferred.promise;
//Candidate Details Ends
};
Method 2: fetch Data from List 2
var queryCandidateNotes = listEndPoint + "/getbytitle('CandidateNotes')/items?$select=Title,CandidateId&#target='" + hostweburl + "'";
// Get All Candidate Notes
var getCandidateNotes = function (queryCandidateNotes) {
alert('getCandidateNotesRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred2 = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase + "SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryCandidateNotes,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject2 = JSON.parse(data.body);
//var results2 = jsonObject2.d.results;
deferred2.resolve(jsonObject2);
//alert('2nd success:' + jsonObject2);
//return jsonObject2;
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error2 :' + errorMessage + data.body);
}
// Get
return deferred2.promise;
};
Method 3: Calling method 2 after method 1
var getRequest = function (query, queryCandidateNotes) {
var deferred = $q.defer();
$.when(getCandidates(query, queryCandidateNotes)).then(function (data) {
alert('Success1:' + data);
$.when(getCandidateNotes(queryCandidateNotes)).then(function (data1) {
deferred.resolve(data);
alert('Success2:' + data1);
});
})
return deferred.promise;
};
return {
getRequest: getRequest
};
}]);
})();
$.when is not appropriate here, utilize $q.all that combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Example
app.controller('listController', function ($scope, $q, listService) {
SP.SOD.executeFunc('SP.RequestExecutor.js', 'SP.RequestExecutor', function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
where listService is a service for getting list items:
app.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);
Solution description
Default.aspx
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<meta name="WebPartPageExpansion" content="full" />
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/listService.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
and
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div ng-app="SPApp" ng-controller="listController">
</div>
</asp:Content>
App.js
'use strict';
(function() {
var app = angular.module('SPApp', ['SPApp.services']);
app.controller('listController', function ($scope, $q, listService) {
executeOnSPLoaded(function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
})();
function executeOnSPLoaded(loaded) {
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var scriptbase = hostweburl + "/_layouts/15/";
$.when(
//$.getScript(scriptbase + "SP.Runtime.js"),
$.getScript(scriptbase + "SP.js"),
$.getScript(scriptbase + "SP.RequestExecutor.js"),
$.Deferred(function (deferred) {
$(deferred.resolve);
})
).done(function () {
loaded();
});
}
listService.js
'use strict';
angular.module('SPApp.services',[])
.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);

Decoding response error in extjs

I am doing the following stuff when a form is submitted. But I get this error:
Error decoding response: SyntaxError: syntax error
Here is my onSubmit success function:
onSubmit: function() {
var vals = this.form.getValues();
Ext.Ajax.request({
url: 'ticketSession.php',
jsonData: {
"function": "sessionTicket",
"parameters": {
"ticket": vals['ticket']
}
},
success: function( result, request ) {
var obj = Ext.decode( result.responseText );
if( obj.success ) {
//alert ('got here');
th.ticketWindow.hide();
Web.Dashboard.loadDefault();
}
},
Here is my ticketSession.php
<?php
function sessionTicket($ticket) {
if( $_REQUEST['ticket'] ) {
session_start();
$ticket = $_REQUEST['ticket'];
$_SESSION['ticket'] = $ticket;
echo("{'success':'true'}");
}
echo "{'failure':'true', 'Error':'No ticket Number found'}");
}
?>
I also modified my onsubmit function but didnt work:
Ext.Ajax.request({
url: 'ticketSession.php',
method: 'POST',
params: {
ticket: vals['ticket']
},
i am simply echoing this but I still get that error
echo("{'success':'true'}");
Maybe this can help you. It's a working example of an ajax-request which is nested in a handler.
var deleteFoldersUrl = '<?php echo $html->url('/trees/delete/') ?>';
function(){
var n = tree.getSelectionModel().getSelectedNode();
//FolderID
var params = {'folder_id':n['id']};
Ext.Ajax.request({
url:deleteFoldersUrl,
params:params,
success:function(response, request) {
if (response.responseText == '{success:false}'){
request.failure();
} else {
Ext.Msg.alert('Success);
}
},
failure:function() {
Ext.Msg.alert('Error');
}
});
}

Childbrowser plugin not working in Phonegap

I'm using Backbone, Require and Underscore Bundled with Phonegap or Cordova.
I tried using the childbrowser plugin but it wont work. I followed the instructions here.
http://blog.digitalbackcountry.com/2012/03/installing-the-childbrowser-plugin-for-ios-with-phonegapcordova-1-5/
define([
'jquery',
'backbone',
'underscore',
'base64',
'mobile',
'const',
'child',
'text!template/login/login.tpl.html'
],function($, Backbone, _, base64, Mobile, Const, ChildBrowser, template){
var EncodeAuth = function(user,pass)
{
var _tok = user + ':' + pass;
var _hash = Base64.encode(_tok);
return "Basic "+ _hash;
}
var LoginView = Backbone.View.extend({
events:{
"click .login-btn" : "Login",
"click .connection-btn" : "OpenSite"
},
initialize: function(){
},
Login: function(){
Const.USERNAME = $("#username").val();
Const.PASSWORD = $("#password").val();
if(!Const.USERNAME || !Const.PASSWORD)
{
navigator.notification.alert("Invalid Username/Password!");
$("input").val("");
}else{
var auth = EncodeAuth(Const.USERNAME,Const.PASSWORD);
var sendAuthorization = function (xhr) {
xhr.setRequestHeader('Authorization', auth)
};
this.model.save(this.model, {
beforeSend : sendAuthorization,
success: function(model,result){
if(result.ErrorMessage === null)
{
alert(JSON.stringify(result.Message));
$("input").val("");
}
else
{
alert(JSON.stringify(result.ErrorMessage));
$("input").val("");
}
},
error: function(model,result){
alert("Remote server returned an error. Not Found");
$("input").val("");
}
});
}
},
OpenSite: function(){
window.plugins.ChildBrowser.showWebPage("http://www.google.com");
}
});
return LoginView;
});
Any ideas?