i am working for the first time with Django Framework. A service provider is using django i can see the data only with an active Cookie on their API Docs.
We received now an API Token to call for the data on the framework.
I am trying to call the data with the Token via AJAX but i receive everytime the same console log "401 (Unauthorized)".
$.ajax({
type: 'POST',
headers: {
'X-CSRFTOKEN': "XXXXXXXXXXXXXXX",
'Content-Type': 'application/json'
},
url: 'www.service-provider.url/api/...',
success: function () {
console.log("ok");
},
error: function () {
console.log("error");
}
});
Sorry i'm a beginner at this point and have no idea where to begin with. I've searched for solution on the inet but couldn't find anything that would work.
Okay i got it! Before the token api key there must be "Token ...".
$.ajax({
type: 'GET',
url: 'https://my-url.com/api/1.0/?format=json',
headers:{
"Content-Type": 'application/json',
"Authorization": 'Token XXXXXXXXXXXXXXXXXXXXX',
},
success: function(data){
console.log(data);
}
});
I'm trying to create a sharepoint online site collection based on the Communication site template, as described by Microsoft here https://learn.microsoft.com/en-us/sharepoint/dev/apis/communication-site-creation-rest by using javascript on a page in a different sharepoint site
But, I keep getting a response of 403- although I am a tenant admin and so definitely have permission to create sites.
I am running the script below from a page at a url like companyname.sharepoint.com/sites/myTestSite/sitepages/RunSomeJS.aspx
I have tried specifying REST endpoint domain of both
companyname.sharepoint.com
and
companyname-admin.sharepoint.com
but get the same error.
function DoRestCall(){
var body={'parameters':
{
"__metadata":{"type":"SP.Publishing.CommunicationSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}
Any suggestions as to what I'm doing wrong here?
You need to make couple of changes as below:
1) Change the metadata as below:
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
2) You need to replace parameters to request
3) Modify the endpoint to create communication site as below:
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
3) Ensure that you are running the code from the root site(whose url is like https://companyname.sharepoint.com/sitepages/RunSomeJS.aspx) and you are the site collection admin of that root site.
You final code would be as below:
function DoRestCall(){
var body={'request':
{
"__metadata":{"type":"SP.Publishing.PublishingSiteCreationRequest"},
"AllowFileSharingForGuestUsers":false,
"Classification":"MyTest Communication Site",
"Description":"Here is my communication site",
"SiteDesignId":"6142d2a0-63a5-4ba0-aede-d9fefca2c767",
"Title":"MyTest Communication Site",
"Url":"https://companyname.sharepoint.com/sites/testSiteName",
"lcid":1033
}
};
$.ajax({
type: 'POST',
url: "https://companyname.sharepoint.com/_api/sitepages/publishingsite/create",
contentType: 'application/json',
processData: false,
headers:{
"accept":"application/json;odata=verbose",
"content-type":"application/json;odata=verbose",
"X-RequestDigest": document.getElementById("__REQUESTDIGEST").value
},
data: JSON.stringify(body),
success: function ()
{
alert('CREATION REQUEST SUBMITTED');
},
error: function(data){
alert('failure:' + data.statusText );
}
});
}
I am trying to use the JIRA REST API to preform some requests. One of the first things that you must do, according the docs, is authenticate in some way.
Atlassian offers 2 methods; Basic Auth and Cookie Based Auth, the later of which uses cookies to establish a session.
The issue comes into play when I involve Jquery/JS.
Here is the request when preformed in ARC (Advanced Rest Client) for Chrome:
If I run that request, I will get a HTTP 200 response with the correct JSON, which is what I want.
However, when I attempt to do this with Jquery/JS, I recieve an error every time.
Here is that code:
function cookieLogin() {
//Grab username and password from the fields on the page
var user = $("#loginUsername").val();
var pass = $("#loginPassword").val();
$.ajax({
//URL
url: baseURL + path,
//Method
//type: 'POST', //analogous to 'method'
method: 'POST',
//Headers
accept: 'application/json',
dataType: 'application/json',
contentType: 'application/json',
//Payload to be sent
data:
{
"username": "admin",
"password": "admin"
},
//Responses to HTTP status codes
statusCode: {
200: function () {
alert("Success!");
},
401: function() {
alert("Invalid Credentials");
},
403: function () {
alert("Failed due to CAPTCHA requirement/throttling.")
}
},
success: function (data) {
var result = jQuery.parseJSON(data);
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error!!!");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I have assured that the URL is correct. As you can see, I also hard-coded the credentials (this is merely a test page) just to test as well. I'm not sure why I am receiving errors in JS when I replicated the same thing that worked in ARC.
As per the documentation, I am seeing that "accept" should be "accepts" and "dataType" takes the string "json", not "application/json".
I am stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:
jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
I am new to AngularJS, and for a start, I thought to develop a new application using only AngularJS.
I am trying to make an AJAX call to the server side, using $http from my Angular App.
For sending the parameters, I tried the following:
$http({
method: "post",
url: URL,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({username: $scope.userName, password: $scope.password})
}).success(function(result){
console.log(result);
});
This is working, but it is using jQuery as well at $.param. For removing the dependency on jQuery, I tried:
data: {username: $scope.userName, password: $scope.password}
but this seemed to fail. Then I tried params:
params: {username: $scope.userName, password: $scope.password}
but this also seemed to fail. Then I tried JSON.stringify:
data: JSON.stringify({username: $scope.userName, password: $scope.password})
I found these possible answers to my quest, but was unsuccessful. Am I doing something wrong? I am sure, AngularJS would provide this functionality, but how?
I think you need to do is to transform your data from object not to JSON string, but to url params.
From Ben Nadel's blog.
By default, the $http service will transform the outgoing request by
serializing the data as JSON and then posting it with the content-
type, "application/json". When we want to post the value as a FORM
post, we need to change the serialization algorithm and post the data
with the content-type, "application/x-www-form-urlencoded".
Example from here.
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {username: $scope.userName, password: $scope.password}
}).then(function () {});
UPDATE
To use new services added with AngularJS V1.4, see
URL-encoding variables using only AngularJS services
URL-encoding variables using only AngularJS services
With AngularJS 1.4 and up, two services can handle the process of url-encoding data for POST requests, eliminating the need to manipulate the data with transformRequest or using external dependencies like jQuery:
$httpParamSerializerJQLike - a serializer inspired by jQuery's .param() (recommended)
$httpParamSerializer - a serializer used by Angular itself for GET requests
Example with $http()
$http({
url: 'some/api/endpoint',
method: 'POST',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).then(function(response) { /* do something here */ });
See a more verbose Plunker demo
Example with $http.post()
$http.post(
'some/api/endpoint',
data: $httpParamSerializerJQLike($scope.appForm.data), // Make sure to inject the service you choose to the controller
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}
).then(function
How are $httpParamSerializerJQLike and $httpParamSerializer different
In general, it seems $httpParamSerializer uses less "traditional" url-encoding format than $httpParamSerializerJQLike when it comes to complex data structures.
For example (ignoring percent encoding of brackets):
• Encoding an array
{sites:['google', 'Facebook']} // Object with array property
sites[]=google&sites[]=facebook // Result with $httpParamSerializerJQLike
sites=google&sites=facebook // Result with $httpParamSerializer
• Encoding an object
{address: {city: 'LA', country: 'USA'}} // Object with object property
address[city]=LA&address[country]=USA // Result with $httpParamSerializerJQLike
address={"city": "LA", country: "USA"} // Result with $httpParamSerializer
All of these look like overkill (or don't work)... just do this:
$http.post(loginUrl, `username=${ encodeURIComponent(username) }` +
`&password=${ encodeURIComponent(password) }` +
'&grant_type=password'
).success(function (data) {
The problem is the JSON string format, You can use a simple URL string in data:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.userName+'&password='+$scope.password
}).success(function () {});
Here is the way it should be (and please no backend changes ... certainly not ... if your front stack does not support application/x-www-form-urlencoded, then throw it away ... hopefully AngularJS does !
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+$scope.username+'&password='+$scope.password
}).then(function(response) {
// on success
}, function(response) {
// on error
});
Works like a charm with AngularJS 1.5
People, let give u some advice:
use promises .then(success, error) when dealing with $http, forget about .sucess and .error callbacks (as they are being deprecated)
From the angularjs site here "You can no longer use the JSON_CALLBACK string as a placeholder for specifying where the callback parameter value should go."
If your data model is more complex that just a username and a password, you can still do that (as suggested above)
$http({
method: 'POST',
url: 'api_endpoint',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: json_formatted_data,
transformRequest: function(data, headers) {
return transform_json_to_urlcoded(data); // iterate over fields and chain key=value separated with &, using encodeURIComponent javascript function
}
}).then(function(response) {
// on succes
}, function(response) {
// on error
});
Document for the encodeURIComponent can be found here
If it is a form try changing the header to:
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
and if it is not a form and a simple json then try this header:
headers[ "Content-type" ] = "application/json";
From the $http docs this should work..
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
$http({
method: "POST",
url: "/server.php",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "name='Олег'&age='28'",
}).success(function(data, status) {
console.log(data);
console.log(status);
});
you need to post plain javascript object, nothing else
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: { id: 4, name: "Kim" }
});
request.success(
function( data ) {
$scope.localData = data;
}
);
if you have php as back-end then you will need to do some more modification.. checkout this link for fixing php server side
Though a late answer, I found angular UrlSearchParams worked very well for me, it takes care of the encoding of parameters as well.
let params = new URLSearchParams();
params.set("abc", "def");
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http
.post(UrlUtil.getOptionSubmitUrl(parentSubcatId), params, options)
.catch();
This worked for me. I use angular for front-end and laravel php for back-end. In my project, angular web sends json data to laravel back-end.
This is my angular controller.
var angularJsApp= angular.module('angularJsApp',[]);
angularJsApp.controller('MainCtrl', function ($scope ,$http) {
$scope.userName ="Victoria";
$scope.password ="password"
$http({
method :'POST',
url:'http://api.mywebsite.com.localhost/httpTest?callback=JSON_CALLBACK',
data: { username : $scope.userName , password: $scope.password},
headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
});
This is my php back-end laravel controller.
public function httpTest(){
if (Input::has('username')) {
$user =Input::all();
return Response::json($user)->setCallback(Input::get('callback'));
}
}
This is my laravel routing
Route::post('httpTest','HttpTestController#httpTest');
The result in browser is
status 200
data JSON_CALLBACK({"username":"Victoria","password":"password","callback":"JSON_CALLBACK"});
httpTesting.js:18 headers function (c){a||(a=sc(b));return
c?a[K(c)]||null:a}
There is chrome extension called postman. You can use to test your back-end url whether it is working or not.
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en
hopefully, my answer will help you.