JavaScript: cross site request on localhost on ASP.NET WebAPI - ajax

I have an ASP.NET WebAPI application running on
http://localhost:13057/worldwind
I have another ASP.NET MVC5 application running on
http://localhost:2425/worldwind
When the client code on the MVC5 application attempts the following AJAX call:
$.ajax(http://localhost:13057/worldwind/images,
{
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: Utilities.Logger.displayAjaxError,
success: this.onImagesRetrieved,
context: this
});
I get error:
XMLHttpRequest cannot load http://localhost:13057/worldwind/api/images. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:2425' is therefore not allowed access.
If I change the dataType in the AJAX request to jsonp, the WebAPI is being invoked even though I get error
jQuery18209344927002675831_1412452833242 was not called
How do I get this thing working?

I ended up enabling CORS following instructions from here
This involved 3 steps (well, after fighting with other NuGet upgrade issues):
Adding NuGet package Microsoft.AspNet.WebApi.Cors
Adding the following lines in WebApiCconfig.Register static method:
var cors = new EnableCorsAttribute("http://locahost:2425", "*", "*");
config.EnableCors(cors);
Rebuilding and running.

if your .jsp put in
http://localhost:13057/MySite/JSONP.jsp
use your script section like this:
<script type = "text/javascript" src="http://localhost:13057/MySite/JSONP.jsp?callback=jsonHandler"></script>
hope it will be help.

Related

Cross Origin Domain Blocking error with AJAX

Could anyone please tell me what I am doing wrong:
I'm using the following code and getting a Cross Origin Domain Blocking error. And no I don't have the ability to enable CORS on the Server Im getting data from. But when I use the URL by itself, I get the data I am after, it's just not working with AJAX, Im trying to use JSONP to get around the issue:
$(document).ready(function () {
$.ajax({
url: "https://serveraddress/remote-json.cfm?do=gettimetable",
dataType: "jsonp",
jsonpCallback: "logResults"
});
});
kind regards,
Brad
You can use back-end to solve this problem. This back-end(php, java, nodejs, curl...) implement a httpclient to getting data from any server.
I try to set "useDefaultXhrHeader: false", it is the configuration ajax.

Headers Issue with file upload via CarrierWave

I am trying to upload a file via Carrierwave to a Rails backend with this Ajax post
$.ajax({
url: mypath
data: myformdata
contentType: false
processData: false
type: "POST"
})
I am getting a "No 'Access-Control-Allow-Origin' header is present on the request resource" and therefore a 500 Internal Server Error.
All other requests are handled by Ember.js and are working properly, through simple-auth-devise.
Any idea what the problem might be?
Thank you in advance for any suggestion!
You need to setup your app to work with CORS on your Rails backend.
See these articles:
http://leopard.in.ua/2012/07/08/using-cors-with-rails/
https://demisx.github.io/rails-api/2014/02/18/configure-accept-headers-cors.html

jQuery ajax POST from local file to access a cross domain not working

As the title says, I'm trying to access (POST) using jQuery AJAX call to a web url, http://host:port/... or http://localhost:8080/... from a local HTML file, c:\home.html. I can't get it to work.
I did Google and also saw several questions here but I can't get it to work. I need some help here. Here is what I've tried so far.
dataType: jsonp
crossDomain: true
Setting the header in my response:
response.setHeader("Access-Control-Allow-Origin", "*");
None of the three browsers are working - IE, FF or Chrome. The request is never reaching the server. Here are some of the errors I'm seeing.
No Transport (IE) if not jsonp is used.
NS_BINDING_ABORTED / Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED) in FF
This is my code. I would appreciate any help. I'm using jquery-1.8.2.min.js.
var http_host = "http://localhost:8080";
function su (pc, p) {
var suUrl = http_host + "/ps/api/v2/authorize.json";
$.ajax({
type: 'POST',
url: suUrl,
data: {
phone_cell: pc,
password: p,
},
dataType: "json",
crossDomain: true,
success: osu,
error: oe
});
return false;
}
function osu (d) {
console.log(d);
}
function oe(xhr, ts, et) {
alert("ServerError: " + et);
}
An example would be a perfect pointer.
I suppose my code got messed up w/ all the different solutions that I was trying. I was finally able to get it to work w/ setting the header (solution that was recommended and worked for others). All that I had to do to get it to work is add the following to my REST service response.
response.setHeader("Access-Control-Allow-Origin", "*");
Update:
I thought I figured this out but I've not. There is more it than just setting the header. Anyways, in my specific situation. I was trying to run my app (html, js) off of the hard drive specifically on chrome and trying to access web services available on the cloud.
Here is how I finally solved the problem. I started the chrome w/ the following parameters.
--disable-web-security -–allow-file-access-from-files
Like I mentioned earlier, this app is really a desktop application that will be run as part of the chromium embedded framework.
Thanks every one for your input.
You can't make a cross-domain request from a local file because it's not on a domain. You need to host C:\home.html on a local webserver instance in order for it to work.

