Cookie doesn't get deleted with xml callback jquery php - php

I'm not sure if somebody asked this already, at least i cant find the answer so i'm wondering what i'm doing wrong with my script.
I'm trying to delete a cookie with a callback done by Jquery that calls a php script on the background, BUT, whatever i try i cannot get this to properly work (deleting the cookie).
I've checked the php website and even looked at the RFC 2109 memo to find out how browsers and php try to accomplish that the cookie will be deleted.
So, my question here is; How can this fail?
Edit: i don't get any error message, deleting the cookie manually works and creating the cookie with the same type of callback done by jquery does also work. It just doesn't get deleted when i try the same callback with jquery to run the PHP script in the background in order to delete the cookie.
Code for that JQ callback action:
$(document).ready(function() {
var alert = $('#Cmessage');
$(".delete").on('click', function(){
$.ajax({
url: 'http://www.oostpijl.nl/shop/offerte/deletecookie.php',
type: 'get', // form submit method get/post
dataType: 'json', // request type html/json/xml
beforeSend: function() {
alert.fadeOut();
},
success: function(result) {
if(result.error){
alert.html(result.html).fadeIn();
console.log(e)
}else{
alert.html(result.html).fadeIn();
}
}
});
});
});
PHP script:
<?php
include("_offertesettings.php");
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
setcookie('offerte', '', time() - 3600, '/' , '.oostpijl.nl' );
setcookie('offerteC', '', time() - 3600, '/', '.oostpijl.nl' );
$result = array("error" => false, "html" => null);
$result["error"] = false;
$result["html"] = "<script type='text/javascript'>setTimeout(function() { window.location='" . $config["BURL"] . "'; }, 10);</script>";
} else {
$result["error"] = true;
$result["html"] = "<h3>Error; Neem contact op met de webmaster</h3>";
}
echo json_encode($result);
exit;
?>

Make sure you get inside your isset condition. You should test it by printing something as a test then exit.
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
echo json_encode('test');
exit;
}
also make sure there is no error in your included file "_offertesettings.php". You can check if there are PHP errors by adding those lines at the top of your PHP script.
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
to delete your cookies you just need this:
setcookie('offerte', '', time() - 3600);
setcookie('offerteC', '', time() - 3600);

Related

php click out logged user with ajax

good afternoon from gmt+8 timezone.
I had built a login/system , now I want to implement a function that will click out users , so i make a status column in the db ,
2 types of values , lock => lock , active => not lock.
I can use crud method to update the status and output in a table. surely i cam lock the user , and status change to lock, that is working fine, but the problem is the locked user still has access the to system , since the session still valid , she/he has to close the browser or their session is terminated.
on the login page I check if user is lock then can login.
since the user still has access when the session still valid , I want to input ajax call the server to check the status on setInterval.
on backend php: check if user is lock , terminate the session , give alerts box and redirect.
but the issue now is my code is not working, here are my ajax call , if I un-comment //console.log('success');, success will be kept in console.log , meaning the call is success.
<script>
function getUserStatus(){
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
});
}
setInterval(function(){
getUserStatus();
},3000);
</script>
on my ajax.php page , I make sure connection to db is working,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$admin_username = check_input($_POST['username']);
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clicked out');window.location.href='../index.php';</script>";
}
}
function to check user is lock
function isLocked($username){
global $connection ;
$query = "SELECT status FROM table where name = '$username' ";
$result = mysqli_query($connection,$query);
confirm($result);
while( $row = fetch_array($result)){
if($row['status'] == 'locked' ){
return true;
}else{
return false;
}
}
}
if i directly access ajax.php with the log user , below action is working .
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clickedout');window.location.href='../index.php';</script>"; }
not sure what is wrong with my codes and how to fix it ?
any assistance/suggestion would be highly appreciated .
your ajax.php echos something, that may be data, a json or in your case a js script.
The ajax calls ajax/ajax.php, if the http request succeeds it enters
success:
function(response){
//console.log('success');
}
so the variable response holds the output of that call to ajax/ajax.php. if you use
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
dataType: "script",
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
the value of "response" will be executed if it is a working script.(without tags)
further information you can find here:
http://api.jquery.com/jQuery.ajax/
without dataType: "script",in the call you could do something like that:
function(response){
//console.log('success');
$('#somediv').html(response);
}
that will insert the result in a div, if it is a well formated js script, it will be executed.

Passing of javascript variable data to php variable in the same php file

