Redirect in AJAX - javascript

I am using Facebook SDK 4.0 and I have a login page in codeigniter using AJAX to send and receive requests and login users.
I would like to allow users to login using Facebook, but I'm stuck. I have a form with action to controller function named facebook_login. I have a javascript on submit of this form:
$('.facebook_login').submit(function() {
var errors = $(this).find('.errors');
var success = $(this).find('.success');
var overlay = $(this).find('.overlay');
overlay.fadeIn(300);
errors.fadeOut('fast');
success.fadeOut('fast');
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url: url, //url = path to which form should be submitted
type: 'POST', //POST = form method
dataType: 'json', //json - data type in which server is supposed to send response
data: data,
success: function(response) { //response = reply sent by server after processing our request
if (response.status == true)
{
errors.fadeOut('fast');
overlay.fadeOut('fast');
success.html(response.message).fadeIn('fast').delay(300).fadeOut(function(){
window.location =response.redirect;
});
}
else
{
success.fadeOut('fast');
overlay.fadeOut();
errors.html(response.message).fadeIn('fast');
}
},
error: function() {
overlay.fadeOut();
}
});
return false;
});
The function facebook_login does this:
session_start();
$this->load->library('facebook');
$user_logged_in = $this->facebook->logged_in();
//check if the user is already logged in with facebook
if(!$user_logged_in){
//if the user is not logged in
$loginUrl = $this->facebook->login_url();
}
I want to redirect the user to login to facebook and then gets redirected back to the website, save or session the user and display an error/successful alert using:
header('Content-Type: application/json');
echo json_encode($response);

Simply use javascript redirect.
location.href = "http://some.com/your path";

Managed by using the JS SDK with the PHP SDK thank you #luschn

Related

passing login data from ajax to php script

Here is my script in the html page:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid=$('#loginid').val();
var password=$('#password').val();
alert("loginid="+loginid);
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid:loginid,password:password},
success: function(html) {
//alert(html);
$('#status').html(html);
}
});
});
});
</script>
I am trying to get the values from the html input boxes and then passing those values to the ajax code which passes it to the php script, which then validates the login id and password and echoes a message
The php script:
<?php
require_once('dbconfig.php');
//if (isset($_POST['signin'])) {
$loginid = $_POST['loginid'];
$password = $_POST['password'];
if ($operations->login($loginid, $password)) {
header("Location:../view/admin_home.php");
} else {
echo "wrong details";
}
//}
$conn = null;
?>
html div where message should be printed:
<div id="status"></div>
When I run the code in the browser no errors are shown, but the code does not work and neither the message is displayed nor is the validation done.
My contribution:
In ajax requests I suggest you to end the php script, you can use a simple die(); for this. After this, you must to print the response, you can use numeric or string pattern to expose this like: 'success' or 'fail', also: 1 or 0.
Here is the same example with a new solution:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
var loginid = $('#loginid').val();
var password = $('#password').val();
e.preventDefault(); //for avoiding conflict with default form function
$.ajax({
type: "POST",
url: "../controller/login_check.php",
data: {loginid: loginid, password: password},
success: function(response) {
if (response == 'success') {
// if a successful response, redirect your client
window.location.href = '../view/admin_home.php';
} else {
// if login fails, put a message on screen
$('#status').html('Wrong credentials, try again.');
}
}
});
});
});
</script>
Don't forget to filter data in php, never trust in your user!
require_once('dbconfig.php');
// pre setting a response status as fail, this avoid you to use an
// else statement
$result = 'fail';
if (isset($_POST['signin'])) {
// Apply filter and sanitize data, if the loginid is an e-mail
// use the FILTER_SANITIZE_EMAIL else a simple string filter is ok.
$loginid = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
if($operations->login($loginid,$password)){
// If everything is ok, you just override the response message
$result = 'success';
}
}
// Ath the end you simply close the connection, print the response and
// stops the PHP script
$conn = null;
print(result);
die();
i solved it by preventing it from performing the default function
i used e.preventDefault() it worked but i have a new problem now
the page to which the php script tries to redirect appears on the same login page how should i solve this now??
here is a screen shot of the same
Give this a try:
<script>
$(document).ready(function(){
$('#form').on('submit',function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: "../controller/login_check.php",
data: form.serialize()
}).done(function (html) {
$('#status').html(html);
});
});
});
</script>
You must redirect with javascript, you are not actually going to the php page, you are just retrieving whatever is printed.
window.open(page,'_self')
rather than
header(...)

