i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.
Related
I don't know why my success function isn't working. I mean although it passes the JSON data to the PHP file and changes the password.
// this is the id of the form
$("#password_form").submit(function(e) {
e.preventDefault();
$(".verify-user-loader").addClass("force-display-block");
password = $("input#password-reset").val();
url = 'reset-pass.php';
$.ajax({
type : 'POST',
url : url,
dataType : 'json',
data : {
cardnumber: <?php echo '\''.$cardnumber.'\''; ?>,
act_token: <?php echo '\''.$activationToken.'\''; ?>,
password: password
},
success : function(success){
alert("success");
},
error : function(request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
});
This file works as expected, it changes the password using the POST data
reset-pass.php
include_once '/../login/user.class.php';
$activationToken = $_POST['act_token'];
$cardnumber = $_POST['cardnumber'];
$password = $_POST['password'];
$user = new User();
$verifyToken = $user->verifyToken( $activationToken, $cardnumber );
if ($verifyToken['status'] === true) {
$tokenStatus = "inactive";
$user->signUp( $cardnumber, $password );
$user->changeTokenStatus( $cardnumber, $tokenStatus );
$success = true;
return $success;
}else{
print_r($verifyToken);
}
You should use echo instead of return, because when you work without function you should need to use echo.
So the code will be
echo true; // or you can write echo $success = true;
exit(); // exit is use to stop further processing of code.
1 ) you need to echo $success; instead of return $success;
Ajax response should be any browser out put (i.e like html or echo or print_r these are browser output ) . instead of return .
2) simple add data like this
........
data : {
cardnumber: '<?php echo $cardnumber; ?>',
act_token: '<?php echo $activationToken; ?>',
password: password
},
........
My site works like this:
User has a balance stored in a database under column named currency. He earns currency then after earning enough he goes to another page to get accounts in exchange of these currencies. I set up everything but something is bugging me since an hour. If user has enough currencies and he retrieve an account, he can refresh and retrieve another account and even though he doesn't have enough currencies my system is still giving him his account on firefox but not on chrome (There are the browser I have tested until now) I'm handling this with session, ajax, and php to handle the delivery and here is the codes:
1. In the file below: I check how much the user has currencies and assign an ability session which will then be checked when retrieving the accounts. User can either get an account with currency amount of 250 or 1000 or 2500 and I am checking how much currency he can have on account:
<?php session_start();
unset($_SESSION["ability"]);
$unames = $_SESSION['username'];
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database-name", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyamount = $row['currency'];
}
if ($currencyamount<250){
$_SESSION["ability"]= 'zero';
echo $_SESSION["ability"];
}
elseif ($currencyamount<1000) {
$_SESSION["ability"]= 'one';
echo $_SESSION["ability"];
}
elseif ($currencyamount<2500) {
$_SESSION["ability"]= 'two';
echo $_SESSION["ability"];
}
else {
$_SESSION["ability"]= 'three';
echo $_SESSION["ability"];
}
?>
I then have the jquery file listening to this php file, for its echos, which will if the user has an ability of 1 allow him to get an account with 250 currencies, if he has an ability of 2: 1000 currencies, if he has an ability of 3: 2500 currencies. If he has ability 0, he won't get any account if he tries, it alerts him to refresh and if he tries to get two accounts or more without refreshing (Did this because I wanted to unset the session when the page loads again then set them because the abilities may change) The script also deletes each account the user got from the database.
$(document).ready(function () {
var ability = 'zero';
var click = 0;
$.ajax({url: "ability.php"}).done(function( html ) {
ability = html
});
$('#currency2500').click(function(){
if (click==0){
if (ability != 'zero') {
function show_account() {
$.ajax({
type: "POST",
url: "select1.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency250').click(function(){
if(click==0){
if (ability != 'zero') {
var id=$(this).data("id3");
$.ajax({
url:"delete1.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == 'zero') {
alert("You dont have the required amount of currencies.");
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
function show_account() {
$.ajax({
type: "POST",
url: "select2.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency1000').click(function(){
if(click==0){
if (ability != 'zero' && ability != 'one') {
var id=$(this).data("id3");
$.ajax({
url:"delete2.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability == "zero" || ability == "one") {
alert("You dont have the required amount of currencies.");
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
function show_account() {
$.ajax({
type: "POST",
url: "select3.php",
data:{action:"showroom"},
success: function (data) {
$('#accountinfo').html(data);
}
});
}
show_account();
click = click + 1;
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
} else {
alert('Refresh the page');
}
});
$('#currency2500').click(function(){
if(click==0){
if (ability == 'three'){
var id=$(this).data("id3");
$.ajax({
url:"delete3.php",
method:"POST",
data:{id:id},
dataType:"text",
success:function(data){
show_account();
}
});
}
} else if(ability != 'three') {
alert("You dont have the required amount of currencies.");
}
});
});
Here is the php file that will deliver the account with 250 currencies to the user, there is also the ones which are the same for 1000, 2500 and with just the value 250 changed. if its called by jquery:
<?php
session_start();
$link = mysqli_connect( 'localhost', 'database-username', 'database-password', 'database' );
$action=$_POST["action"];
if($action=="showroom") {
$query="SELECT * FROM tablename LIMIT 1";
$show = mysqli_query($link, $query) or die("Error");
echo "<p id='paragraph' style='font-size:22px;font-weight: bold;'>Here is your 250 currencies account:</p>";
echo "<table style='position:relative;bottom:30px;' border='2px'><tr><td>Email</td><td>id</td></tr>";
while ($row = mysqli_fetch_array($show)) {
echo "<tr><td>" . $row['email'] . "</td><td>" . $row['id'] . "</td></tr>";
}
echo "</table>";
$unames = $_SESSION['username'];
$query2 = "UPDATE users SET currency=currency-250 WHERE username='$unames'";
$update = mysqli_query($link, $query2);
$link = mysql_connect( "localhost", "database-username", "database-password");
mysql_select_db("database", $link);
$currencyquery = mysql_query("SELECT currency FROM users WHERE username = '$unames'", $link);
while ($row = mysql_fetch_array($currencyquery)) {
$currencyvalue = $row['currency'];
}
unset($_SESSION['currencynumber']);
$_SESSION["currencynumber"]=strval($currencyvalue);
}
?>
Then the page which users gets in: ( Only a part from it )
<?PHP
session_start();
if( !isset($_SESSION['username']) ) {
header ("Location: login.html");
}
<div id="accountinfo"></div>
<input type="button" id="currency2500" value="Get 2500 currencies" />
<input type="button" id="currency1000" value="Get 1000 currencies" />
<input type="button" id="currency250" value="Get 250 currencies" />
So: If using firefox: I can refresh 2-4 times until i can't get accounts anymore and my balance will be negative after getting those accounts. Maybe there is a way that if the balance gets negative to cancel the operation and not show anything to the user? Or how can it be solved? I am using sessions to track.
There are many posts that are made by users, I want each post (or div in this case) to display the background color green or grey depending on the user status (logged in or not).
What I am trying to achieve is while idling on the page, you should see a user going online without refreshing the page
status.php
if (logged_in() === true){
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
echo "online";
}
}
}
}else {
echo "offline";
}
Main page
$res8 = mysql_query("SELECT * FROM `users` WHERE user_id='".$user_id."' LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
?>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
datatype:"application/json",
type: 'GET',
success: function(data) {
if (data === "online") {
$('.status').css({background: '#40A547'});
} else {
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 5000);
});
</script>
<?php
}
}
}
echo '<div class="status">TEST</div></a></div>';
This code changes the background color of all the divs but I want it to only target the divs that correspond to the user that logged in (the creator of the post).
Not sure how to make the div have the dynamic styling using ajax.
Any help is much appreciated!
You can use the id user from the database to achieve this. Then add an id to the div corresponding to the user id. For instance :
Ajax Request in success :
$('.status #user'+ dataId).css({background: '#7f8c8d'});
In your HTML :
echo '<div class="status" id="user1">TEST</div></a></div>';
Edit
Your Main page (your AJAX request)
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.message === "online")
{
$('.status #user'+ data.userId).css({background: '#40A547'});
} else // data.message === "offline"
{
$('.status #user'+ data.userId).css({background: '#7f8c8d'});
}
}
});
//...
// HTML looks like...
echo '<div class="status" id="user1">TEST</div></a></div>';
echo '<div class="status" id="user2">TEST2</div></a></div>';
status.php
You set the dataType of your ajax request that you want return Json but it's unclea, your your status.php add the header content-type to json.
<?php
header('Content-Type: application/json'); // So add this
//...
$array = array(); // New variable which would be return as json
if (logged_in() === true) // Your online part
{
$res8 = mysql_query("SELECT * FROM `users` WHERE status=1 LIMIT 1");
if(mysql_num_rows($res8) > 0){
while($row8 = mysql_fetch_assoc($res8)){
if ($row8['status'] === "1") {
$array['message'] = 'online';
$array['userId'] = $row8['user_id']; // Here is the userId (adapt following your code)
}
}
}
}// Your offline part
else {
$array['message'] = 'offline';
}
echo json_encode($array);
I cannot get this script work. I try to warn if login that user entered is available. But I cannot manage this script to work:
$( "#myRegForm" ).submit(function( event ) {
var errors = false;
var userAvi = true;
var loginInput = $('#login').val();
if( loginInput == ""){
$("#errorArea").text('LOGIN CANNOT BE EMPTY!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if(loginInput.length < 5 ){
$("#errorArea").text('LOGIN MUST BE AT LEAST 5 CHARACTERS!');
$("#errorArea").fadeOut('15000', function() { });
$("#errorArea").fadeIn('15000', function() { });
errors = true;
}
else if (loginInput.length >=5) {
$.post('checkLogin.php', {login2: loginInput}, function(result) {
if(result == "0") {
alert("this");
}
else {
alert("that");
}
});
}
if (errors==true) {
return false;
}
});
Everything works fine until loginInput.length >=5 else block. So I assume there is a problem with getting answer from PHP file, but I cannot handle it, though I tried many different ways. Here is checkLogin.php's file (note that jQuery script and PHP file are in the same folder):
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}
else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
<?php
include ("bd.php");
$login2 = mysql_real_escape_string($_POST['login2']);
$result = mysql_query("SELECT login FROM users WHERE login='$login2'");
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo "0"; // for you to use if(if(result == "0") you should send a string
} else {
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo "1";
}
?>
You're literally sending the string 'loginInput'.
change
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) {
to
$.post('checkLogin.php', {login2: loginInput}, function(result) {
Edit
I would just comment out everything except the following for now and see if that at least works
$.post('checkLogin.php', {login2: 'loginInput'}, function(result) { // put loginInput back in quotes
alert('#'+result+'#'); // # to check for whitespace
});
The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}