i want to logout on clicking this button
html input
<input type="button" value="logout" id="top-btn-logout" onclick="test()">
my js file
function test()
{
$("#top-btn-logout").click(function() {
$.ajax({
url: 'http://localhost/New%20folder/vigcheck.php?action=logout',
success: function(data){
alert(data);
//location.reload();
//window.location.href = data;
}
});
});
}
check.php file.
<?php
if(isset($_GET['action']) == "logout" ){
//$_SESSION = array();
session_destroy();
session_unset();
echo "logout";exit;
}?>
First use a proper get request using jquery ajax try
$.ajax({
url: 'http://localhost/New%20folder/vigcheck.php',
type: 'get',
data:{action:'logout'},
success: function(data){
alert(data);
//location.reload();
//window.location.href = data;
}
});
then check.php file. (you are combining conditions to check use both conditions separate)
<?php
if(isset($_GET['action']) && $_GET['action'] == "logout" ){
//$_SESSION = array();
session_destroy();
session_unset();
echo "logout";exit;
}?>
if(isset($_GET['action']) == "logout" ){
This is incorrect because isset will return true and true != 'logout' so make it as
if(isset($_GET['action'])){
if($_GET['action']=="logout";
//do whatever you wanna do
}
You need to check for returned data from check.php file on success of ajax request . After that redirect the user to your login page.
Try this it will work :
JS File :
function test()
{
$("#top-btn-logout").click(function() {
$.ajax({
url: 'http://localhost/New%20folder/vigcheck.php?action=logout',
success: function(data){
alert(data);
//location.reload();
//window.location.href = data;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
if (XMLHttpRequest.status === 401) {
location.href = 'index.php';
}
}
});
});
}
check.php :
<?php
if(isset($_GET['action']) == "logout" ){
header("HTTP/1.1 401 Unauthorized");
}
?>
Related
I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.
The div:
<div id="result"></div>
Ajax:
$(document).ready(function() {
$('#submit').click(function() {
$.ajax
({
type:'post',
cache: false,
url:'save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
});
save.php:
<?php
$co= 'aaa';
if(!empty($_POST['tosave']))
{
if($_POST['tosave'] == $co)
{
$foo = fopen("plik.txt","a+");
flock($foo, 2);
fwrite($foo,$_POST['tosave']."\r\n");
flock($foo ,3);
fclose($foo);
echo "success";
exit();
} else {
echo 'bad';
exit;
}
} else {
echo "empty";
exit;
}
?>
This might be because you don't prevent the default behavior on the submit button which is to send the form's data to the specified link, maybe in your case the link is on the same page than your PHP leading to only see the message in the div for a split second before the page reloads itself.
So to prevent this default behavior, you have to catch the event and use the preventDefault() function like so :
$('#submit').click(function(event) { //we pass the event as an attribute
event.preventDefault(); //we prevent its default behavior so we can do our own stuff below
$.ajax
({
type:'post',
cache: false,
url:'save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
});
First of all there is a mistake in your Ajax call code you have write your submit.click() submit function under document.ready().remove document.ready() because submit.click()will run when you submit the form. Second thing is you should add
event.preventDefault() to prevent the default behabiour of your submit form otherwise it will display for short time and then it will disappeared.See my code below it is working.
AJAX WITH HTML FORM:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="action">
<input type="text" name="tosave" value="bbb">
<button type="submit">clickme</button>>
</form>
<div id="result"></div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script type="text/javascript">
$("#action").click(function(event) {
event.preventDefault();//TO PREVENT THE DEFAULT BEHAVIOUR OF FORM
$.ajax
({
type:'post',
cache: false,
url:'https:save.php',
data: $("#action").serialize(),
dataType: "html",
success: function(response) {
if(response == 'success')
{
alert('success');
}
if(response == 'empty')
{
alert('empty');
}
if(response == 'bad')
{
$("#result").html(response);
}
}
});
});
</script>
PHP:
<?php
$co = 'aaa';
if (!empty($_POST['tosave'])) {
if ($_POST['tosave'] == $co) {
$foo = fopen("plik.txt", "a+");
flock($foo, 2);
fwrite($foo, $_POST['tosave'] . "\r\n");
flock($foo, 3);
fclose($foo);
echo "success";
exit();
} else {
echo 'bad';
exit;
}
} else {
echo "empty";
exit;
}
?>
**OUTPUT DISPLAY IN DIV: bad**
I have send query ajax request to server. The server response in two variable that is errmsg or successmsg . so how can i understand response is whether errmsg or successmsg. More code explain below
script.js
$.ajax({
url:"abc.php",
method:"POST",
data:$('#form').serialize(),
success:function(data){
?????????
}
error:function(data){
.......
}
});
abc.php
<?php
if (condition) {
$successmsg = hello;
echo "$successmsg";
}
elseif (condition) {
$errmsg = Error Occured;
echo "$errmsg";
}
elseif (condition) {
$successmsg = welcome;
echo "$successmsg";
}
else {
$errmsg = Bye;
echo "$errmsg";
}
?>
return error or success depending on what you are doing with your code in php for example
return iferror ? ['errmsg' = 'Error'] : ['successmsg'=>'success'];
then get your response in ajax like
$.ajax({
url : 'your-url,
data : {your - data},
success: function(response){
if(response.successmsg){
console.log(response.successmsg);
}
else{
console.log(response.errmsg);
},
error: function(response){
console.log(response);
}
});
You can return the server's response using this code:
<?php
if ($textvar > 500){
echo 'SUCCESS';
}else{
echo 'ERROR';
}
?>
Then the Ajax code can be:
$.ajax({
cache: false,
url: '/js/checkmsgs.php',
success: function(res){ // This will be applied if the php code is completlly done without any programming mistakes.
if (res == 'SUCCESS'){
alert('Success');
}else{
alert('Error !');
}
},
error: function(){ // this one will be applied if the php code have a mistake !
alert('eeeeeerrror');
}
});
i have try ajax success and error. but its not working on my login form. but its work on my insert, update or delete php.
here my ajax code :
$('#login').submit(function() {
$.ajax({
type: 'POST',
url: 'resto_proses_login.php',
data: $(this).serialize(),
dataType: 'json',
success: function(status) {
alert("success");
},
error: function(){
alert("error");
}
})
return false;
});
and this is my resto_proses_login.php
<?php
session_start();
include 'connect.php';
$query = mysql_query("SELECT * FROM tb WHERE user='$_POST[user]' AND pass='$_POST[pass]'");
if(mysql_num_rows($query) == 1)
{
$return_arr=array();
$row_array['status']='sukses';
array_push($return_arr,$row_array);
echo json_encode($return_arr);
$data = mysql_fetch_array($query);
$_SESSION['access']=$data['access'];
$_SESSION['nama']=$data['nama'];
} if($_SESSION['access']== "ADMIN" ) { header('location: admin/');
} elseif ($_SESSION['access']== "KASIR") { header('location: kasir/');
} elseif ($_SESSION['access']== "DAPUR") { header('location: dapur/');
} elseif ($_SESSION['access']== "PELAYAN") { header('location: pelayan/');
} else { echo "failed"; }
?>
if im not use ajax, this process have error with code. that error will show number line : undefined index: access. if it success. no error showing.
my question is if use ajax. it just show alert("error"); although I input the correct data
I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});
Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.
Actually I'm trying to redirect to the index after logging in with ajax button
but what is happening is strange , header is not taking me to the index.php !
i just get the HTML code of the index.php in my login.php page !!
I'm using Smarty to separate the html from php code , and I don't know how to fix the problem !
click the login and get the HTML of the index in login page !
why ?
in login.php page
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
the ajax function :
function ajax3(Div_Submit,Div_Response,SuccessScript,Data_Submit)
{
var Type = 1;
var Aj_type = "POST";
var post_data = '';
if(!Data_Submit)
post_data = $('#'+Div_Submit+' *').serialize();
else
post_data = Data_Submit;
$.ajax({
type: Aj_type,
url: document.URL,
data: post_data,
dataType: "text",
beforeSend: function(xhr)
{
$.blockUI({ message: '<img src="images/loading.gif" />',
css: { border: 'none', backgroundColor: 'transparent' } });
xhr.setRequestHeader("Ajax-Request", "true");
},
success: function(response) {
$('#'+Div_Response).html(response+'<script>'+SuccessScript+'</script>');
},
complete: function(){
$.unblockUI();
}
});
return false;
}
the html button call :
<div class="buttons" >
<a class="positive" onclick="$('#login_action').val('login');ajax3('login_form','login_form','','')">
<img src="images/checkbox_checked.png" alt=""/>
<font size="3px"> login </font>
</a>
</div>
That wouldn't work as what you expected.
It should be something like this.
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo "success";
}
On your javascript/jquery file.
have something like this
jQuery.ajax({
url: "login.php",
success:function(data){
if(data == "success") window.location = "index.php";
}
});
With AJAX, this is the expected output. What happens is that the AJAX request itself is being redirected to index.php, which I what is then outputted and returned to that request.
If you want to redirect to index.php from AJAX, you would need to exit with a specific code, or a JSON-encoded value and catch that in the AJAX result itself.
Example:
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo json_encode(array('redirect' => 'index.php'));
exit;
}
JavaScript:
$.ajax(
url: 'your-url',
success: function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}
);
u can get success response whenever login credentials are appropriate , at that moment change the window location using javascript or jquery..