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.
Related
I would like to done an ajax request directly done by client on desktop.
Problem is my ajax request need a "secret api Key". I don't want the client has an access to this api key.
Here my currently js code:
var url = 'myurl';
var obj = new Object();
obj.api_key = "myKeyIwantToHide";
$.ajax({ url: url,
type: 'post',
dataType: 'json',
data: obj,
cache: false,
success: function(result){
alert(result);
}
});
It is possible to hide information to client with javascript in order to done my ajax request.
Thx,
Christophe
You cannot hide the api key completely from client. But if your client is non technical. You can make it hard for him/her to find api key. If you are using MVC you can set the api key when the first request is sent to the Index method and on return you can set it to a javascript variable. In this way user wont be able to see hardcoded value unlike in the code you have shown. If you are using ASP.NET then you can easily use ViewBag to set value to javascript variable using razor syntax.
If you look at the parameter of my ASP.NET MVC Controller clientId, it's always null.
the only way i can get it to not be null and actually pass the data through successfully is to create a class... but that gets tedious and I can't create a class for every backend function i make just to get this to work.
Is there a way to pass data successfully without creating a class?
Thank you for any help
Angular Factory
PlaylistsFactory.getUsersForClient = function (clientId) {
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: JSON.stringify(clientId)
});
};
Angular Controller
PlaylistsFactory.getUsersForClient(clientId)
.success(function (userList) {
console.log('success!');
});
ASP.NET MVC Controller
public JsonResult GetUsersForClient(string clientId) //clientId is always null unless i create an object
{
...
}
Try making your JSON parameter match the name of your C# parameter as well as encasing that in the data payload as JSON:
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: {clientId: JSON.stringify(clientId)}
});
};
i would recommend that you follow the rules of a RESTful API.
This means you should use the HTTP verbs like GET (getting data), POST (updating data), PUT (creating data), DELETE (deleting data). See http://www.tutorialsteacher.com/mvc/actionverbs-in-mvc
Then you could also add the parameter you want to pass into the route of your API: /Show/GetUsersForClient/{clientId}. See http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx
In this case you disengage the problem of sending data in the body without having a ViewModel on the MVC-Controller side.
When you want to proceed with your solution, then try creating the Object before sending it:
PlaylistsFactory.getUsersForClient = function (clientId) {
var payload = { clientId: clientId }
return $http({
method: 'POST',
url: '/Show/GetUsersForClient',
data: payload
});
};
MVC / WebAPI also sometime choke when the content-type in the request header is text/plain or application/json. For example: a json-object will not be recognized properly by .Net when sent in text/plain.
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.
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);
});
Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here