I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!
Related
I am running into CSRF token validation failed error when trying to do a POST request on an endpoint which is on a different server using cors-anywhere. Its mostly because the CSRF Token that I am passing to the cors-server is cached and hence the validation fails.
I have read the following Stack Overflow link - Similar issue
. Turns out my problem is same as the one in the link but since that link does not contain any solution I am asking it here.
Please help.
EDIT:-
$.ajax({
async: false,
crossDomain: true,
data: batch_request,
url: "https://cors-anywhere.herokuapp.com/https://......api.s4hana.ondemand.com:xxx/sap/opu/odata/sap/API_MKT_CONTACT_SRV;v=0002/$batch",
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic xxxxxxxxxxxxxxx");
xhr.setRequestHeader("X-CSRF-Token", "xxxxxxxxx");
xhr.setRequestHeader("Content-Type", "multipart/mixed;boundary=batch");
},
success:function(response) {
console.log("Succesfully added new contacts");
console.log(response);
},
error: function (error) {
console.log("Error");
console.log(error);
}
});
I have made a GET call using POSTMAN and retrieved the CSRF token from the server. For now, I have hardcoded the token in the AJAX call. I receive the following error when I do it-
CSRF validation depends on matching two tokens associated with the request. Typically one is in the request itself and the other is stored in a session associated with the request by a cookie.
Since you are going through a simple proxy, you are anonymising yourself and there is no session associated with the request.
If you want to work around this, then you would need to write your own server-side proxy which maintained the session on a per-user basis.
I'm trying to send Ajax request using jquery and HTML5.
I have several pages in my application.
Is it possible to make Ajax request on a page(e.g sync.html) and receive response on a different page(e.g home.html).
I know there are other approaches to this like web-sockets and long pooling but if it's possible to achieve this using Ajax then that will make my work easier preventing me from changing any server configurations.
I'm using ASP.NET,C# on the server side.
The reason why I'm doing this is to prevent users from waiting for the response before they resume doing any other activity because this might take long depending on the size of data sent to server and the internet speed.
$.ajax({
dataType: 'jsonp',
jsonp: 'jsonp_callback',
url: server_url,
data: {
number_chunksdone : num_chunksdone,
sync_data: round_1_sync_data,
organisation_id: organisation_id,
sync_id: sync_id,
instrument_id: instrument_id,
user_id: user_id,
sync_data_2: round_2_sync_data
},
success: function (j) {
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Any idea?
You can try writing Location.replace() or Location.assign() method inside success function. For e.g., document.location.replace('home.html');
The Location.replace() method replaces the current resource with the one at the given URL.
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 set up a generic call to webservices using jquery $.ajax. I'd like to be able to get raw data back and bind it to a grid.
I have calls working correctly when I know the dataType, but I want to try and make an ajax call without knowing the datatype, specifically to find what the dataType is.
For example, my ajax call knowing the datatype could be:
$.ajax({
type: 'GET',
crossDomain: true,
dataType: "jsonp",
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff;
},
error: function (jqXHR, textStatus, errorThrown) {
//DoStuff
}
});
But any time I make a request without knowing the datatype I simply get a response status of "Error"?
What I would eventually like to be able to do with this is ping a url (webservice) that returns json, xml, or perhaps odata(unlikely). Since I won't know which, I want to be able to simply make a call to the url once to find out what kind of data I might get back, along with what content-type there is.
I've tried simply getting back the content type in the header in the error, but so far nothing I've tried has worked or returned anything at all.
$.ajax({
type: 'GET',
crossDomain: true,
url: 'http://itunes.apple.com/search?term=coldplay',
success: function (res, status, xhr) {
//DoStuff
},
error: function (jqXHR, textStatus, errorThrown) {
$("#results").html(textStatus + jqXHR.getResponseHeader('Content-Type'));
}
});
Can this even be done with Jquery?
Edit
I am aware that this can (and in most cases should) be done server side, and in all likelihood this is what will end up happening. But for the purposes of seeing how far I can go binding a grid to a datasource clientside without knowing my dataType the above question is born.
Thanks to all for the time.
Your approach is reasonable, but you are asking the user's browser to fetch information from a third party web server.
XMLHttpRequest cannot load http://itunes.apple.com/search?term=coldplay. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
Unless the third party grants you permission, the Same Origin Policy will prevent your JavaScript from accessing any information about the response.
You should move your logic server side.
I need to build a login box satisfying the following requirements:
Build it as a UI Component that can be used in multiple locations on a site
Two instances of this component can exist on the same page
Use jQuery, HTML5 and CSS3
Your site supports IE9+ and current versions of Safari, Chrome,
Firefox
Your site supports iOS6
Login form submits username and password data using AJAX to:
api.yoursite.com/login
This is a demo/test, so the referenced site is hypothetical (but a solution would obviously need to pass on a real site).
The wording of the last requirement is somewhat odd - should I assume api.yoursite.com/login exists on the same domain? Perhaps I'm overthinking this, but I initially assumed the opposite, and began researching a cross-domain approach. The fiddle I am up with can be found here: http://jsfiddle.net/manh2244/rwxq5/8/. I attempted with JSONP, albeit unsuccessfully:
$(":submit").click(function (e) {
var username = $(".loginID").val();
var password = $(".loginPassword").val();
$.ajax({
url: "http://api.yoursite.com/login",
type: "GET",
data: {
username: username,
password: password
},
dataType: "jsonp",
success: function (data) {
console.log(data);
},
error: function (jq, status, message, data) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
console.log(data);
}
});
e.preventDefault();
});
I'm at a loss and am now wondering if:
I should look into CORS
If I'm indeed overthinking this, perhaps the solution is much simpler than I thought
Either way, I still haven't factored in what happens server side once the form is submitted. A requirement indicated I can only use jQuery, HTML and CSS, none of which seem appropriate. That is, unless I can have a login.php file - the requirements are only for building the login box. They don't account for what happens once the login credentials are submitted.
Try modifying your ajax call as follows:
$.ajax({
url: "http://api.yoursite.com/login",
type: "POST",
crossDomain: true,
data: {
username: username,
password: password
},
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (jq, status, message, data) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
console.log(data);
}
});
Use CORS by all means if your application is for latest browsers. It will make your life a lot easier. When using CORS, you would have to change response headers on server side. Below is an example in python, you should be able to write similar code in php or what ever language your server side is in:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response