Submit checkbox form after calling e.preventDefault() - javascript

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']);
}

Related

getting unexpected output from ajax

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();
?>

Why is this AJAX call not working in IE 11?

I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>

See Events in calendar, using PHP and Javascript,

In this matter, I have a problem when site is online(live), it works very good locally but when online (live) does not show events
<script type="text/JavaScript" language="JavaScript">
events = new Array(
<? php
$get_event = $db - > Execute("SELECT * FROM events WHERE fromdate>= date(now()) and removed='N'");
// $get_event=$db->Execute("SELECT * FROM events WHERE fromdate>='".$_SESSION['session_start_date_s_front']."' and removed='N'");
$ttl_event = $get_event - > RecordCount();
$gp = 1;
while (!$get_event - > EOF) {
$xx = dates_range($get_event - > fields['fromdate'], $get_event - > fields['todate']);
$ttl_dte = count($xx) - 1;
for ($i = 0; $i < count($xx); $i++) {
$d_e = explode('-', $xx[$i]);
if ($gp == $ttl_event && $i == $ttl_dte) { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""] <? php
} else { ?> ["D", "<?php echo $d_e[1]?>", "<?php echo $d_e[2]?>", "<?php echo $d_e[0]?>", "1:00 AM", "12:59 PM", "<?php echo addslashes($get_event->fields['event'])?>", ""], <? php
}
}
$gp++;
$get_event - > MoveNext();
}
?>
Create a Database Table
CREATE TABLE `events` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`date` date NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active, 0=Block',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*
* Function requested by Ajax
*/
if(isset($_POST['func']) && !empty($_POST['func'])){
switch($_POST['func']){
case 'getCalender':
getCalender($_POST['year'],$_POST['month']);
break;
case 'getEvents':
getEvents($_POST['date']);
break;
default:
break;
}
}
/*
* Get calendar full HTML
*/
function getCalender($year = '',$month = '')
{
$dateYear = ($year != '')?$year:date("Y");
$dateMonth = ($month != '')?$month:date("m");
$date = $dateYear.'-'.$dateMonth.'-01';
$currentMonthFirstDay = date("N",strtotime($date));
$totalDaysOfMonth = cal_days_in_month(CAL_GREGORIAN,$dateMonth,$dateYear);
$totalDaysOfMonthDisplay = ($currentMonthFirstDay == 7)?($totalDaysOfMonth):($totalDaysOfMonth + $currentMonthFirstDay);
$boxDisplay = ($totalDaysOfMonthDisplay <= 35)?35:42;
?>
<div id="calender_section">
<h2>
<<
<select name="month_dropdown" class="month_dropdown dropdown"><?php echo getAllMonths($dateMonth); ?></select>
<select name="year_dropdown" class="year_dropdown dropdown"><?php echo getYearList($dateYear); ?></select>
>>
</h2>
<div id="event_list" class="none"></div>
<div id="calender_section_top">
<ul>
<li>Sun</li>
<li>Mon</li>
<li>Tue</li>
<li>Wed</li>
<li>Thu</li>
<li>Fri</li>
<li>Sat</li>
</ul>
</div>
<div id="calender_section_bot">
<ul>
<?php
$dayCount = 1;
for($cb=1;$cb<=$boxDisplay;$cb++){
if(($cb >= $currentMonthFirstDay+1 || $currentMonthFirstDay == 7) && $cb <= ($totalDaysOfMonthDisplay)){
//Current date
$currentDate = $dateYear.'-'.$dateMonth.'-'.$dayCount;
$eventNum = 0;
//Include db configuration file
include 'dbConfig.php';
//Get number of events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$currentDate."' AND status = 1");
$eventNum = $result->num_rows;
//Define date cell color
if(strtotime($currentDate) == strtotime(date("Y-m-d"))){
echo '<li date="'.$currentDate.'" class="grey date_cell">';
}elseif($eventNum > 0){
echo '<li date="'.$currentDate.'" class="light_sky date_cell">';
}else{
echo '<li date="'.$currentDate.'" class="date_cell">';
}
//Date cell
echo '<span>';
echo $dayCount;
echo '</span>';
//Hover event popup
echo '<div id="date_popup_'.$currentDate.'" class="date_popup_wrap none">';
echo '<div class="date_window">';
echo '<div class="popup_event">Events ('.$eventNum.')</div>';
echo ($eventNum > 0)?'view events':'';
echo '</div></div>';
echo '</li>';
$dayCount++;
?>
<?php }else{ ?>
<li><span> </span></li>
<?php } } ?>
</ul>
</div>
</div>
<script type="text/javascript">
function getCalendar(target_div,year,month){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getCalender&year='+year+'&month='+month,
success:function(html){
$('#'+target_div).html(html);
}
});
}
function getEvents(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=getEvents&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
function addEvent(date){
$.ajax({
type:'POST',
url:'functions.php',
data:'func=addEvent&date='+date,
success:function(html){
$('#event_list').html(html);
$('#event_list').slideDown('slow');
}
});
}
$(document).ready(function(){
$('.date_cell').mouseenter(function(){
date = $(this).attr('date');
$(".date_popup_wrap").fadeOut();
$("#date_popup_"+date).fadeIn();
});
$('.date_cell').mouseleave(function(){
$(".date_popup_wrap").fadeOut();
});
$('.month_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$('.year_dropdown').on('change',function(){
getCalendar('calendar_div',$('.year_dropdown').val(),$('.month_dropdown').val());
});
$(document).click(function(){
$('#event_list').slideUp('slow');
});
});
</script>
<?php
}
/*
* Get months options list.
*/
function getAllMonths($selected = ''){
$options = '';
for($i=1;$i<=12;$i++)
{
$value = ($i < 10)?'0'.$i:$i;
$selectedOpt = ($value == $selected)?'selected':'';
$options .= '<option value="'.$value.'" '.$selectedOpt.' >'.date("F", mktime(0, 0, 0, $i+1, 0, 0)).'</option>';
}
return $options;
}
/*
* Get years options list.
*/
function getYearList($selected = ''){
$options = '';
for($i=2015;$i<=2025;$i++)
{
$selectedOpt = ($i == $selected)?'selected':'';
$options .= '<option value="'.$i.'" '.$selectedOpt.' >'.$i.'</option>';
}
return $options;
}
/*
* Get events by date
*/
function getEvents($date = ''){
//Include db configuration file
include 'dbConfig.php';
$eventListHTML = '';
$date = $date?$date:date("Y-m-d");
//Get events based on the current date
$result = $db->query("SELECT title FROM events WHERE date = '".$date."' AND status = 1");
if($result->num_rows > 0){
$eventListHTML = '<h2>Events on '.date("l, d M Y",strtotime($date)).'</h2>';
$eventListHTML .= '<ul>';
while($row = $result->fetch_assoc()){
$eventListHTML .= '<li>'.$row['title'].'</li>';
}
$eventListHTML .= '</ul>';
}
echo $eventListHTML;
}
?>
//In index.php
<?php
//Include the event calendar functions file
include_once('functions.php');
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Event Calendar by CodexWorld</title>
<!-- Include the stylesheet -->
<link type="text/css" rel="stylesheet" href="style.css"/>
<!-- Include the jQuery library -->
<script src="jquery.min.js"></script>
</head>
<body>
<!-- Display event calendar -->
<div id="calendar_div">
<?php echo getCalender(); ?>
</div>
</body>
</html>

$.post JQuery not working

I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!

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