Status Code:404 Not Found (from cache) | Hybrid App using AngularJS - javascript

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
});

Related

Translating an AJAX put request into a Python request

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!

Salesforce OAuth with REST API using Javascript

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.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

GAE blobstore url error: GET not supported

I am having trouble with the google app engine blob store. I am running in the development environment (ie local on my machine.)
Heres what i am doing...
once the form pops up i call into a servlet to generate the URL like this
String url = blobstoreService.createUploadUrl("test/joi");
once i have that i save it in my java scrip and then once the user submits the form i am doing this
$.ajax({ url: self.url,
type: "POST",
//crossDomain: true,
dataType: "jsonp",
//dataType: "multipart/form-data",
success:
function(response, textStatus, jqXHR)
{
alert("saved.");
}
});
}
however, when i do that i get the following exception
GET 405 (HTTP method GET is not supported by this URL) jquery.js:4
i am really struggling with this and any help would be greatly appreciated!
Apart from any other issues, the blobstore expects file uploads in multipart form format; you're attempting to post to it using jquery. If you want to do the post in javascript, you will need to format the body of the POST request appropriately.

kendo mobile JSON data calling

I have written a code for taking JSON data from a PHP and putting to listview, it works great in localhost.
When I put the PHP file in a web server and called in Javascript it showing error and not getting data.
This method I have used:
var dataSource = new kendo.data.DataSource({
transport: {
read: {
//url: "userchk.php", //this works in localhost
url: "http://example.com/web/userchk.php", this is not working in localhost
dataType: "json", // JSONP (JSON with padding) is required for cross-domain AJAX
data: { //additional parameters sent to the remote service
q: "javascript"
}
}
},
The first url data is getting in localhost and works great, second url is not working(but data show if we run the url in a browser).
It show an error like this:
XMLHttpRequest cannot load http://example.com/web/userchk.php?q=javascript. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
waiting for a good response
This may be due to cross domain issue. You need to use datatype:jsonp .. A sample code reading data from ODATA Version 2.0 feed is as following ,
studentsData = new kendo.data.DataSource(
{
type: "odata",
transport: {
read: {
url: "http://server/Service.svc/Students",
dataType: "jsonp",
data: {
Accept: "application/json"
}
}
},
serverfiltering: false,
serverPaging: true,
batch: false,
pageSize: 10
});
You can read the complete "Kendo UI ListView Control and OData in Windows Phone Application" post.
Thanks
#debug_mode
This is related to the same origin policy that most web browsers implement. It seems like the php file you are trying to access is in another server other than your current one (localhost).
If you are tyring to access local:
I suggest you change the url to /web/userchk.php
If you are are trying to access another site
I suggest you change the dataType to "jsonp"
Try looking at the kendoUI datasource example with twitter. They try to access twitter (a different origin) using jsonp.

Categories