getting unexpected output from ajax - javascript

I am creating wishlist where I am sending data via ajax but it's not returning data as I implemented in the code I fail to figure out what is the main reason behind this. Here is the code
<li><span><i style="color:red;" class="<?php
if(isset($_SESSION['email'])){
$selwishlist = $con->prepare("SELECT * FROM wishlist WHERE user_id =:userid and product_id =:productid ");
$selwishlist->bindParam(":userid",$userid);
$selwishlist->bindParam(":productid",$id);
$selwishlist->execute();
$selresultwishlis = $selwishlist->rowCount();
if($selresultwishlis > 0){
echo "fa fa-heart";}else{
echo "ion-android-favorite-outline";
}}else{
echo "ion-android-favorite-outline";
}
?> wishlist-click" id="wishlist-product-id-<?php echo $id; ?>"></i></span>
</li>
if(isset($_SESSION['email'])){
$email = $_SESSION['email'];
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
}
else{
$email = '';
$userid = '';
}
This is my input button Where first I check if the session is running or not an then check if the item is in the user wishlist or not and according to that I change the class of wishlist icon
$(".wishlist-click").click(function(e){
e.preventDefault();
var el = $(this);
alert('I am clicked')
var ids = this.id;
var splitids = ids.split('-');
var wishlistid = splitids[3];
$.ajax({
url:'wishlistajax.php',
type:'POST',
data:{ids:wishlistid},
success:function(response){
if(response == 1){
alert('1');
}else if(response == '0'){
alert('0');
}else if(response == '3'){
alert('its 3');
}
else{
alert('Not in All');
}
}
});
});
This is my jquery code and I am getting Not in both in response AND HERE IS MY AJAX CODE
<?php
session_start();
if(isset($_SESSION['email'])){
echo "1";
exit();
if(isset($_POST['ids'])){
$email = $_SESSION['email'];
$productid = htmlspecialchars($_POST['ids']);
include "conn.php";
$userdetail = $con->prepare("SELECT * FROM user WHERE email = :email");
$userdetail->bindParam(":email",$email);
$userdetail->execute();
$userres = $userdetail->fetch();
$userid = $userres['id'];
$ip = $_SERVER['REMOTE_ADDR'];
$insertquery = $con->prepare("INSERT INTO wishlist (product_id, user_id) VALUES (:productid, :userid)");
$insertquery->bindParam(":productid",$productid);
$insertquery->bindParam(":userid",$userid);
$insertquery->execute();
echo 'Item added';
exit();
}}
else{
echo '2';
header("location:loginregister.php");
exit();
}
echo '3';
exit();
?>

Related

Submit checkbox form after calling e.preventDefault()

