I'm building an app, using Rails and Backbone as my back-end, that requires users to login to access certain pages. On one of the user authenticated pages, I have it setup so they can create an entry in my database, by entering in data, which is then sent to the Google Maps API to retrieve the latitude and longitude.
Via a helper function, I'm checking if the user is authenticated or not, but when I send up the AJAX call to Google Maps API, the user token is also being sent up. Here's the code that I have set up right now.
In my api js file, which is ran first on load for my page
var token = $('#api-token').val();
$.ajaxSetup({
headers:{
"accept": "application/json",
"token": token
}
});
In my users_controller.rb
def profile
authorize!
#user = current_user
#bathrooms = Bathroom.all.sort_by { |name| name }
render layout: 'profile_layout'
end
def authorize!
redirect_to '/login' unless current_user
end
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
Here's my AJAX call
function getInfo(location) {
console.log('getInfo');
$.ajax({
method: 'get',
url: 'https://maps.googleapis.com/maps/api/geocode/json',
data:{address: location, key: 'API KEY GOES HERE'},
success: function(data) {
extractData(data);
}
})
}
You can try following steps:
function getInfo(location) {
console.log('getInfo');
delete $.ajaxSettings.headers["token"]; // Remove header before call
$.ajax({
method: 'get',
url: 'https://maps.googleapis.com/maps/api/geocode/json',
data:{address: location, key: 'API KEY GOES HERE'},
success: function(data) {
extractData(data);
}
});
$.ajaxSettings.headers["token"] = token; // Add it back immediately
}
Related
I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form.
At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax.
Views.py
def indexView (request):
form = FriendForm ()
friends = Friend.objects.all ()
return render (request, "index.html", {"form": form, "friends": friends})
def searchFriend(request):
if request.method =="POST":
form = FriendForm (request.POST)
if form.is_valid():
if request.is_ajax():
name = form.cleaned_data['name']
query = Friend.objects.filer(first_name__contains=name)
print(query)
return JsonResponse(list(query), safe=False)
else:
return JsonResponse(form.errors)
Main.js
$(document).ready(function() {
$("#form1").submit(function() { // catch the form's submit event
var search = $("#searchField").val();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
method: 'post',
dataType: 'json',
url: "search/ajax/friend/",
success: function(data) { // on success..
console.log(data)
}
});
return false;
});
});
Is your query getting printed in terminal ?
Friend.objects.filer use filter instead of filer
and use type: 'post' instead of method: 'post',
and add data: $(search).serialize(), instead of data: $(this).serialize(),
If login is successful i need to redirect to a login success page and I need to include a session in that.. How can it be possible. I am using html with vue js for front end and back end is django.
This is my vue js script for login.
<script>
logBox = new Vue({
el: "#logBox",
data: {
email : '',
password: '',
response: {
authentication : '',
}
},
methods: {
handelSubmit: function(e) {
var vm = this;
data = {};
data['email'] = this.email;
data['password'] = this.password;
$.ajax({
url: '/login/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if(e.status){
alert("Login Success");
// Redirect the user
window.location.href = "/loginsuccess/";
}
else {
vm.response = e;
alert("failed to login!");
}
}
});
return false;
}
},
});
</script>
So, how can I include session in login successpage.. This is the first time I am doing a work.. Please help me ..
If you are not doing a SPA, you can use the usual way of store sessions, put the session token in a cookie (the server is the responsible of doing when a successful login request happens). The next time the user do a request the cookie will send automatically to the server.
If you are doing a SPA, you can store the session token in the localStorage. In this case, you should configure the ajax calls to set a header with the token or any other way you prefer to send the token to the server.
I'm trying to wire up this AJAX POST request in my react component to communicate with my rails api controller. The console logs a 404 error and I can't seem to hit the pry.
react/src/pages/HomeIndex.js
getCompare() {
$.ajax({
url: '/api/sources/compare',
type: 'POST',
data: {value: this.state.inputValue, from: this.state.compareFrom, to: this.state.compareTo },
contentType: 'application/json'
})
}
controllers/api/sources_controller.rb
def compare
binding.pry
end
config/routes
post '/api/sources/compare', to: 'api/sources#compare'
namespace :api do
resources :sources, only: [:index, :compare]
end
rake routes
api_sources_compare POST /api/sources/compare(.:format) api/sources#compare
update
I tried updating the routes with several permutations...
namespace :api do
resources :sources, only: [:index] do
collection do
post :compare
end
end
end
namespace :api do
resources :sources, only: [:index, :compare] do
collection do
post :compare
end
end
end
namespace :api do
resources :sources, only: [:index] do
collection do
resources :compare, only: [:compare]
end
end
end
namespace :api do
resources :sources do
post :compare
end
end
...all with the same outcome.
You can solve this by stringifying your AJAX payload, as follows:
getCompare() {
let data = JSON.stringify({value: this.state.inputValue, from: this.state.compareFrom, to: this.state.compareTo })
$.ajax({
url: '/api/sources/compare',
type: 'POST',
data: data,
contentType: 'application/json'
})
}
I'm trying to pass a parameter through a url in an Ajax request that's triggered by a confirmation dialogue. I'd like to fetch the value of that parameter in my Rails controller given a successful request but I haven't been able to do it.
I've tried so far the following code:
Here my Ajax request where I've been adding the param in the URL plus other params in data
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "POST",
url: "/leaderboards/1/?test=1",
data: { leader: { name: name, time: time } },
success: success
});
}
Here the dialogue-related JS
function nameAlert() {
return confirm("Name already exists. Would you like to continue?");
};
(function() {
if (nameAlert()) {
continueSave();
}
else {
//something else here
}
})();
Although the request successfully reaches the controller there's params[:test] is nil in the controller.
I've also tried to pass the test param in data, but it is not working either.
Would appreciate some help.
The relevant controller action (leaders_controller.rb)
def create
#leader = Leader.new(leader_params)
#leader.leaderboard_id = #leaderboard.id
#name_repeated = !#leaderboard.leaders.find_by(name: #leader.name).nil?
#check = params[:test]
if params[:test].nil? && #name_repeated == true
render :template => 'leaders/repeated_name.js.erb'
else
#leader.save
#rank = #leader.rank_in(#leaderboard)
respond_to do |format|
if #leader.save
format.html { redirect_to root_path }
format.js { }
else
end
end
end
end
Note:
1.- 'leaders/repeated_name.js.erb' contains the code for the Ajax request
2.- In routes Leader resource is nested within Leaderboard resource
Sorry guys I found the mistake. It was a dumb one.
I have shallow nested routes so that leaders is nested in leaderboards, therefore I was using the incorrect path for the request. It should be:
$.ajax({
type: "POST",
url: "/leaderboards/1/leaders?test=1",
data: { leader: { name: name, time: time } },
success: success
});
I should have caught that before sorry for wasting your time.
I'll post here - my comments are getting too long.
Try adding { type: 1} to your data and changing type to GET. Rails params contain both GET and POST data - you don't even have to change your controller.
function continueSave() {
var name = $('#leader_name').val();
var persisted_time = $('#leader_time').val();
$.ajax({
type: "GET",
url: "/leaderboards/1/",
data: { leader: { name: name, time: time }, test: 1 },
success: success
});
}
I am calling web service on this url .
here is my code .
http://jsfiddle.net/LsKbJ/8/
$(document).ready(function () {
//event handler for submit button
$("#btnSubmit").click(function () {
//collect userName and password entered by users
var userName = $("#username").val();
var password = $("#password").val();
//call the authenticate function
authenticate(userName, password);
});
});
//authenticate function to make ajax call
function authenticate(userName, password) {
$.ajax({
//the url where you want to sent the userName and password to
url: "",
type: "POST",
// dataType: 'jsonp',
async: false,
crossDomain: true,
contentType: 'application/json',
//json object to sent to the authentication url
data: JSON.stringify({
Ticket: 'Some ticket',
Data: {
Password: "1",
Username:"aa"
}
}),
success: function (t) {
alert(t+"df")
},
error:function(data){
alert(data+"dfdfd")
}
})
}
Response
**
**
It mean that I first call this method then call login method ?
Perhaps the message means that during development, while you are writing and testing the code, use the URL:
http://isuite.c-entron.de/CentronServiceAppleDemoIndia/REST/GetNewAuthentifikationTicket
rather than:
http://isuite.c-entron.de/CentronService/REST/Login
Because you don't need the application id for the development method. You can see from the error message that you are missing the application (gu)id
The guid '61136208-742B-44E4-B00D-C32ED26775A3' is no valid application guid
Your javascript needs to be updated to use new url http://isuite.c-entron.de/CentronServiceAppleDemoIndia/GetNewAuthentifikationTicket as per the backend sode team.
Also, even if you do this, your will not be able to get reply correctly since service requires cross domain configuration entries in web.config. You have to use this reference:http://encosia.com/using-cors-to-access-asp-net-services-across-domains/ and configure server's web.config in a way so that you can call it from cross domain.