JAVASCRIPT: Redirecting to Homepage after successful Ajax response on localhost

I am trying to redirect to Homepage from SignIn Page after the validation of user credentials is done. The response is working perfectly fine.
On getting a successful response, I want to redirect to Homepage.
I am using Javascript for client side and PHP on server side.
I have tried all the possible solutions provided elsewhere on this site.
Here is the script for redirection on SignIn page:
$(document).ready(function(){
$("#SignInForm").submit(function(){
var em = document.getElementById("Email").value;
var ps = document.getElementById("Password").value; var obj; $.ajax({
url: 'WebService/SignIn.php',
type: 'post',
async: false,
data: {
Email: em,
Password: ps
},
dataType: 'json',
success: function(data) { var str = JSON.stringify(data); obj = JSON.parse(str);
if(obj.status == 1) {
window.location="Homepage.html";
} else { alert("Invalid Username/Password") }
},
error: function(xhr){ //alert("An error occured: " + xhr.status + " " + xhr.statusText ); alert("An error occured. Please Try Again"); }
})
}); }); </script>
A simple
window.location="Homepage.html";
should be suffice. But it isn't working.
Any help is appreciated.
window.location.href = "homepage.html" ?
The problem is related to the submit action:
By default, in fact, the submit action redirects to the url provided in the action (form parameter): https://developer.mozilla.org/en/docs/Web/API/HTMLFormElement/submit
Hence, in order to be able to perform an AJAX request, you have to first prevent the default action performed by the submit.
Just replace:
$("#SignInForm").submit(function(){
var em = document.getElementById("Email").value;
With:
$("#SignInForm").submit(function(e){ // <-- note the e
e.preventDefault();
var em = document.getElementById("Email").value;
Live example of what happens WITHOUT preventing the default action:
http://jsfiddle.net/hhjqqeza/
Live example of what happens by PREVENTING the default action:
http://jsfiddle.net/hhjqqeza/1/

Safari Extension not geting session Info

I create simple safari extension which used simple js file where i send request on my own server and check user session is set or not. In my extension code when i send Ajax call to my own server it get other information but can't get user session while user is logged in.Here is my code:
var storeUrl = window.location.href;
$(document).ready(function()
{
var store = storeUrl.replace("http://",'');
store = store.replace("/",'');
jQuery.ajax({
url: 'https://www.karmora.com/checkstore/' + store,
context: document.body,
error: function(data, transport) {
},
success: function(data) {
var storeData = jQuery.parseJSON(data);
console.info(storeData);
}
});
});

how to pass a json object from html form submit

I have a logging page and I wanted to send the logging details in json format to the checkuser.php file which is a other page in the web site.
checkUser.php file will create a new window.
What is the best way to do this ? if possible please give me some example.
$("#myform").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "blabla.com/api",
type: 'POST',
contentType: 'application/json',
data: JSON.stringify( { key: val } ) // <-------- HERE IS YOUR JSON
}).done(function() {
console.log('hooray!');
});
});
Suppose you have a login form as login.php with html form controls txtLogin and txtPassword and a Submit button. Once the user submits the form it would post data onto checkuser.php
You can write the following code that can push data in JSON format
$login = $_POST['txtLogin'];
$password = $_POST['txtPassword'];
$userArray = array('login'=>$login,'password'=>$password);
$json_array = json_encode($userArray);

Codeigniter ajax CSRF problem

I've made a simple autoload function that loads content when you scroll down on a website. However, there seems to be a few problems when i enable CSRF protection in Codeigniter.
I'm not using a form, so i don't know how i can send the token from A to B when i'm doing my post request as you scroll.
My JavaScript
if (location.href == baseurl) {
$(window).scroll(function(){
if ($(window).scrollTop() > $('body').height() / 2) {
if(doScroll == 1) {
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
$("#wrapper_content").append(data);
if(data == 'Det finnes ikke flere bilder i databasen, WTF!? Send inn forslag ASAP!') {
doScroll = 0;
}
ID++;
});
}
}
});
}
Since Codeigniter expects a TOKEN on all POST request i can't get this to work when CSRF i enabled. Any suggestions?
Error when CSRF is Enabled
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
If i turn CSRF off, everything works great...
You might like to try this code I've used. It works great:
<script type="text/javascript">
$(function(){
$('.answerlist').each(function(e){
$(this).click(function(){
var valrad = $("input[#name=answer]:checked").val();
var post_data = {
'ansid': valrad,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>online/checkanswer",
data: post_data,
success: function(msg){
/// do something
}
});
});
});
});
</script>
As others say - you have to post the CSFR token name and its value with the AJAX request parameters. Here is a simple solution to append it automatically to every AJAX request.
Here is what I put on my main view, so this code is on every page before loading the other javascript files:
<script>
var csfrData = {};
csfrData['<?php echo $this->security->get_csrf_token_name(); ?>']
= '<?php echo $this->security->get_csrf_hash(); ?>';
</script>
<!-- ... include other javascript files -->
</body>
</html>
And here is a part of a javascript file that I include on every page:
$(function() {
// Attach csfr data token
$.ajaxSetup({
data: csfrData
});
});
If you want, you can echo both the token name and the hash somewhere appropriate. Something like this.
echo $this->security->get_csrf_token_name()
and
echo $this->security->get_csrf_hash()
Or, you could use form_open() as usual and use the hidden input that is generated for you from your javascript. Disabling the CSRF-functionality is the wrong way to go.
Having reviewed my situation I believe the best option is to use CSRF but reset the token on each attempt. Otherwise the ideas expressed earlier about re-using the cookie token would allow an attacker to resubmit data hundreds of times using the same token which defeats the object of the point.
As such I have created the following function:
public function resetCSRF(){
$this->security = null;
$_COOKIE[$this->config->item('csrf_cookie_name')] = null;
load_class('Security', 'core');
$this->security->csrf_set_cookie();
return $this->security->get_csrf_hash();
}
If for example an ajax based login form fails - call this function in your PHP and then on the javascript side that receives the failure (this solution uses Jquery and a getCookie function from w3schools) would then simply call:
$('input[name="csrf_test_name"]').val(getCookie('csrf_cookie_name'));
Basically what you need to do is get the expected csrf value from the cookie (named 'ci_csrf_token' by default), then post it along with your other data.
You would need to modify this line:
$.post(baseurl + 'ajax/images',{'id' : ID}, function(data) {
to:
$.post(baseurl + 'ajax/images',{'id' : ID,'ci_csrf_token' : $.cookie('ci_csrf_token')}, function(data) {
Might need to install the cookie addon (I'm not really sure; I use mootools). Here is more information: http://aymsystems.com/ajax-csrf-protection-codeigniter-20.
Previous suggestions work great, but rather than using a variable that you can apply in every data-post, I find it simpler to use the ajax-setting to automatically apply this token to every post:
$(document).ajaxSend(function(elm, xhr, s){
if(s.data){
s.data += '&';
}
s.data += '<?php echo $this->security->get_csrf_token_name(); ?>=<?php echo $this->security->get_csrf_hash(); ?>';
});
(works with jquery-1.9.1. I'm not sure about other jquery-versions)
The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:
In your CodeIgniter Controller:
$data = array('data'=> 'data to send back to browser');
$csrf = $this->security->get_csrf_hash();
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));
$data = the data to return to the browser
$csrf = new csrf token to be used by the browser for next ajax post request
Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request
Then in your next ajax request (javascript):
var token = data.csrf;
$.ajax({
url: '/next/ajax/request/url',
type: 'POST',
data: { new_data: 'new data to send via post', csrf_token:token },
cache: false,
success: function(data, textStatus, jqXHR) {
// Get new csrf token for next ajax post
var new_csrf_token = data.csrf
//Do something with data returned from post request
},
error: function(jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
}
});
Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';

Categories

Resources