I have an ajax which log in but unable to set up a php session.
How is it possible to set session by php in ajax?
I already start the session in header but when this below script runs it always show me that session is true.
<script>
$(document).ready(function() {
var loc=true;
var php_var;
// process the form
$('#loginform').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData2 = {
'email' : $('input[name=email]').val(),
'password' : $('input[name=password]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'http://example/api/v1/login', // the url where we want to POST
data : formData2, // our data object
dataType: 'json',
success: function(data){
console.log(data);
if(data.error){
//show error message here
$('#name-group').html('<p>'+data.message);
<?php $_SESSION['isloggedIn']=false;?>
}else{
//handle success part
$('#name-group').html('<p>Login Successful');
<?php $_SESSION['isloggedIn']=true;?>
}
},
error: function(jqXHR, textStatus, errorThrown){
//request error
$('#name-group').html('<p>'+textStatus.message);
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
You are mixing clientside with serverside code, the php code get executed before the user get the page in the browser, so as you did it with the api, use an ajax request to a php site on your server and set there the session. Don't forget the session_start()
.