I have a javascript that needs to pass data to a php variable. I already searched on how to implement this but I cant make it work properly. Here is what I've done:
Javascript:
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "POST",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
Then on my php tag:
<?php
if(isset($_GET['subDir']))
{
$subDir = $_GET['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
I always get the fail text so there must be something wrong. I just started on php and jquery, I dont know what is wrong. Please I need your help. By the way, they are on the same file which is signage.php .Thanks in advance!
When you answer to a POST call that way, you need three things - read the data from _POST, put it there properly, and answer in JSON.
$.ajax({
type: "POST",
url: 'signage.php',
data: {
subDir: val,
}
success: function(answer)
{
alert("server said: " + answer.data);
}
});
or also:
$.post(
'signage.php',
{
subDir: val
},
function(answer){
alert("server said: " + answer.data);
}
}
Then in the response:
<?php
if (array_key_exists('subDir', $_POST)) {
$subDir = $_POST['subDir'];
$answer = array(
'data' => "You said, '{$subDir}'",
);
header("Content-Type: application/json;charset=utf-8");
print json_encode($answer);
exit();
}
Note that in the response, you have to set the Content-Type and you must send valid JSON, which normally means you have to exit immediately after sending the JSON packet in order to be sure not to send anything else. Also, the response must come as soon as possible and must not contain anything else before (not even some invisible BOM character before the
Note also that using isset is risky, because you cannot send some values that are equivalent to unset (for example the boolean false, or an empty string). If you want to check that _POST actually contains a subDir key, then use explicitly array_key_exists (for the same reason in Javascript you will sometimes use hasOwnProperty).
Finally, since you use a single file, you must consider that when opening the file the first time, _POST will be empty, so you will start with "fail" displayed! You had already begun remediating this by using _POST:
_POST means that this is an AJAX call
_GET means that this is the normal opening of signage.php
So you would do something like:
<?php // NO HTML BEFORE THIS POINT. NO OUTPUT AT ALL, ACTUALLY,
// OR $.post() WILL FAIL.
if (!empty($_POST)) {
// AJAX call. Do whatever you want, but the script must not
// get out of this if() alive.
exit(); // Ensure it doesn't.
}
// Normal _GET opening of the page (i.e. we display HTML here).
A surer way to check is verifying the XHR status of the request with an ancillary function such as:
/**
* isXHR. Answers the question, "Was I called through AJAX?".
* #return boolean
*/
function isXHR() {
$key = 'HTTP_X_REQUESTED_WITH';
return array_key_exists($key, $_SERVER)
&& ('xmlhttprequest'
== strtolower($_SERVER[$key])
)
;
}
Now you would have:
if (isXHR()) {
// Now you can use both $.post() or $.get()
exit();
}
and actually you could offload your AJAX code into another file:
if (isXHR()) {
include('signage-ajax.php');
exit();
}
You are send data using POST method and getting is using GET
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
You have used method POST in ajax so you must change to POST in php as well.
<?php
if(isset($_POST['subDir']))
{
$subDir = $_POST['subDir'];
echo($subDir);
}
else
{
echo('fail');
}?>
Edit your javascript code change POST to GET in ajax type
$(document).ready(function() {
$(".filter").click(function() {
var val = $(this).attr('data-rel');
//check value
alert($(this).attr('data-rel'));
$.ajax({
type: "GET",
url: 'signage.php',
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
});
});
when you use $_GET you have to set you data value in your url, I mean
$.ajax({
type: "POST",
url: 'signage.php?subDir=' + val,
data: "subDir=" + val,
success: function(data)
{
alert("success!");
}
});
or change your server side code from $_GET to $_POST

Wordpress Table Won't Update after AJAX / PHP (even with 200 ok response)

This is my first attempt at trying to update a database with ajax & wordpress. I am trying to set a field to a status of 'complete' when a link is clicked. Everything seems to go fine, I get a "200 ok" response from the console, and the jQuery even shows the success actions that I'm taking. However the php doesn't update the database. The proper variables are being echoed out to the console, so I know those are being set correctly. I don't know if it's my MySQL query that I'm trying or if there's something that I'm overlooking. Any help or suggestions would be greatly appreciated.
Here's my jQuery:
// Click to Complete Activity Functionality
jQuery(".complete-activity").click( function( e ) {
e.preventDefault();
nonce = jQuery(this).attr("data-nonce")
wp_user_id = jQuery(this).attr("wp_user_id")
activity_post_id = jQuery(this).attr("activity_post_id")
wp_user_id = parseInt(wp_user_id);
activity_post_id = parseInt(activity_post_id);
console.log('My wp user id is: ' + wp_user_id);
console.log('My Activity id is: ' + activity_post_id);
jQuery.ajax({
type : "post",
url : myAjax.ajaxurl,
data : {
action: "gw_complete_activity",
"wp_user_id" : wp_user_id,
"activity_post_id" : activity_post_id,
"nonce" : nonce
},
success: function(response) {
console.log('Your field has been set as completed');
jQuery('li#active-'+ activity_post_id).css('display', 'none');
}
})
}) // End click to complete activity
Here's my php code:
<?php
//Complete Activity in Database (AJAX)
add_action("wp_ajax_gw_complete_activity", "gw_complete_activity");
add_action("wp_ajax_nopriv_gw_complete_activity", "my_must_login_to_complete");
function gw_complete_activity() {
if ( !wp_verify_nonce( $_REQUEST['nonce'], "gw_complete_activity")) {
exit("No naughty business please");
}
$wp_user_id = $_REQUEST['wp_user_id'];
$activity_post_id_complete = $_REQUEST['activity_post_id'];
$date_completed = current_time('mysql', 1);
global $wpdb;
$wpdb->update (
'wp_gwactivities',
array( 'date_completed' => $date_completed, 'activity_status' => 'complete'),
array( 'wp_user_id' => $wp_user_id)
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result_add = json_encode($result_add);
echo $result_add;
}
else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
function my_must_login_to_complete() {
echo "You must be logged in to complete your activities.";
die();
}
?>
Just because you get a 200 (OK) from the requested page, doesn't mean the requested page didn't error out :) Secondly, it looks like this is going to be used in Wordpress... with that said, you can't use add_action without having wordpress loaded.
For files outside the normal wordpress install, you need to include wp-load.php include "/path/to/wordpress/wp-load.php", for example. Then you can use its functions.
After your update query ,put below code and check query in mysql directly.
print_r($wpdb->last_query);
provide your query here also if its not work.

Delay in populating session.upload_progress data

I'm trying to check the progress of files uploaded. I'm using the Kohana framework which has a Session class, but for the upload progress I'm using native PHP sessions. I'm calling session_start() in Kohana's bootstrap.php, which means session_start() will be called on every page request.
After the upload form is submitted, I wait 1 second and then begin calling a PHP file to check the upload progress using jQuery $.ajax().
The problem is that $_SESSION[$key] ($key contains the key for the upload data) isn't set on the first call to the PHP. I've tried debugging this quite a bit, and session_id() returns the correct session ID, so the session is definitely the right one and is active. I'm also waiting 1 second before checking the upload progress, so it's not a timing issue. I could fix this by continuing even if $_SESSION[$key] is not set, but the way to check if the upload is complete is when $_SESSION[$key] is unset.
The HTML form is created on-the-fly with jQuery because this is a multi-file upload. Here's the HTML for a generated form:
<form action="ajax/upload" id="form-HZbAcYFuj3" name="form-HZbAcYFuj3" method="post" enctype="multipart/form-data" target="frame-HZbAcYFuj3">
<iframe id="frame-HZbAcYFuj3" name="frame-HZbAcYFuj3"></iframe>
<input type="hidden" name="PHP_SESSION_UPLOAD_PROGRESS" value="HZbAcYFuj3">
<input type="file" id="file-HZbAcYFuj3" name="photo" accept="image/jpeg,image/pjpeg,image/png,image/gif">
<button type="button">+ Select Photo</button>
</form>
Here's the PHP that the JavaScript calls to check the progress:
public function action_uploadprogress()
{
$id = isset($_POST['id']) ? $_POST['id'] : false;
if (!$id)
throw new Kohana_HTTP_Exception_404();
$progress = 0;
$upload_progress = false;
$key = ini_get("session.upload_progress.prefix") . $id;
if (isset($_SESSION[$key]))
$upload_progress = $_SESSION[$key];
else
exit('100');
$processed = $upload_progress['bytes_processed'];
$size = $upload_progress['content_length'];
if ($processed <= 0 || $size <= 0)
throw new Kohana_HTTP_Exception_404();
else
$progress = round(($processed / $size) * 100, 2);
echo $progress;
}
Here's the jQuery ajax() request:
this.send_request = function()
{
$.ajax(
{
url: 'ajax/uploadprogress',
type: 'post',
dataType: 'html',
data: { id: _this.id },
success:
function(data, textStatus, jqXHR)
{
if (textStatus == "success")
{
if (data < 100)
setTimeout(_this.send_request, 1000);
}
}
}
);
};
You are sending a POST called 'id' to the PHP script.
However, the documentation says that the upload progress will be available only when you send a POST with same name as session.upload_progress.name configured in php.ini.
So, in other words, if your session.upload_progress.name is set to default value (PHP_SESSION_UPLOAD_PROGRESS), you have to change the following line, in send_request function:
Change:
data: { id: _this.id }
To:
data: { PHP_SESSION_UPLOAD_PROGRESS: _this.id }
You also have to change the $_POST['id'] to $_POST['PHP_SESSION_UPLOAD_PROGRESS'] or $_POST[ini_get("session.upload_progress.name")] in the PHP script (and the name of input too in case it's not default).
The upload progress will be available in the $_SESSION superglobal when an upload is in progress, and when POSTing a variable of the same name as the session.upload_progress.name INI setting is set to. When PHP detects such POST requests, it will populate an array in the $_SESSION, where the index is a concatenated value of the session.upload_progress.prefix and session.upload_progress.name INI options. The key is typically retrieved by reading these INI settings, i.e.
Source: http://php.net/manual/pt_BR/session.upload-progress.php
Lets see if I can get some of that sweet sweet bounty.. My first thought is that the $key string is not getting set properly.
Try echoing its value out and doing a print_r on the entire $_SESSION variable to keep track of things.
Now I don't see a 'success' output from action_uploadprogress() at all. I see 100 which I guess indicates done but you aren't checking for that in js. I would recommend looking into that. Might as well echo out your calculations as well. I assume its very unlikely but make sure that you are uploading files properly and are able to determine their current size without any issue.
Another issue could be with how you are handling ajax with jquery. I'm not 100% sure about this but I think the success option has been depreciated (1.5+).
From : http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
The only way I've seen success being used is like this....
$.ajax({
type: "POST",
url: '/login/spam',
data: formData,
success: function (data) {
if (data == 'value') {
//Do stuff
}
}
});
However I could be completely wrong about this....your setup might be perfectly fine. What I want you to do is get is directly in the success/done function is
alert(data);
alert(textStatus); //if you still use it
This will tell you if you are getting a proper response from your ajax query.
I will check back a few times tonight and I'll be around tomorrow to help. Tell me if anything I said helps anything.

returning php session to ajax

I am having trouble getting jQuery ajax to recognise a session. I am creating a php session from a login script, but what is happening is that when ajax loads the authenticated page, the session is always unset. For example, in the secure page, if I refresh the page, the session id changes each time. I have session_start(); in each page. Can someone please show me the correct way to handle sessions with ajax and php? I have spent 2 days and have used google so much, I will probably get an invite to there xmas lunch :-) I have included the relevant code and would be grateful for any help. Thanks
PS. If it makes any difference, I am trying to develop mobile app using jquery mobile.
login html js
$(function() {
$("#kt_login1").click(function() {
var user = $('#user').val();
var pass = $('#pass').val();
if (user == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=user]').addClass("label")
return false;
}
else if (pass == '') {
$("#login_message").html('This field cannot be empty')
$('label[for=pass]').addClass("label")
return false;
}
else $('label[for=user]').removeClass("label");
$('label[for=pass]').removeClass("label");
//alert(user + pass + ok);
data = 'user=' + user + '&pass=' + pass;
$.ajax({
type: "POST",
url: "testajax.php",
cache: false,
data: data,
success: function(data) {
if (data == 'authenticated') {
//alert(user);
document.location = 'secure.php';
}
else $('#login_message').html('You are not authorised');
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
},
error: function(xhr, ajaxOptions, thrownError) {
jAlert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
return false;
});
});
testajax.php
<?php
// test wether the user session is already set
$username = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string(md5($_POST['pass']));
mysql_connect('localhost', 'root', '');
mysql_select_db('sample');
//now validating the username and password
$sql="SELECT * FROM user_usr WHERE username_usr='$username' and password_usr='$pass'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0) {
session_start();
$_SESSION['u_name']=$row['name_usr'];
/*
echo '<pre>';
print_r( $_SESSION['u_name'] );
print_r( $_REQUEST );
echo '</pre>';
exit;
*/
echo 'authenticated';
}
else
{
echo 'Unknown User';
}
?>
+++++SOLUTION+++++
Changed form input from submit to button and voila. All ok
you have to call session_start() each time working with a session (not only when creating it)
see: http://php.net/manual/en/function.session-start.php
There are a whole load of reasons this might be the case - but you're code is upside down! This may well be the cause (or a contributory factor).
You should not treat the existence of a session as evidence of authentication (the contents of the session is another thing altogether). Call session_start() at the top of your script - not conditionally, half-way through.
As to why your session data is not available...that's an FAQ here - have a look at some of the previous answers for potential causes / how to investigate.

Categories