I have a simple log-in form with C开发者_高级运维odeIgniter and jQuery. I have a couple of questions considering redirects and best practices. Here's my ajax call code:
$(document).ready(function(){
$("#btnLogin").click(function(e) {
$("p.error").hide();
var email = $("#email").val();
var password = $("#password").val();
$(".loader").show();
$.ajax({
type: "POST",
url: "/login/go",
data: ({email: email, password: password}),
success: function(data){
$(".loader").hide();
if(!data['status'])
{
$("p.error").html(data['error']);
$("p.error").slideDown("fast");
}
else
{
window.location = "site/index";
}
}
});
e.preventDefault();
});
});
As you can see, I return true or false from my controller (in data['status']) and move forward from that. However, I'm not sure if the window.location = ""
is the right way to do this. Security-wise, is it okay to put that URL there?
People cannot access site/index without having logged in first. Logging in correctly sets a CI-session and site/index checks for that. If someone is not logged in, they get redirected to the login page. I just feel a bit weird having that URL in my ajax call, haha :(
I tried to solve this by just putting redirect("site/index")
in my controller after setting the session. Some code so this makes sense:
if ($this->form_validation->run() == FALSE)
{
// validation failed, returns false
}
else
{
// successful
// sets session and then i tried doing:
redirect("site/index");
}
However, this doesn't work. I don't really understand why it doesn't work, so if someone could explain that I'd be very grateful. Thanks a lot.
As for the first part of your question:
You can always put data['my_redirect']='site/index'
in controller and return that with data['status']
, so your site structure wont be 'exposed' for others to view.
As for the second part:
Its not working because you have an Ajax request, and you cant make redirect on server before you return data to JavaScript that made that request.
cabaret - not sure if you're still having this issue, but as I was searching for it I found this and then eventually found a suitable solution, so i figured i'd post the link to what i did. i posted the code and explanation on the CI forums:
http://codeigniter.com/forums/viewthread/65486/
hope that helps
精彩评论