Ajax requests ignore virtual application sub-folder name in URL for ASP.NET MVC application

My application is located on the server under a separate virtual directory. To access my ASP.NET MVC application users have to go to:
http://server-dev/superApp
I have a problem with Ajax/Json server requests ignoring the "superApp" directory part. Whenever an Ajax request is made Fiddler shows 404 because instead of http://server-dev/superApp/User/GetUsersJson for example, http://server-dev/User/GetUsersJson is called (note the missing superApp name).
Example of an Ajax request:
function GetUsers(id) {
$.ajax({
url: "/User/GetUsersJson/",
data:{ id: id},
datatype: 'json',
type:'post',
success: function (result) {
////Do stuff with returned result
}
});
}
Registered route:
r.Match("User/GetUsersJson", "User", "GetUsersJson");
Where should I look and what can I change to make sure that my application virtual folder is ALWAYS included in all URL requests ?
p.s. Please note that all Javascript/Ajax logic is kept in separate .js files so no RAZOR syntax is available.
Did you try using the HTML helper method ?
url: "#Url.ACtion("GetUsersJson","User)"
EDIT : As per the comment
You may get the Path name using the HTML Helper method and Keep that in a Global variable and access that in the external javascript file
In the view
<script type="text/javascript>
var globalGetJSONPath='#Url.ACtion("GetUsersJson","User)';
</script>
And now you can use it in the external file like this
$.ajax({
url: globalGetJSONPath,
data:{ id: id},
//remaining items....
});
I solved this stuff by passing variable to js that contains hostname+vdir. Because of heavy js url generation.
In other cases Shyju's answer is best way to solve this.
No way to do it without some server-side code generation. Easiest thing would be defining global variable (sorry) holding you application root and initializing it somewhere in master page.
Javascript generation of route urls always was one of the messiest parts of asp.net mvc.

Extjs to call a RESTful webservice

I am trying to make a RESTful webservice call using Extjs. Below is the code i am using:
Ext.Ajax.request({ url: incomingURL ,
method: 'POST',
params: {param1:p1, param2:p2},
success: function(responseObject){
var obj = Ext.decode(responseObject.responseText);
alert(obj);
},
failure: function(responseObject){
var obj = Ext.decode(responseObject.responseText);
alert(obj);
}
});
but it does not work, the request is sent using OPTIONS method instead of POST.
I also tried to do the same thing using below code but result is the same:
var conn = new Ext.data.Connection();
conn.request({
url: incomingURL,
method: 'POST',
params: {param1:p1, param2:p2},
success: function(responseObject)
{
Ext.Msg.alert('Status', 'success');
},
failure: function(responseObject)
{
Ext.Msg.alert('Status', 'Failure');
}
});
But when i tried to do the same thing using basic ajax call ( using the browser objects directly i.e. XMLHttpRequest() or ActiveXObject("Microsoft.XMLHTTP")) it works fine and i get the response as expected.
Can anyone please help me, as i am not able to understand what i am doing wrong with extjs ajax call?
You can't make a standard AJAX call between domains. The URL for Ext.Ajax.request should be a relative one (relative to the script's origin).
If you want to do cross-domain calls, use a ScriptTagProxy or such.
The problem is exactly because of the reason ob1 and Chuck Hinson described.
I have an RESTful service, wich is running on Tomcat.
And i made a static client(no deployed to Tomcat) using ExtJs with Json reader.
I just made an html page with ExtJs integrated consuming REST service like url: http://localhost:8080/service/invoices/
And all the time ExtJs was making OPTIONS request, not GET or POST even if i was setting them as being used methods. The problem is this security feature, because Client is not the part of same application and i am doing AJAX call between domains.
As soon as i put my client to my Web application and deployed to Tomcat and started using relative calls it started working.
if you don't want cross-domain request, please remove the website prefix 'http://website' from propery url of ajax proxy.

Resources