i just don't seem to get it right, i have tried all the methods and yet i can't get the form to submit after confirmation
It's basically a quiz system, am outputting the response whether the answer is correct or not before submitting, its showing the response but when i click on ok, its not submitting the form to take me to another question
<form id="form" method="post" action="javascript:void(0)">
<ul class="choices">
<?php while($row=$choices->fetch_assoc()): ?>
<li><input name="choice" type="radio" value="<?php echo $row['id']; ?>"/>
<?php echo $row['choice']; ?>
</li>
<?php endwhile; ?>
<input type="submit" id="submit" name="submit1" value="Gönder"/>
<input type="hidden" name="number" value="<?php echo $number; ?>"/>
</form>
and the Bootbox.js code
<script src="../../css/bootbox.min.js"></script>
<script src="../../css/bootbox.locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({ url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: [$("input[name='choice']:checked").serialize()],
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
process.php
<?php include 'database.php'; ?>
<?php session_start();
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
$_SESSION['question']=array();
$_SESSION['answer']=array();
}
//Check if form was submitted
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
$lesson = (int) $_GET['l'];
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}
}
?>
firstly do this copy this script
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
var number = $("input[name='number']");
var lesson = <?=$lesson; ?>
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({
url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: 'choice='+radioValue+'&number='+number+'&lesson='+lesson,
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
then now time is your php
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
// you didn't send any get request remove this
//$lesson = (int) $_GET['l'];
$lesson = $_POST['lesson'];
// I found mistake till here and other code it depends on your code
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}

why my $_SESSION['user_login'] not change to true?

in index.php
<?php
session_start();
$_SESSION['user_login'] = false;
}
?>
<li>
<div style="margin-left: 15px ;margin-right:15px ; text-align: center">
<?php
if (!$_SESSION['user_login']){
echo '<a href="View/login.php" class="btnprofile" style="background-image:url(./img/defaullt_profile.jpg)" ></a>';
}
else{
echo '<a href="View/profile.php" class="btnprofile" style="background-image:url(coba.jpg)" ></a>';
}
?>
</div>
</li>
in login.php
just see when the $cekrole == 'member'
<?php
include_once '../Dao/UserDaoImpl.php';
include_once '../Entity/USER.php';
include_once '../util/PDOUTIL.php';
session_start();
$loginPressed = filter_input(INPUT_POST, 'btnLogin');
if (isset($loginPressed)) {
$userDao = new UserDaoImpl();
$username = filter_input(INPUT_POST, 'txtUsername');
$password = filter_input(INPUT_POST, 'txtPassword');
$md5Password = md5($password);
$userLogin = new User();
$userLogin->setUsername($username);
$userLogin->setPassword($md5Password);
/* #var $arrResult User */
$arrResult = $userDao->login($userLogin);
$longname = $arrResult['longname'];
$email = $arrResult['email'];
$gender = $arrResult['gender'];
$dateofbirth = $arrResult['dateofbirth'];
$cekrole = $arrResult['role'];
$profile = $arrResult['profile'];
if (isset($arrResult) && !empty($arrResult['name'])) {
if ($cekrole == 'admin') {
$_SESSION['user_login'] = TRUE;
$_SESSION['user_name'] = $arrResult['username'];
header('location:homeadmin.php');
} elseif ($cekrole == 'employee') {
$_SESSION['user_login'] = TRUE;
$_SESSION['user_name'] = $arrResult['username'];
$_SESSION['namauser'] = $username;
header('location:homeemployee.php');
} elseif ($cekrole == 'member') {
$_SESSION['user_login'] = TRUE;
$_SESSION['user_name'] = $arrResult['username'];
$_SESSION['profile'] = $profile;
$_SESSION['longname'] = $longname;
$_SESSION['email'] = $email;
$_SESSION['dateofbirth'] = $dateofbirth;
$_SESSION['gender'] = $gender;
header('location:../index.php');
}
}
else{
$message = 'Id atau Password salah';
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>
can someone help me :( , see the login.php and just see when role == member
why when the login is true and set session['user_login'] = TRUE and header to index.php, but the session['user_login'] in index.php still FALSE
sory my english so bad :D
<?php
session_start();
if (!isset($_SESSION['user_login'])) { //if session doesn't exist, set user_login to false
$_SESSION['user_login'] = false;
}
?>
So when session doesn't exist yet, or user isn't logged then $_SESSION['user_login'] = false else $_SESSION['user_login'] is true and you can continue your workflow.

Getting Undefined index when making a session

Hi I'm trying to make a session in my main page but its just giving me an error of undefined index in uniqueID line 5.
The connection between my webqr.js and server.php have no errors but when I tried to connect it to my wow.php it gives me an error of undefined index.
webqr.js Code
function read(a){
var html=htmlEntities(a);
var audio = new Audio('lib/beep.ogg');
audio.play();
var uniqueID = document.getElementById("mapo").innerHTML= html;
window.location.href = "http://localhost/QR_JEFF/server.php?uniqueID=" + uniqueID; }
server.php Code
session_start();
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
wow.php Code
<?php include('server.php');?>
<?php if (isset($_SESSION['unique_id'])) : ?>
Welcome User:
<input type="text" value="<?php echo $_SESSION['unique_id']; ?>" disabled>
<?php endif ?>
Now I'm receiving this error.
okay so this solve my own question.
session_start();
if(isset($_GET['uniqueID'])){
$uniqueID = " ";
$db = mysqli_connect('localhost', 'root','','suffrage');
$uniqueID = $_GET['uniqueID'];
$query = "SELECT * FROM applicant_table WHERE unique_id='$uniqueID'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if($logged_in_user['validation_status'] == 'Verified' && $logged_in_user['voting_status'] == 'No'){
$_SESSION['unique_id'] = $uniqueID;
$_SESSION['validation_status'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: wow.php');
}
}
}
I put my code in another if statement.

how to add characters to the end of the value if it already exists?

Here when I click post button it inserts a random value on database.
If a value already exists on database then show error. It works fine.
But I want to add 2/3 characters at the end of value if it already exists on database. If $check == 1 then I want to add some characters at the end of the value instead of showing alert. How to do this?
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
// if $check==1 then i want to add 2 characters at the end of $slug .
if($check == 1)
{
// instead of showing alert i want to add 2 more characters at the end of that value and and insert it on database
echo "<script> alert('something is wrong') </script> ";
exit ();
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>
<form method="POST" >
<?php
$result = "";
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chararray = str_split($chars);
for($i = 0; $i < 7 ; $i++)
{
$randitem = array_rand($chararray);
$result .= "".$chararray[$randitem];
}
echo $result ;
?>
<input type="hidden" value="<?php echo $result;?>" name="rand" />
<span class="input-group-btn">
<button class="btn btn-info" type="submit" name="submit">POST</button>
</span>
</form>
just run update query if $check == 1
if($check == 1){
$newSlug = $slug."xy";
$update = "update slug set post_slug = '".$newSlug."' where post_slug = '".$slug."'";
$run = mysqli_query($con,$update );
echo "<script> alert('Updated Successfully') </script> ";
exit ();
}
This is helpful for you
<?php
$con = mysqli_connect("localhost","root","","post" ) or die
( "unable to connect to internet");
if(isset($_POST['submit'])){
$tmp_slug = $_POST['rand'];
$slug = $_POST['rand'];
while(check_exiest($tmp_slug))
{
$tmp_rand = rand(11,99);
$tmp_slug = $slug.$tmp_rand;
}
$insert ="insert into slug (post_slug) values ('$tmp_slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
public function check_exiest($slug)
{
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check >= 1)
{
return true;
}
else
{
return false;
}
}
?>
Just few modification in your code to insert new value.
<?php
$con = mysqli_connect("localhost","root","","post") or die("unable to connect to internet");
if(isset($_POST['submit']))
{
$slug = $_POST['rand'];
$get_slug = "select * from slug where post_slug='$slug' ";
$run_slug = mysqli_query($con,$get_slug );
$check = mysqli_num_rows($run_slug );
if($check == 1)
{
$slug_new = $slug.'ab'; // Add 2 characters at the end
$update ="UPDATE slug SET post_slug = '$slug_new' WHERE post_slug = '$slug'";
$run = mysqli_query($con,$update);
}
else
{
$insert ="insert into slug (post_slug) values ('$slug') ";
$run = mysqli_query($con,$insert);
if($run)
{
echo "<p style='float:right;'> Posted successfully </p>";
}
}
}
?>

Update data through checkbox using jquery

I can't get this to work. I need to update the value of a column of the checked checkboxes in mysql. When I click the button it is supposed to update the value of the checked checkboxes. Here is my code for editLayout.php:
<form action="updateLayout.php" method="POST">
<input name="update" type="SUBMIT" value="Update" id="update">
<?php
$x = 'seats';
$linkID = # mysql_connect("localhost", "root", "Newpass123#") or die("Could not connect to MySQL server");
# mysql_select_db("seatmapping") or die("Could not select database");
/* Create and execute query. */
$query = "SELECT * from $x order by rowId, columnId desc";
$result = mysql_query($query);
$prevRowId = null;
$seatColor = null;
$tableRow = false;
//echo $result;
echo "<table class='map'>";
while (list($rowId, $columnId, $status, $name, $seatid) = mysql_fetch_row($result))
{
if ($prevRowId != $rowId) {
if ($rowId != 'A') {
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table><tr>";
} else {
$tableRow = false;
}
if ($status == 0) {
$seatColor = "#A6E22E";
}
else if ($status == 1){
$seatColor = "#D34836";
}
else if ($status == 2){
$seatColor = "#00A0D1";
}
echo "\n<td bgcolor='$seatColor'>";
echo $seatid;
echo "<input type='checkbox' name='seats[]' id='seats' value=".$seatid."> </checkbox>";
echo "</td>";
}
echo "</tr></table></td>";
echo "</tr>";
echo "</form>";
echo "</table>";
/* Close connection to database server. */
mysql_close();
?>
And here is my code for the jquery residing on different page (functions.js). I already included this in the header:
jQuery(function($) {
$("form input[id='update']").click(function() {
var count_checked = $("[name='seats[]']:checked").length;
if(count_checked == 0) {
alert("Please select product(s) to update.");
return false;
}
if(count_checked == 1) {
return confirm("Are you sure you want to update these product?");
} else {
return confirm("Are you sure you want to update these products?");
}
});
});
And here is my updateLayout.php.:
<?php
$db = mysql_connect("localhost", "root", "Newpass123#");
if(!$db) { echo mysql_error(); }
$select_db = mysql_select_db("seatmapping");
if(!$select_db) { echo mysql_error(); }
if(isset($_POST['update'])) {
$id_array = $_POST['seats'];
$id_count = count($_POST['seats']);
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
header("Location: editLayout.php");
}
?>
I'm using jquery 1.11.0. I know there's a lot of sql injection in here and im still using mysql but I plan to change it all once I get this to work. Any kind of help is appreciated.
Thanks in advance.
Your update query doesn't use the correct update value. You use '$seatid', which isn't declared anywhere. You should use '$id'.
Change
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$seatid'");
if(!$query) { die(mysql_error()); }
}
into
for($i=0; $i < $id_count; $i++) {
$id = $id_array[$i];
$query = mysql_query("Update `seats` set `status`='2' where `seatid`='$id'");
if(!$query) { die(mysql_error()); }
}

Categories