I am facing problem while requesting url
In documents for web service access there are required parameters as UserID, queryparam , and header as
x-requested-by
2nd thing I have noticed
I am having my browser url to run code is as
01234.domain_name.com/my form.html
And my request url is as
09876.domain_name.com/serviceapi/
Where domain_name part is same.
While posting data I am using code as:
URL: 09876.domain_name.com/serviceapi/+ name + '?u=UserID';
$.ajax(function(){
type: post,
url: URL,
data: datajsonobject,
headers: {x-requested-by: UserID},
success: successfun
});
Code is typing on mobile , please ignore caps lock mistakes in code.
After running this code getting 401 response. Plz help me
Status code 401 stands for Unauthorized. You need to login into your application and then make an Ajax call or your credentials are wrong.
Maybe you can have a debug point in the code where user authentication is being handled.
Related
I am trying to post data to a from AJAX to a Google form, but even though it reports success with a statusCode of 0, the data never appears in the form:
var dat={ "entry.529474552" :"data1", "entry.1066559787": "name1"};
postToGoogle("1FAIpQLSf4w1OQGsIncaiqXlmfAl4jYSt-e4Zx3xVJa7Weob4LnQbRZQ",dat);
function postToGoogle(id, dat) {
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', 'chrome-extension://EXTENSION_ID');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET, POST, PUT');
},
url: "https://docs.google.com/forms/d/e/"+id+"/formResponse",
data: dat,
type: "POST",
dataType: "xml",
xhrFields: { withCredentials: true },
statusCode: {
0: function() { console.log("OK") },
200: function() { console.log("error") },
}
});
}
It generates a CORS error, but supposedly, the POST should go through anyway.
For those looking to do this as of April 2019
I was working on this today. The current answer is as follows:
Each field in the Google Form has a unique ID. In order to retrieve it, get a pre-filled link by filling out all relevant form fields you wish to programatically submit
Note: In order to ensure the URL is accessible without restriction, you'll also want to disable restriction to your domain only (for GSuite paying users)
Then, copy the link and paste in your browser. The URL has a base format as follows:
https://docs.google.com/forms/d/e/[FORMID]/formResponse
Each param is a key/value pair of type: entry.XXXXXX=value
The prefilled link will give you the value of XXXXX for each relevant field
Request must be made with following headers:
Method: GET
Content-Type: application/x-www-form-urlencoded
The final request looks like this
https://docs.google.com/forms/d/e/123332233bsj333/formResponse?entry.123456=value1&entry.2333442=value2&submit=Submit
Don't forget to append submit=Submit at the end of your request!
It generates a CORS error, but supposedly, the POST should go through anyway.
While it is possible to make a successful POST request, get a CORS error, and be unable to read the response, this is only true for Simple Requests.
Because your request has:
Custom headers (Access-Control-Allow-Origin and Access-Control-Allow-Methods, which are response headers and have no business being on a request in the first place)
Credentials (i.e. you have set withCredentials: true)
… it is a Preflighted Request.
Before the browser will make the POST request, it will make an OPTIONS request to ask permission.
Since it doesn't get permission, the request fails.
Note that even if you did turn it into a simple request and make the POST successfully, you would still get a status of 0. You can't read the status when there is a CORS error.
I am trying to use NOAA's climate data API with AJAX https://www.ncdc.noaa.gov/cdo-web/webservices/v2#gettingStarted and am not having any luck. I get "bad request" when I try the AJAX way, and a CORS error when I try xhttp. Does anyone know how to format a code snippet that would get a response, without any CORS issues?
Thanks!
var noaaUrl = "https://www.ncdc.noaa.gov/cdo-web/api/v2/datasets";
var tokenFromNoaa = "aToken";
$.ajax({
url: noaaUrl,
headers:{
token: tokenFromNoaa
},
success: function(returnedData) {
console.log(returnedData);
}
})
You need to replace the "aToken" with the actual token they gave you and replace datasets with whichever endpoint you want to access.
This should log the data into your browser console. You can access that by pressing F12. This code snippet also requires jQuery to use.
I'm starting to get stumped on this. I'm developing a C#.NET Web API service and frontend application to use it. I've been having a lot of difficulty using a token to authenticate my requests and jQuery seems to be having trouble. I can get a token just fine, but jQuery won't add it to an Authorization header in further requests.
My setup is an index.html page with several jQuery Mobile pages inside it. It starts on a '#login' page, which sends a request to my /Token URI with a username, password, and grant type. This is successful and the return is the token. The page changes to '#home' and a test ajax call is sent to /api/values to grab value. The problem is that instead of adding a header called 'Authorization', jQuery adds an 'Access-Control-Request-Headers' with the value 'accept, authorization' instead. At first I thought it was a CORS issue, but the request works fine when I use Advanced Rest Client in Chrome to send the request.
AJAX Call from '#Home'
$.ajax({
url: 'http://slalomtest2.azurewebsites.net/api/values/',
type: 'GET',
async: true,
dataType:"json",
beforeSend: function(request){
request.withCredentials = true;
request.setRequestHeader("Authorization", "Basic " + Token);
},
success: function(result){
console.log(result);
},
error: function(request, error){
$.mobile.changePage("#login");
}
});
The bad request the AJAX sends
This is what it looks like from Advanced Rest Client in the same browser
Thanks in advance for the help, I've been banging my head against the wall all day.
I have an app in my salesforce developer account that I want to allow my users to access from a remote app that I am building. I see that I must use OAuth2.0 to first authorize my users before they are allowed to access the salesforce data. At the moment I am trying to use the username-password OAuth flow described on salesforce.
Step 1) I request access token using username and password via the below code snippet
var password = 'userPassword' + 'securityToken'
$.ajax({
type: 'GET',
url: 'https://login.salesforce.com/services/oauth2/token',
contentType: 'application/json',
dataType: 'json',
beforeSend: function(xhr) {
xhr.setRequestHeader('grant_type','password'),
xhr.setRequestHeader('client_id', '<client_id_here>'),
xhr.setRequestHeader('client_secret', '<client_secret_here'),
xhr.setRequestHeader('username', 'username#location.com'),
xhr.setRequestHeader('password', "password")
},
success: function(response) {
console.log('Successfully retrieved ' + response);
//Other logic here
},
error: function(response) {
console.log('Failed ' + response.status + ' ' + response.statusText);
//Other logic here
}
});
My request, however, is failing with the following message:
1) OPTIONS https://login.salesforce.com/services/oauth2/token 400 (Bad Request)
2) XMLHttpRequest cannot load https://login.salesforce.com/services/oauth2/token. No
'Access- Control-Allow-Origin' header is present on the requested resource.
Origin http://localhost is therefore not allowed access.
I have seen some sources (here here here) mention that CORS is not supported in salesforce, and that another solution should be used. Some solutions I have seen are Salesforce APEX code, AJAX toolkit, or ForceTK.
In summary, I am looking to see if (1) there is a simple mistake that I am making with my above request to get the OAuth access_token (2) or if I need to do something different to get the access (3) is there a better way to login users and access their salesforce data from my connected app?
All and any help is appreciated!
You will need to handle the OAUTH part on your own server. This isn't just due to lack of CORS, there is also no way to securely OAUTH purely on the client-side. The server could really be anything but here is an example server written in Java using Play Framework which has a JavaScript / AngularJS client as well: http://typesafe.com/activator/template/reactive-salesforce-rest-javascript-seed
You can not make this request from JavaScript. You'll need to make a server side request. There are many implementations of this flow in PHP, C#, Java, etc.
I'm posting my ajax code here that has worked for me and this CORS error in console doesn't matter. If you see in network you will get the access token.
see the ajax code below.
function gettoken()
{
var param = {
grant_type: "password",
client_id : "id here",
client_secret : "seceret here ",
username:"username",
password:"password with full key provided by sf"};
$.ajax({
url: 'https://test.salesforce.com/services/oauth2/token',
type: 'POST',
data: param,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
success: function (data) {
alert(data);
}
});
}
I hope this will work for you perfectly.
I think you need to add the origin URL/IP in CORS setting as well in salesforce if you are making a request from Javascript app so it can get access to salesforce data.
I'm trying to use jQuery to POST a form to chargify. My "Net" tab shows a 302 redirect (in red indicating an error), but jQuery is throwing a 404 error. Is it possible to preform a x-domain, post, redirect request from the browser or will I need to use proxy?
$(function() {
var endpoint = "https://api.chargify.com/api/v2/signups"
$('#new_sub_form').on('submit', function(e){
e.preventDefault()
var jqxhr = $.ajax({
type: "POST",
url: endpoint,
crossDomain:true,
data: $('#new_sub_form').serialize(),
success: function(data, textStatus, request){
console.log(request.getResponseHeader('Location'));
},
error: function (request, textStatus, errorThrown) {
console.log(request.getResponseHeader('Location')); // Returns null
}
})
})//on('submit')
})//ready()
UPDATE (more info):
So I realized the 302 was redirecting me to a page that didn't exist on my server. Unfortunately once i fixed this, I still have an issue. From what I can tell, i POST to chargify, they then send a 302 back to the browser with the URI I specified. This URI is located on my server (localhost for now). Once the user is redirected my server parses the response and returns JSON. I tested the Response Header location via copy and paste into another tab and works fine.
Chargify is only offering https, while my localhost is http. Would this cause the error?!
HTTP Response
Ran into to a very similar problem the other day. However im using ASP.NET MVC4.
Its not enough if you use crossDomain:true u also need to add,
dataType: 'json or html depending on the return value',
xhrFields: {
withCredentials: true
},
You will also need to add these headers "Access-Control-Allow-Origin:"http://yourdomain.net" ,
Access-Control-Allow-Credentials:true" and maybe "Access-Control-Allow-Methods:GET,POST" in your case aswell to your RESPONSE.
Chargify Direct does not support ajax/CORS.
You should use a "transarent redirect", as they describe, which is basically a standard form post redirecting the user to Chargify, and they will redirect the user back again to the URL you specify in the payload. This means the user will briefly leave your site and return back to it.
<form method="post" action="https://api.chargify.com/api/v2/signups">
</form>
Docs: https://docs.chargify.com/chargify-direct-introduction