I have the following AJAX PUT request that was given to me. I'd like to run it from a Python script. I'm new to everything AJAX/HTTP related, so I'm guessing. Here's the request:
$.ajax({
url: <insert base URL here> + "/state",
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify({
state: "<insert state here>",
state_modified_by: $.cookie("<insert username here>")
}),
complete: function(data) {
document.location.reload();
}
})
Here's my attempt at implementing the same request in Python using the requests library:
import requests
url = <insert base URL here> + "/state"
data = json.dumps({"state" : "<insert state here>", "state_modified_by" : "<insert username here>"})
headers = {"Content-Type":"application/json"}
response = requests.put(url, headers = headers, data = data)
That gets me a "bad request" response from the URL.
Things I'm definitely unsure about:
- Is using the requests library even the best route? Is there an easier way to run jQuery type stuff from Python?
- Is json.dumps equivalent enough to JSON.stringify?
- What is "$.cookie" and how do I do something similar in Python?
- How do I do the "completion event" that the AJAX request does using requests in Python?
Any help is greatly appreciated - thanks very much!
Related
I'm currently creating a hybrid mobile application.
While running the application on an Android emulator, I get the following error: Status Code:404 Not Found (from cache) in one $http.post request.
Below is the post request used in my code. The URL is of a local Tomcat server being used in my project.
var postData = {'loginId':$scope.user.id};
postData = $.param(postData);
$http({
method: "POST",
url: checkUserURL,
data: postData,
cache:false,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;'
}
});
When I place the url in href of an anchor tag inside the mobile application and click it, I get redirected to the mobile browser from where I'm able to hit the url and get the expected output.
I am able to access the url from my web browser too. The error occurs only when I try to use the $http request in the application.
Note: I've all the libraries needed included in my project.
Is it because of the format of the data I'm sending to the server?
Can you please let me know what could be the issue here and the possible resolution actions that can be taken?
It's probably because of the way you are passing your parameter. You don't have to use $.param. Try to pass a plain JavaScript object:
var postData = {
loginId: $scope.user.id
};
$http({
method: "POST",
url: checkUserURL,
data: postData,
cache:false
});
I want to clear my http response before each request sending to API.
My Http request:
$http(
{
method: 'GET',
url: URI,
headers: { 'Content-Type': 'application/json' },
async: false
}).success(function (data) {
$('#processing').hide();
$scope.items = JSON.parse( angular.toJson(data));
$scope.header = $scope.items[0];
Could you please help me ,so that each time I will get new response?
Thanks
The response is probably cached by browser or something between your browser and server.
You can either try to prevent caching by adding header which tells the browser not the cache given response
Or
you can append unique timestamp to the URL, like this
var no_cache_url = URL + new Date().getTime()
If you are using some query string in your url then the code is slightly more complicated, but you will figure that out.
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.
Currently I'm using this function to send my JSON from a chrome extension. This is the client code from javascript sending the data.
function callPython(){
var url = 'http://AWS_IPNUMBER/';
var data = {'bob':'foo','paul':'dog'};
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
success: function(data){
var jsonObj = $.parseJSON(data);
alert(jsonObj.encPassword);
},
failure: function(errorMsg) {
alert(errorMsg);
}
});
}
This is the server code for Python:
s = socket()
s.bind(('', 80))
s.listen(4)
ns, na = s.accept()
while True:
try:
data = ns.recv(8192)
except:
ns.close()
s.close()
break
data = json.loads(data)
print data
The problem is that although it is listening, data is empty at data = ns.recv(8192). Then data = json.loads(data) doesn't work since data is empty. Why is this? I thought it may be a problem with my security group on AWS but if I go to http://AWS_IPNUMBER/ I get the header from the browser while running the python script.
You may have better luck with a good framework like tornado or django.
I say this because in your code you are trying to parse an http POST with json.loads. HTTP isn't that simple. You will need to deal with the request and headers before you get to the body, and this can be spread out across multiple packets. Why try to reinvent the wheel when you can setup a standards compliant server from a well established project.
The data that $.ajax function will put is a complete HTTP request, which json.loads() won't understand. In this case you need to instantiate a HTTP server which will process the HTTP requests and then process the HTTP payload with json.loads().
I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.