I am trying to create vote up in my codeigniter named "like". I use this method, that i just found in http://www.technicalkeeda.com/codeigniter-tutorials/voting-system-using-jquery-ajax-and-php-codeigniter-framework
And update is run successfully on database, But the problem is the result of like in view is not showing and the output is text from localhost "Sorry unable to update". And when i refresh the page, the result of "like" showing up.
This is the Controller:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
$data['id_vote'] = $id_vote;
redirect ('home',$data);
}
This is Model:
function updateUpVote($id_vote){
$sql = "UPDATE vote set like = like+1 WHERE id_vote =?";
$this->db->query($sql, array($id_vote));
return $this->db->affected_rows();
}
Here is the view:
<button class="btn btn-success voteme" id="3_upvote"><span id="<?php echo $data['id_vote']?>_upvote_result" ><?php echo $data['like']?></span> <b>Like</b></button>
This is javascript:
<script type="text/javascript">
$(document).ready(function(){
$(".voteme").click(function() {
var id_vote = this.id;
var upOrDown = id_vote.split('_');
$.ajax({
type: "post",
url: "http://localhost/ngelol/home/voteme",
cache: false,
data:'id_vote='+upOrDown[0] + '&upOrDown=' +upOrDown[1],
success: function(response){
try{
if(response=='true'){
var newValue = parseInt($("#"+id_vote+'_result').text()) + 1;
$("#"+id_vote+'_result').html(newValue);
}else{
alert('Sorry Unable to update..');
}
}catch(e) {
alert('Exception while request..');
}
},
error: function(){
alert('Error while request..');
}
});
});
});
How to get this result of like without refreshing page?
Many Thanks....
Update:
I have new problem guys, does anyone know how to redirect page in javascript.. I mean, to use vote we need to login first, then i replace
alert('Sorry Unable to update..');
with
url: "localhost/latihan/login"; but it didn't work... thanks for help before
Problem is in your controller function voteme after echoing status you should not use redirect, if you use redirect then it will return your home page html with true status.
So, you can use is_ajax_request(), if ajax request is true then use exit; otherwise redirect() it like,
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
echo $status;
// check for ajax request
if(! $this->input->is_ajax_request()){ // if not ajax request
$data['id_vote'] = $id_vote;
redirect ('home',$data);// redirect it
}
exit;
}
Even your referral link is not using redirect()
Try this:
function voteme(){
$id_vote= $this->input->post('id_vote');
$upOrDown= $this->input->post('upOrDown');
$status ="false";
$updateRecords = 0;
if($upOrDown=='upvote'){
$updateRecords = $this->home_model->updateUpVote($id_vote);
}
if($updateRecords>0){
$status = "true";
}
return $status
}
To redirect with javascript, you can use 'window.location.href' :
window.location.href = "localhost/latihan/login";
Related
I have a PHP login script which executes with ajax. The ajax request now starts the session in the login successfully but the window.location function doesn't work (doesn't redirect to exporter.php) in the ajax request. Below are my codes.
php Login Script
if(isset($_POST['log_name']) && isset($_POST['log_password'])) {
$username = $_POST['log_name'];
$password = $_POST['log_password'];
$sql = $db->prepare("SELECT * FROM users WHERE uname = ?");
$sql->bindParam(1, $username, SQLITE3_TEXT);
$ret = $sql->execute();
while ($row = $ret->fetchArray(SQLITE3_ASSOC))
{
$id = $row['userid'];
$regas = $row['regas'];
$uemail = $row['uemail'];
$pword = $row['pword'];
$uname = $row['uname'];
$package = $row['package'];
if (password_verify($password, $pword))
{
$_SESSION['log_id'] = $id;
$_SESSION['log_name'] = $username;
$_SESSION['regas'] = $regas;
$_SESSION['uemail'] = $uemail;
$_SESSION['package'] = $package;
//header("Location: index.php?log_id=$id");
//echo "Sigining In...";
//die("<script>window.location='exporter.php?userid={$id}';</script>");
exit();
}
else
{
echo "Information incorrect";
exit();
}
}
}
Ajax Request
$("#submit_log").click(function() {
//e.preventDefault();
username=$("#log_name").val();
password=$("#log_password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "log_name="+username+"&log_password="+password,
success: function(html){
if(html=='true') {
window.location.assign = "exporter.php";
}
else {
$(".logresult").html('Incorrect Username and Password');
}
},
beforeSend:function()
{
$(".logresult").html("Loading...")
}
});
return false;
});
Beginning part of exporter.php
session_start();
require_once ("db.php");
$db = new MyDB();
if (!isset($_SESSION['log_name']) || !isset($_SESSION['log_id']) || !isset($_SESSION['regas']))
{
header("Location: index.php");
}
What could be wrong here and how do i fix this redirecting issue please!!!.Thanks.
your php login script needs echo 'true'; according to your ajax callback.
and use location.href = "/exporter.php"; to redirect page with JavaScript
You should use like this:
window.location.href= "/exporter.php";
window.location.assign = "exporter.php";
will not work, use
window.location = "exporter.php";
You are using assign incorrectly.
window.location.assign("exporter.php")
Or you can use href instead.
window.location.href = "exporter.php";
Try using assign like this:
window.location.assign(data);
if this method not work for you let me know.
and if the Success:html is boolean then you're checking it in wrong way delete the single quotes it's not a string it is boolean datatype.
I got function that collects and display's all posts, and for each have upvote/downvote buttons.
On button click I call function called upvotePost and downvotePost.
It all works fine, but it refreshes page, I want to understand how to make it not-refresh page.
I know it's done by ajax/jquery, but don't understand how to make it.
My button example:
<a href="fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>">
Function calling:
if(isset($_GET['upvote-btn'])){
$fun->upvotePost();
}
And my function:
public function upvotePost(){
try
{
if(isset($_SESSION['user_session'])){
$user_id = $_SESSION['user_session'];
$stmt = $this->runQuery("SELECT * FROM users WHERE id=:id");
$stmt->execute(array(":id"=>$user_id));
$myRow=$stmt->fetch(PDO::FETCH_ASSOC);
}else{
$_SESSION["error"]='Sorry, You have to login in you account!';
}
$id = $_GET['image_id'];
$user_id = $myRow['id'];
$stmt2 = $this->conn->prepare("SELECT count(*) FROM fun_post_upvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt2->execute();
$result2 = $stmt2->fetchColumn();
if($result2 == 0){
$stmt3 = $this->conn->prepare("INSERT INTO fun_post_upvotes (image_id,user_id) VALUES(:image_id,:user_id)");
$stmt3->bindparam(":image_id", $id);
$stmt3->bindparam(":user_id", $user_id);
$stmt3->execute();
$stmt4 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt4->execute();
$result4 = $stmt4->fetchAll();
foreach($result4 as $post){
$newUpvotes = $post['upvotes']+1;
$stmt5 = $this->conn->prepare("UPDATE fun_posts SET upvotes=$newUpvotes WHERE id=('$id')");
$stmt5->execute();
$_SESSION["result"]='You have succesfully liked this post!';
}
}else{
$_SESSION["error"]='You have already liked this post!';
}
$stmt6 = $this->conn->prepare("SELECT count(*) FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt6->execute();
$result6 = $stmt6->fetchColumn();
if($result6 > 0){
$stmt7 = $this->conn->prepare("DELETE FROM fun_post_downvotes WHERE image_id=('$id') AND user_id=('$user_id')");
$stmt7->execute();
$stmt8 = $this->conn->prepare("SELECT * FROM fun_posts WHERE id=('$id')");
$stmt8->execute();
$result8 = $stmt8->fetchAll();
foreach($result8 as $post){
$newDownvotes = $post['downvotes'] - 1;
$stmt9 = $this->conn->prepare("UPDATE fun_posts SET downvotes=$newDownvotes WHERE id=('$id')");
$stmt9->execute();
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Ajax is the perfect answer for your question. Please check out this. you may need to alter this snippet according to your requirement.
before doing this you should import jquery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
your upvote button should be like this,
<button id="upvote"> upvote </button>
add below snippet in your javascript section.
$(function(){
$("#upvote").click(function(){
$.ajax(
{ url: "fun.php?upvote-btn=true?action=select&image_id=<?php echo $post['id'];?>",
type: "get",
success: function(result){
// todo something you need to perform after ajax call
}
});
});
});
Basically you have to create a php file which will route the call(let's call it a controller) to the intended function. Then create an ajax function which will hit that controller. Have a look at
Ajax Intro
Or look at the Jquery Implementation
I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?
<script>
$("#cart-button").click(function(){
$.ajax({
url: "includes/cart-read.php",
success: function(data){
console.log(data);
alert(data);
$('#modal-body').empty().append(''+data+'');
}
});
});
</script>
and in cart-read.php
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
$msg = $dice;
echo json_encode($msg);
}
}
session dices is an array with simple numbers. such as 4, 5, 6.
Make sure you have the following things in your code
Check if you have added session_start(); below after
Try putting an else case to your session check,
Try using an array to store and display the results.
<?php
session_start();
$result = array();
$msg = array();
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
array_push($msg,$dice);
}
if(sizeof($msg) > 0)
{
$result['status'] = true;
$result['message'] = $msg;
}
else
{
$result['status'] = false;
$result['message'] = 'No values';
}
}
else
{
$result['status'] = false;
$result['message'] = 'Session not set';
}
echo json_encode($result);
?>
Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.
I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}