I can't seem to make an ajax call to my Web API controller. Either the URL isn't right (method not found) or I get a method not allowed error. This is my ajax call:
$.ajax({
url: 'server/InstallApp',
type: 'POST',
data: {server: serverAsJson, appWithGroup: appWithGroupAsJson},
contentType: "application/json",
success: InstallRequested
});
That ajax call is being called from this URL:
http://serverName/PrestoWebApi/app/#/server/ApplicationServers%5E%5E8
These are the various URLs I've tried to use in the above ajax call, and the result:
url: 'server/InstallApp'
POST http://serverName/PrestoWebApi/app/server/InstallApp 404 (Not Found)
Notice that the # is missing. Not sure if that matters.
url: '#/server/InstallApp'
POST http://serverName/PrestoWebApi/app/ 405 (Method Not Allowed)
Not sure why the URL is truncated like that. Why Method Not Allowed when the URL doesn't even match the controller?
url: '/PrestoWebApi/app/#/server/InstallApp'
POST http://serverName/PrestoWebApi/app/ 405 (Method Not Allowed)
I'm not sure what to try. I've done this with other apps. I even tried putting webdav removal entries in my web.config.
This is my controller (note that I can call the Get method in my controller):
[EnableCors(origins: "http://serverName", headers: "*", methods: "*")]
public class ServerController : ApiController
{
public ApplicationServer Get(string id)
{
// Get code here
}
[HttpPost]
public void InstallApp(ApplicationServer server, ApplicationWithOverrideVariableGroup appWithGroup)
{
Debug.WriteLine("snuh");
}
I'm at a loss. Any ideas on what to try?
The # in your URL is used for client side logic, most likely routing, and is completely ignored in your WebAPI routes.
i.e. this URL:
http://serverName/PrestoWebApi/app/#/server/ApplicationServers%5E%5E8
Is interpreted as this on the server:
http://serverName/PrestoWebApi/app/
The second issue I see is that, unless you specifically changed this in your WebApiConfig, your WebAPI methods do not reside at /app, rather /api (or possibly /server in your case). You could change your ajax call to:
$.ajax({
url: '/PrestoWebApi/server/InstallApp', // or /PrestoWebApi/api/server/InstallApp
type: 'POST',
data: {server: serverAsJson, appWithGroup: appWithGroupAsJson},
contentType: "application/json",
success: InstallRequested
});
You can see exactly what the URL should look like by going to the WebAPI welcome page (probably http://serverName/PrestoWebApi/api) and looking at the Help page by clicking Api from the navigation bar.
The URL for your ajax call should be, "HTTP://{{domainname}}.com/api/{{controller}}"
For example, "http://myapiproject.com/api/server"... unless you have your controller in a different directory than "Controllers."
Then, since you've set the HttpPost attribute on the "InstallApp" method of your controller, you just make sure that the 'type' setting in your ajax call is set to 'POST' and it should route.
Doing it this way, you won't be able to have two methods with the [HttpPost] attribute added to it.
Related
I have my json data which i need to be posted to a url or just update the json data in one of my site urls. But i get the 405 error.
This is my code.
$.post("details", {name: "John", location: "us"});
405 errors can be traced to configuration of the Web server and security governing access to the content of the Web site. It seems that the server to which you are sending the Post request(your Site's server) has been configured to block Post request. You can configure your server to allow the Post request. For more details, go to http://www.checkupdown.com/status/E405.html
I had the same problem. My failure was in the sort of the request:
I had a "POST" request in my mockserver.js:
{method: "POST", path: "app/Registration/sendRegisData.*", response: function (xhr) { xhr.respondFile(200, {}, "../testdata/getUser.json"); } }
and tried to use this path with a "PUT"-call in my controller:
$.ajax({
url: "z_dominosapp/Registration/sendRegisData",
type: "POST",
data: data
}).done(function(){.......});
First, I didn't noticed it and was wondering why only the "fail" part of the ajax call was called. Maybe this careless mistake of me helps you in any way.
I'm using jquery's .ajax method to make a get call to ruby on rails api. The body of get call includes a boolean variable. However this boolean variable keeps getting converted to string on rails side. I'm using correct contentType when making the request.
Here is my javascript ajax call:
var postBody = {male: true}
var request = $.ajax({
method: "GET",
url: "/biographies/getAll",
dataType: 'json',
contentType: 'application/json',
data: postBody
});
On Ruby on rails controller side, I'm using:
params[:male]
However params[:male] returns "true" string instead of true boolean.
According to Ruby on Rails api:
If the "Content-Type" header of your request is set to "application/json", Rails will automatically convert your parameters into the params hash, which you can access as you would normally.
http://guides.rubyonrails.org/action_controller_overview.html#json-parameters
Does anyone has any idea why it would not convert json request to boolean but keep it as string.
thanks.
In Rails, parameter values are always strings; Rails makes no attempt to guess or cast the type. You have to modify your code logic to adjust with this Rails behaviour. e.g.:
params[:male] == 'true'
See this for reference.
I am trying to issue a simple AJAX request to populate a menu in Laravel, however, I am having a lot of trouble with getting it to work properly.
I am not sure what the issue is, and after a couple hours of searching, I cannot find anything that can help.
Here is my AJAX request:
$.ajax({
type: 'POST',
url: '/ajax/populateApiAuth',
data: json,
dataType: 'JSON',
success: function (json) {
alert('test');
return true;
},
error: alert('fail')
});
My route to the AJAX callback:
Route::get('/ajax/populateApiAuth', 'ApiController#populateApiAuth');
and my controller to handle the AJAX callback in ApiController:
public function populateApiAuth()
{
return Response::json(array('msg' => 'test');
}
When sending the AJAX request, it returns with the fail message in the error parameters, and in the console, it tells me:
POST http://localhost:8000/ajax/populateApiAuth 405 (Method Not Allowed)
Researching this error message, it results from making a POST request to a different domain/server? How can this be?
I have tried to use an absolute URL for the AJAX request with:
url: '{{ URL::to("ajax/populateApiAuth") }}
which gives the full URL: http://localhost:8000/ajax/populateApiAuth but that does not solve the issue either.
Wouldn't this be your issue?
Route::get('/ajax/populateApiAuth', 'ApiController#populateApiAuth');
You set the route up for GET requests, but you're trying to access it via a POST request.
I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});
Currenly i use asp.net web service but when i call web service method by ajax call it always return XML not json
i try
ASP.Net web service won't return JSON - Always XML
but its also not work for me..
JS :-
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "jsonp",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
LoginWebservice.asmx :-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Demo()
{
return "Harshit";
}
where i am wrong..
jsfiddle Example:-
http://jsfiddle.net/EXvqc/
First you have to use Post method to send a request to your web service. And as you have used JSONP as it always looks for the callbacks, and you have to define callback methods for it.
Please Refer
And the other thing you have to add like following
[System.Web.Script.Services.ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class LoginWebservice : System.Web.Services.WebService
{
[WebMethod]
public string Demo()
{
return "Harshit";
}
}
Indicates that a Web service can be invoked from script. This class cannot be inherited.
Your aspx/HTML will contain
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "http://www.quietincomes.com/LoginWebservice.asmx/Demo",
dataType: "json",
success: function (data) {
alert("1" + data);
},
error: function (result) {
alert("2" + JSON.stringify(result));
}
});
See output below
JSONP is not JSON, JSONP is used to get over the same origin policy (site A cannot make ajax request to site B). To solve this problem site A will create a script tag:
document.createElement("script")
Then set it's source to site B, usually specifying a callback like www.B?callback=callMe
A typical response of site B would be:
callMe({siteBSays:"hello"});
JQuery hides creating the javascript element for you so it looks like a normal ajax request. Make sure site B has the right response type headers I think it's text/javascript
Another way to do cross domain requests is that site B has a response header that allows site A making ajax requests to it (cors) by setting a response header Access-Control-Allow-Origin