How to route an array of parameters in Rails 3 - javascript

I´m trying to route an array of parameters in my Rails 3 app but i keep getting a 404 error.
Here´s the ajax request in my JS file:
var url = '/arrayquery?kind[]=startup&kind[]=investor'
$.ajax({
url: url,
dataType: "text"
}).done(function(data) {
console.log(data)
})
My routing:
match 'arrayquery/:kind', :to => 'home#arrayquery'
And my controller method:
def arrayquery
#players = Player.where("kind = ?", params[:kind])
end
My browser keep throwing this line:
"NetworkError: 404 Not Found - http://localhost:3000/arrayquery?kind[]=startup&kind[]=investor"
Does anybody know why there´s no matching route for the request?

The route you've defined in your routes file is looking for,
http://localhost:3000/arrayquery/KIND?param=value&param=value
Try changing the route to,
match 'arrayquery', :to => 'home#arrayquery'

Related

How to pass variables in a get request without showing it in the url - nodejs

I want to make a get request to render a page but I need to pass 2 variables to that page. How can I create a ajax request to do this without having the variables show up in my url such as var1=?var2=?.
$.ajax({
async: true,
type: 'POST',
url: '/profile',
data: {
'UID': currentUid,
'Name': user_data.displayName
},
success: function (res) {}
})
I thought of creating a post request and passing the variables that way but then how do I render the page that I want to because my Post request doesn't fetch the page
In express you should get the page using
app.post
instead of
app.get
If you do for example:
var express=require('express')
var app=express()
app.get('/profile')
Your app will not fetch the page using POST method. Only GET method.
This might be your issue.
More info:
App req.METHOD()

Using a URL as a URL parameter in Django Rest Framework

I have a model whose unique field is an address. The thing is, I am trying to get instances of this model using AJAX.
var address = 'http://example.com/blog/2/';
$.ajax({
url: 'http://sitemy.com/api/get_content/'+encodeURIComponent(address),
type: 'GET',
dataType: 'json',
success: function(json) {
console.log('Success');
}
});
In my urls.py, I have the following code:
url(r'^api/get_content/(?P<url>.+)/$', views.get_content),
So I am trying to use this URL pattern to capture the get request. However, I am constantly getting a 404 error since the url sent from the request does not match my pattern. What gives? How can I solve this?
In case its important, in my views, I am doing the following:
def get_content(request, address):
try:
content = Content.objects.get(address=urllib.unquote(address))
except:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = ContentSerializer(content)
return Response(serializer.data)
Any help would be appreciated. Also, I welcome any general advice regarding the encoding of URLS, as that just boggles my mind for some reason. Thanks.

How to "get" from NodeJS with AngularJS

I started an AngularJs App and to retrieve some data from database I'm using NodeJS (totally new to me), on the console of NodeJS it works and also typing the URL directly in the browser but when I try to get the information needed using http.get() in AngularJS using the same URL in the browser I get 404 not found.
I figured it would be a cors problem so I added
require('cors') in the nodeJS app and still doesn't work
Can anyone help me with that ?
Am I right making separate apps for Angularjs in front-end and NodeJS in the Backend or should I assemble them in only one application ?
Thank you for your help
This is the AngularJS code:
$scope.keyLoad = function () {
$http.get("localhost:8080/product")
.success(function (response) {
$scope.keys = response;
console.log(response)
})
};
$scope.keyLoad();
I get 404 not found. I figured it would be a cors problem
If it says it is a 404 error then it is a 404 error and not a CORS problem.
Look at your code:
$http.get("localhost:8080/product")
That URL is missing the scheme. It is a relative URL.
You are going to be requesting something like http://example.com/myapp/localhost:8080/product.
Put http:// or https:// in front of it.
You should use $http service.
For example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Or
$http.get('/someUrl', config).then(successCallback, errorCallback);

(Ruby-On-Rails4) Route error when calling method from ajax

I'm trying to retrieve some information calling a method through ajax. It seems I'm missing something on my code, because when troubleshooting from chrome inspect I get an "url not found" error. My Models are Warehouse & Product. What i would like to accomplish is when a product is selected from the select_tag field, populate a text_field with a default price for that product. This is what I have so far:
1. select_tag view:
<%= select_tag "product_selection", options_from_collection_for_select(Product.all, "id", "name") %>
2. warehouses.js
$(document).on("change", '#product_selection', function() {
$.ajax({
url: "/warehouses/get_price",
type: "GET",
dataType: "json",
data: { product_id: $('#product_selection option:selected').value() }, // This goes to Controller in params hash, i.e. params[:file_name]
complete: function() {},
success: function(data, textStatus, xhr) {
// Do something with the response here
document.getElementById("default_price").value = data.default_price;
},
error: function() {
alert("Ajax error!")
}
});
});
3. warehouses_controller.rb
def get_price
#price = Product.find(params[:product_id]).price
if request.xhr?
render :json => { :default_price => #price }
end
end
4. routes.rb
resources :products
resources :warehouses
resources :warehouses do
member do
get 'get_price'
end
The message I get from Chrome Inspect:
jquery.self-c64a743….js?body=1:10244 GET http://localhost:3000/warehouses/get_price?product_id=2 404 (Not Found)
Check out Rails routing here: Rails Routes
Routes are read from the top down, and so it looks for :get_price in the first reference to warehouses. One choice is Combine the routes:
resources :products
resources :warehouses do
member do
get 'get price'
end
end
That will actually point to
/warehouses/{:id}/get_price
To lose the restful id, you could try
resources :products
resources :warehouses do
collection do
get 'get price'
end
end
That should respond to
/warehouses/get_price
and then pass the appropriate parameter.
Alternatively, To get the route that you are looking for, you could
get 'warehouses/get_price', to: 'warehouses#get_price'
resources :products
resources :warehouses
Notice the custom route is above the resources.
The Ajax call to the method (url: "warehoueses/get_price") was failing because I generated the get_price method inside the private methods section on warehouses_controller.rb so that was basically my mistake. Thanks anyway for the help!

Google UserService logoutUrl with Angular #

I am using the Google UserService to get login and logout URLs for my app engine Angular application and am trying to pass the path for the redirect as a query param. This is an example of an Angular URL:
http://localhost:8080/#/dashboard
In Java I am trying to create the Url like this:
String logoutUrl = UserServiceFactory.getUserService().createLogoutURL(redirectPath);
redirectPath is the query param string "#/dashboard" as expected.
The problem is that the URL that is produced with the included '#' does not work. It just redirects to itself with a new URL. Here is a sample of what the URL looks like that is generated from the UserService:
/_ah/logout?continue=%23%2Fdashboard
If I just pass the string "/" to the endpoint then I get a URL like this:
/_ah/logout?continue=%2F
This works as expected and loads my Angular app at the root document. I would really like to be able to get my UserService URLS to work as expected. Any ideas?
This is the URL that it redirects to from the URL above:
http://localhost:8080/_ah/logout?continue=%23%2Fdashboard#/dashboard
I found a solution to the problem. The UserService works fine if I send the full URL instead of just the resource path. My Angular code now looks like the following. The app will get the login URL and then redirect to the requested URL upon login. This is actually in a service but I simplified the code for StackOverflow.
$http({
url: '/rest/user/login_uri?redirectPath=' + encodeURIComponent($location.absUrl()),
method: 'GET',
contentType: "application/json"
}).success(function (data) {
$window.location.href = data.uri;
}).catch(function (data) {
//Handle failed request....
});
I hope this helps somebody down the road.

Categories

Resources