How to Enable only Scheduled Dates in date picker - php

My Project Description
I'm making Attendance management system. requirement is as follows
1)First i need make a Schedule.
2)Select Schedule and Put attendance.
I'm getting following Values from schedule.php file
Array ( [schedulename] => Class for 1st year [subject] => Data Structure [university] => abc [facultyname] => Dr Rao [scheduleStartDate] => 2015-06-09 [scheduleEndDate] => 2015-06-18 [submit] => )
And My AddAttendance.php file as follows
<?php
require_once 'config/config.php';
//require_once 'config/session.php';
require_once 'class/dbclass.php';
require_once 'class/StuRegister.php';
$stu = new StuRegister();
$AllList = $stu->AllList();
?>
<!DOCTYPE html>
<html>
<head>
<?php require_once 'config/commonJS.php'; ?>
<script>
$(document).ready(function(){
$( "#date" ).datepicker({
currentText: "Now",
dateFormat: 'yy-mm-dd',
inline: true,
altField: '#datepicker_value',
onSelect: function(){
getData();
}
});
var myDate = new Date();
var prettyDate =myDate.getFullYear() +'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
$("#datepicker_value").val(prettyDate);
});
</script>
<script type="text/javascript">
function getData(){
//alert('Hi you have Selected Date');
var dt = $("#datepicker_value").val();
$.ajax({
type: "POST",
url: "process/processStuAttendance.php",
data: {type:'get',date:dt},
beforeSend : function () {
$('#wait').html("Loading");
},
success: function(resp){
var obj = jQuery.parseJSON(resp);
if(obj.sucess == 'new'){
$('.present').attr('checked',false);
}else{
$('.present').attr('checked',false);
$(obj.data).attr('checked',true);
}
},
error: function(e){
alet('Please Try again form not submit sucessful');
}
});
}
function setData(){
if(!$('#formSubmit').validationEngine('validate')){
}else{
//alert('Hi setDate called');
var absent = unCheckedStudent();
var formVal = $('#formSubmit').serialize();
if(absent != null){
formVal+="&absent="+absent;
}
$.ajax({
type: "POST",
url: "process/processStuAttendance.php",
data: formVal,
beforeSend : function () {
$('#wait').html("Loading");
},
success: function(resp){
alert('Sucessful'+resp);
},
error: function(e){
alet('Please Try again form not submit sucessful');
}
});
}
}
function unCheckedStudent(){
//alert('Hi unCheckedStudent called');
var ellength = document.formSubmit.elements.length;
var absent = new Array();
for(i=0;i<ellength;i++){
var type = document.formSubmit.elements[i].type;
var name = document.formSubmit.elements[i].name;
if (type=="checkbox" && name=="present[]" && document.formSubmit.elements[i].checked){
}
else if(type=="checkbox" && name=="present[]"){
absent.push(document.formSubmit.elements[i].value);
}
}
return absent;
}
</script>
</head>
<body>
<div id="content-wrap">
<div id="main">
<form name="formSubmit" class='form' id="formSubmit" method="post" >
<input type="hidden" name="type" value="<?php echo $sl_no == '' ? 'Add' : 'Update'; ?>">
<!-- <input type="text" onchange="getData(this.value)" class="validate[required]" readonly style="margin-left: 20px;" name="date" id="date" >-->
<input type="hidden" onchange="getData(this.value)" class="validate[required]" readonly style="margin-left: 20px;" name="date" id="datepicker_value" >
<div id="date" style="float: right;margin: 20px;"></div>
<br/>
<br/>
<div style="float: left;margin: 20px;">
<table width="500px" class="tbl">
<tr><th><b>Present</b></th><th><b>Name</b></th><th><b>University</b></th></tr>
<?php
for ($i = 0; $i < count($AllList); $i++) {
echo "<tr>";
echo "<td><input id='{$AllList[$i]['sl_no']}' type='checkbox' name='present[]' class='present' value='{$AllList[$i]['sl_no']}'></td>";
echo "<td>{$AllList[$i]['student_name']}</td>";
echo "<td>{$AllList[$i]['university']}</td>";
echo "</tr>";
}
?>
</table>
<input style="margin: 20px;cursor: pointer;" type="button" class="button" onclick="setData()" value="Save">
</div>
</form>
</div>
</div>
</body>
</html>
How can Make only scheduled dates are Enabled in datepicker, Any help may greatly appreciated.

What you need to do is to do this tricky 2 step
Step 1 :
List the Dates between your From and To Date by
<?php
$scheduleStartDate = '2015-06-09';
$scheduleEndDate = '2015-06-18';
$Date = getDatesFromRange($scheduleStartDate,$scheduleEndDate);
$Date = substr($Date, 0, -1);
function getDatesFromRange($start, $end){
$dates = array($start);
$Value = '';
while(end($dates) < $end)
{
$dates[] = date('Y-m-d', strtotime(end($dates).' +1 day'));
$Value .= '"'.date('j-n-Y', strtotime(end($dates).' +1 day')).'",';
}
return $Value;
}
?>
Step 2 :
Pass it inside the script that you have , $Date is the one you got from php
<script>
$( window ).load(function() {
var availableDates = [<?php echo $Date?>];
function available(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, availableDates) != -1) {
return [true, "","Available"];
} else {
return [false,"","unAvailable"];
}
}
$('#date').datepicker({ beforeShowDay: available });
});
</script>
So, Finally you can this code to enable the date you want ;)

Related

Select results from live search ajax

I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});

Filter Records based on combobox value php ajax

I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
I want to display records based on the value of the combobox (dropdown list) using ajax. Display list of examinees based on the examdate. Help. I am a newbie in PHP and AJAX.
<?php
include 'configuration.php';
$queryselect = mysql_query("SELECT examdateno, examdate from tbl_examdate ORDER BY examdate DESC");
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="onclick edit jquery php, grid in php, onclick change text box in jquery, onclick edit table row, insert update delete using jquery ajax, simple php data grid" />
<meta name="description" content="This article is about simple grid system using PHP, jQuery. Insert a new record to the table using by normal Ajax PHP. It will show the editable textbox when user clicks on the label." />
<link rel="stylesheet" type="text/css" href="css/grid.css" />
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/component.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
// Function for load the grid
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function (responseText) {
gridder.html(responseText);
}
});
}
// Seperate Function for datepiker() to save the value
function ForDatePiker(ThisElement) {
ThisElement.prev('span').html(ThisElement.val()).prop('title', ThisElement.val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
LoadGrid(); // Load the grid on page loads
// Execute datepiker() for date fields
$("body").delegate("input[type=text].datepicker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd',
onSelect: function () {
setTimeout(ForDatePiker(ThisElement), 500);
}
});
});
// Show the text box on click
$('body').delegate('.editable', 'click', function () {
var ThisElement = $(this);
ThisElement.find('span').hide();
ThisElement.find('.gridder_input').show().focus();
});
// Pass and save the textbox values on blur function
$('body').delegate('.gridder_input', 'blur', function () {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
});
// Same as the above blur() when user hits the 'Enter' key
$('body').delegate('.gridder_input', 'keypress', function (e) {
if (e.keyCode == '13') {
var ThisElement = $(this);
ThisElement.hide();
ThisElement.prev('span').show().html($(this).val()).prop('title', $(this).val());
var UrlToPass = 'action=update&value=' + ThisElement.val() + '&crypto=' + ThisElement.prop('name');
if (ThisElement.hasClass('datepicker')) {
return false;
}
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass
});
}
});
// Function for delete the record
$('body').delegate('.gridder_delete', 'click', function () {
var conf = confirm('Are you sure want to delete this record?');
if (!conf) {
return false;
}
var ThisElement = $(this);
var UrlToPass = 'action=delete&value=' + ThisElement.attr('href');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: UrlToPass,
success: function () {
LoadGrid();
}
});
return false;
});
// Add new record
// Add new record when the table is empty
$('body').delegate('.gridder_insert', 'click', function () {
$('#norecords').hide();
$('#addnew').slideDown();
return false;
});
// Add new record when the table in non-empty
$('body').delegate('.gridder_addnew', 'click', function () {
$('html, body').animate({scrollTop: $('.as_gridder').offset().top}, 250); // Scroll to top gridder table
$('#addnew').slideDown();
return false;
});
// Cancel the insertion
$('body').delegate('.gridder_cancel', 'click', function () {
LoadGrid()
return false;
});
// For datepiker
$("body").delegate(".gridder_add.datepiker", "focusin", function () {
var ThisElement = $(this);
$(this).datepicker({
dateFormat: 'yy/mm/dd'
});
});
// Pass the values to ajax page to add the values
$('body').delegate('#gridder_addrecord', 'click', function () {
// Do insert vaidation here
if ($('#fname').val() == '') {
$('#fname').focus();
alert('Enter the First Name');
return false;
}
if ($('#lname').val() == '') {
$('#lname').focus();
alert('Enter the Last Name');
return false;
}
if ($('#age').val() == '') {
$('#age').focus();
alert('Enter the Age');
return false;
}
if ($('#profession').val() == '') {
$('#profession').focus();
alert('Select the Profession');
return false;
}
if ($('#date').val() == '') {
$('#date').focus();
alert('Select the Date');
return false;
}
// Pass the form data to the ajax page
var data = $('#gridder_addform').serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
success: function () {
LoadGrid();
}
});
return false;
});
});
</script>
</head>
<body>
<header>
<img src="images/qes_logob.png" alt="logo">
<button class="hamburger">☰</button>
<button class="cross">˟</button>
</header>
<div class="menu">
<ul>
<a href="encodeinterview.php">
<li>Encode Grades</li>
</a>
<a href="viewinterview.php">
<li>View Grades</li>
</a>
<a href="../index.php">
<li>Logout</li>
</a>
</ul>
</div>
<script>
$(function () {
$(".cross").hide();
$(".menu").hide();
$(".hamburger").click(function () {
$(".menu").slideToggle("slow", function () {
$(".hamburger").hide();
$(".cross").show();
});
});
$(".cross").click(function () {
$(".menu").slideToggle("slow", function () {
$(".cross").hide();
$(".hamburger").show();
});
});
});
</script>
<form>
<h1>Exam Dates</>
<select name="examdate" id="examDate" onchange="LoadGrid(this.value)">
<option>Select Exam Date</option>
<?php
while ($row = mysql_fetch_array($queryselect)) {
echo "<option value={$row['examdateno']}>{$row['examdate']}</option>\n";
}
?>
</select>
</form>
<div class="as_wrapper">
<div class="as_grid_container">
<div class="as_gridder" id="as_gridder"></div> <!-- GRID LOADER -->
</div>
</div>
</body>
</html>
AJAX
<?php
include 'configuration.php';
include 'functions/functions.php';
$action = $_REQUEST['action'];
$q = intval($_POST['q']);
switch($action) {
case "load":
$query = mysql_query("select s.sno, s.fname, s.lname, s.examdate, s.interviewgrade, s.gwa from student s inner join tbl_examdate e on s.examdate=e.examdate where e.examdateno=$q");
$count = mysql_num_rows($query);
if($count > 0) {
while($fetch = mysql_fetch_array($query)) {
$record[] = $fetch;
}
}
$department = array('Software Architect', 'Inventor', 'Programmer', 'Entrepreneur');
?>
<table class="as_gridder_table">
<tr class="grid_header">
<td><div class="grid_heading">Sno</div></td>
<td><div class="grid_heading">First Name</div></td>
<td><div class="grid_heading">Last Name</div></td>
<td><div class="grid_heading">Age</div></td>
<td><div class="grid_heading">Profession</div></td>
<td><div class="grid_heading">Date</div></td>
<td><div class="grid_heading">Actions</div></td>
</tr>
<tr id="addnew">
<td> </td>
<td colspan="6">
<form id="gridder_addform" method="post">
<input type="hidden" name="action" value="addnew" />
<table width="100%">
<tr>
<td><input type="text" name="fname" id="fname" class="gridder_add" /></td>
<td><input type="text" name="lname" id="lname" class="gridder_add" /></td>
<td><input type="text" name="age" id="age" class="gridder_add" /></td>
<td><select name="profession" id="profession" class="gridder_add select">
<option value="">SELECT</option>
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>"><?php echo $departments; ?></option>
<?php } ?>
</select></td>
<td><input type="text" name="date" id="date" class="gridder_add datepiker" /></td>
<td>
<input type="submit" id="gridder_addrecord" value="" class="gridder_addrecord_button" title="Add" />
<img src="images/delete.png" alt="Cancel" title="Cancel" /></td>
</tr>
</table>
</form>
</tr>
<?php
if($count <= 0) {
?>
<tr id="norecords">
<td colspan="7" align="center">No records found <img src="images/insert.png" alt="Add New" title="Add New" /></td>
</tr>
<?php } else {
$i = 0;
foreach($record as $records) {
$i = $i + 1;
?>
<tr class="<?php if($i%2 == 0) { echo 'even'; } else { echo 'odd'; } ?>">
<td><div class="grid_content sno"><span><?php echo $i; ?></span></div></td>
<td><div class="grid_content editable"><span><?php echo $records['fname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("fname|".$records['id']); ?>" value="<?php echo $records['fname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['lname']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("lname|".$records['id']); ?>" value="<?php echo $records['lname']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['age']; ?></span><input type="text" class="gridder_input" name="<?php echo encrypt("age|".$records['id']); ?>" value="<?php echo $records['age']; ?>" /></div></td>
<td><div class="grid_content editable"><span><?php echo $records['profession']; ?></span>
<select class="gridder_input select" name="<?php echo encrypt("profession|".$records['id']); ?>">
<?php foreach($department as $departments) { ?>
<option value="<?php echo $departments; ?>" <?php if($departments == $records['profession']) { echo 'selected="selected"'; } ?>><?php echo $departments; ?></option>
<?php } ?>
</select>
</div></td>
<td><div class="grid_content editable"><span><?php echo date("Y/m/d", strtotime($records['posted_date'])); ?></span><input type="text" class="gridder_input datepicker" name="<?php echo encrypt("posted_date|".$records['id']); ?>" value="<?php echo date("Y/m/d", strtotime($records['posted_date'])); ?>" /></div></td>
<td>
<img src="images/insert.png" alt="Add New" title="Add New" />
<img src="images/delete.png" alt="Delete" title="Delete" /></td>
</tr>
<?php
}
}
?>
</table>
<?php
break;
case "addnew":
$fname = isset($_POST['fname']) ? mysql_real_escape_string($_POST['fname']) : '';
$lname = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
$age = isset($_POST['age']) ? mysql_real_escape_string($_POST['age']) : '';
$profession = isset($_POST['profession']) ? mysql_real_escape_string($_POST['profession']) : '';
$date = isset($_POST['date']) ? mysql_real_escape_string($_POST['date']) : '';
mysql_query("INSERT INTO `grid` (fname, lname, age, profession, posted_date) VALUES ('$fname', '$lname', '$age', '$profession', '$date')");
break;
case "update":
$value = $_POST['value'];
$crypto = decrypt($_POST['crypto']);
$explode = explode('|', $crypto);
$columnName = $explode[0];
$rowId = $explode[1];
if($columnName == 'posted_date') { // Check the column is 'date', if yes convert it to date format
$datevalue = $value;
$value = date('Y-m-d', strtotime($datevalue));
}
$query = mysql_query("UPDATE `grid` SET `$columnName` = '$value' WHERE id = '$rowId' ");
break;
case "delete":
$value = decrypt($_POST['value']);
$query = mysql_query("DELETE FROM `grid` WHERE id = '$value' ");
break;
}
?>
You are not passing exam date in your ajax, i e q, but you are using that in $_POST, so pass the value from ajax to your file.
function LoadGrid(dte) {
var gridder = $('#as_gridder');
var UrlToPass = 'action=load';
var value = $('#examdate').val();
gridder.html('loading..');
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {action:"load",q:dte}, <----- this line.
success: function (responseText) {
gridder.html(responseText);
}
});
}

unexpected end of input php jQuery

I have written same code at one machine and it is working fine but on other machine same code is giving error unexpected end of input. This is driving me crazy as why it is happening. Anybody who can help, please. These are my files with which I am working.
edit: I am making a small online test application for learning purpose. As the test start, the first question appears, on clicking next button the url changes to what it should be but next question does not appear and the error in the console says unexpected end of input. Since all my brackets are ok, I am not able to find error. Please help!!
TestStart.php
<?php
session_start();
if(isset($_SESSION['TestId']))
{
$TestId = $_SESSION['TestId'];
}
include('Config.php');
include('Reference.php');
$query = "select * from testquestions where testid='".$TestId."'";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$z = array();
while($fetch = mysql_fetch_array($res))
{
$z[]=$fetch['QId'];
}
$y = implode(",", $z);
$_SESSION['QIds']=$z;
}
else{
echo mysql_error();
}
?>
<body>
<div class="container">
<div class="row">
<div class="col-md-12" id="resultDiv">
<div class="col-md-12" id="qtext"></div>
<div class="col-md-12">
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionA"name="options" value="A"><span id="optA"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionB" name="options" Value="B"><span id="optB"></span>
</div>
</div>
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionC" name="options" value="C"><span id="optC"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionD" name="options" value="D"><span id="optD"></span>
</div>
</div>
</div>
<div id="nextbuttondiv"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
<?php
if(isset($_GET['qno'])&&isset($_GET['qindex']))
{
$qno = $_GET['qno'];
$qindex = $_GET['qindex'];
}
else{
$qno = '1';
$qindex = '0';
}
?>
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
var qidsarrCm = '<?php echo $y;?>';
var arrQid = qidsarrCm.split(",");
var totalQuestions = arrQid.length;
$.ajax({
type : "post",
url : "GetQuestionForTest.php",
data : {
"quId" : arrQid[qindex]
},
dataType : "json",
success : function(data){
alert('xy');
console.log(data);
$.each(data, function(){
var qText = this.questiontext;
var optionA = this.OptionA;
var optionB = this.OptionB;
var optionC = this.OptionC;
var optionD = this.OptionD;
var nxtBtn = this.NextButton;
$('#qtext').text(qText);
$('#optA').text(optionA);
$('#optB').text(optionB);
$('#optC').text(optionC);
$('#optD').text(optionD);
$('#nextbuttondiv').html(nxtBtn);
});
},
error: function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
$('input[type=radio]').on('click',function(){
$('.nxtbtn').removeAttr('disabled');
});
$('body').on('click','.nxtbtn', function(){
$.ajax({
type : "post",
url : "SaveTestAnswers.php",
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : <?php echo $_SESSION['CurrentUser'];?>,
"testId" : <?php echo $TestId;?>
},
dataType : "json",
success : function(data){
if(data.toString() == "true"){
qindex = qindex + 1;
qno = qno + 1;
if(qno > totalQuestions){
window.location.href="TestFinish.php";
}
else{
window.location.href="TestStart.php?qno="+qno+"&qindex="+qindex;
}
}
else{
alert(data + "Please resubmit the answer");
}
},
error : function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
});
});
</script>
</body>
GetQuestionForTest.php
<?php
$questionid = $_POST['quId'];
include('Config.php');
$query = "select * from questionstable where questionid = '".$questionid."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
$someArray = [];
while($fetch = mysql_fetch_array($result))
{
array_push($someArray,[
'questiontext' => $fetch['questiontext'],
'OptionA' => $fetch['optionA'],
'OptionB' => $fetch['optionB'],
'OptionC' => $fetch['optionC'],
'OptionD' => $fetch['optionD'],
'NextButton' => '<button class="btn btn-success nxtbtn" disabled >Next</button>'
]);
}
$someJSON = json_encode($someArray);
echo $someJSON;
}
else{
echo mysql_error();
}
?>
SaveTestAnswers.php
<?php
$qid = $_POST['qid'];
$ansId = $_POST['ansId'];
$stuId = $_POST['stuId'];
$testId = $_POST['testId'];
include('Config.php');
$query = "insert into testattemptedanswers(StudentId,TestId,QuestionId,AnswerGiven) values('".$stuId."','".$testId."','".$qid."','".$ansId."')";
$res = mysql_query($query);
if($res){
echo 'true';
}
else{
echo 'false'.mysql_error();
}
?>
Missing quotes -
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
Change them to -
var qno = '<?php echo $qno;?>';
var qindex = '<?php echo $qindex;?>';
And here also -
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : '<?php echo $_SESSION['CurrentUser'];?>',
"testId" : '<?php echo $TestId;?>'
},

Javascript Not Updating Database

I have a Edit Profile, for the user's profile. Well, The Javascript seems to be only getting the value of the Age's Form. The PHP File is getting the Age, but no others and it's not updating the database.
Javascript:
function UpdateProfile() {
var newage = $("#NewAge").val();
var newimage = $("#NewImage").val();
var newbio = $("#NewBio").val();
var dataString = 'newage=' + newage || 'newimage=' + newimage || 'newbio=' + newbio;
if (newbio.length , newage.length , newimage.length == 0) {
$('#Required').fadeIn(300);
$('#Mask').fadeIn(300);
} else {
$.ajax({
type: "POST",
url: "update_profile.php",
data: dataString,
cache: false,
success: function (UpdateProfile) {
$('#EditInfo').hide();
$("#UpdatedProfile").html(UpdateProfile);
$("#UpdatedProfile").fadeIn('slow');
$("#Age").html('Age: ' + newage);
$('#Image').html('<img src="' + newimage +'" width="150" height="100" />');
}
});
}
}
Here's The update_profile.php File:
<?php session_start() ?>
<?php include 'connect.php' ?>
<?php
$newimage = $_POST['newimage'];
$newbio = $_POST['newabout'];
$newage = $_POST['newage'];
$update = "UPDATE members SET bio=(".$newbio.") age=(".$newage.") image=(".$newimage.") WHERE id='".$id."'";
$res = mysql_query($update);
echo 'Success: Profile Updated!<br />';
echo $update . '<br />';
?>
HTML:
<input type="text" id="NewAge" value="<?php echo $age ?>" maxlength="2" />
<input type="text" id="NewImage" value="<?php echo $image ?>" maxlength="500" />
<textarea id="NewBio" style="width: 500; max-width: 500; height: 100; max-height: 150;"><?php echo $bio ?></textarea>
<input type="submit" value="Update Profile" onClick="UpdateProfile()" />
The Code The Update outputs is this:
Success: Profile Updated!
UPDATE members SET bio=() age=(18) image=() WHERE id='1'
Try this instead:
$.ajax({
...
data: { newimage: newimage,
newage: newage,
newbio: newbio }
...
});
Update this line:
$newbio = $_POST['newabout'];
to
$newbio = $_POST['newbio'];
And it should work.

Problem with Mootools Ajax request and submitting a form

I have a table with content comming from a database. Now i tryed to realize a way to (a) delete rows from the table (b) edit the content of the row "on the fly". (a) is working perfectly (b) makes my head smoking!
Here is the complete Mootools Code:
<script type="text/javascript">
window.addEvent('domready', function() {
var eDit = $('edit_hide');
eDit.slide('hide');
var del = new Request.HTML(
{
url: 'fuss_response.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
eDit.slide('in');
}
});
$$('input.delete').addEvent( 'click', function(e){
e.stop();
var aID = 'delete_', bID = '';
var deleteID = this.getProperty('id').replace(aID,bID);
new MooDialog.Confirm('Soll der Termin gelöscht werden?', function(){
del.send({data : "id=" + deleteID});
}, function(){
new MooDialog.Alert('Schon Konfuzius hat gesagt: Erst denken dann handeln!');
});
});
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
var safe = new Request.HTML(
{
url: 'termin_safe.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
}
});
$$('input.edit').addEvent( 'click', function(e){
e.stop();
var aID = 'edit_', bID = '';
var editID = this.getProperty('id').replace(aID,bID);
edit.send({data : "id=" + editID});
$('edit_hide').slide('toggle');
});
});
</script>
Here the PHP Part that makes the Edit Form:
<?php
$cKey = mysql_real_escape_string($_POST['id']);
$request = mysql_query("SELECT * FROM fusspflege WHERE ID = '".$cKey."'");
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
}
echo '<form id="termin_edit" method="post" action="">';
echo '<div><label>Name:</label><input type="text" id="nns" name="name" value="'.$name.'"></div>';
echo '<div><label>Vorname:</label><input type="text" id="nvs" name="vorname" value="'.$vor.'"></div>';
echo '<div><label>Ort:</label><input type="text" id="nos" name="ort" value="'.$ort.'"></div>';
echo '<div><label>Telefon:</label><input type="text" id="nts" name="telefon" value="'.$tel.'"></div>';
echo '<div><label>eMail:</label><input type="text" id="nms" name="email" value="'.$mail.'"></div>';
echo '<input name="id" type="hidden" id="ids" value="'.$id.'"/>';
echo '<input type="button" id="sst" value="Speichern">';
echo '</form>';
?>
And last the Code of the termin_safe.php
$id = mysql_real_escape_string($_POST['id']);
$na = mysql_real_escape_string($_POST['name']);
$vn = mysql_real_escape_string($_POST['vorname']);
$ort = mysql_real_escape_string($_POST['ort']);
$tel = mysql_real_escape_string($_POST['telefon']);
$em = mysql_real_escape_string($_POST['email']);
$score = mysql_query("UPDATE fuspflege SET name = '".$na."', vorname = '".$vn."', ort = '".$ort."', telefon = '".$tel."', email = '".$em."' WHERE ID = '".$id."'");
As far as i can see the request does work but the data is not updated! i guess somethings wrong with the things posted
For any suggestions i will be gladly happy!
PS after some comments: I see the problem in this part:
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
The "Edit" request opens the form with the prefilled input fields and then attaches a click event to the submit button which should call a new request when clicked.
This third request i fail to pass the data of the input fields. i tried to get the value of each field like this:
var name = $('nns').getProperty('value');
and pass it this way
.send({data : "name=" + name});
did not work so far
PPS:
as requested the code that makes the html from main site
<?php $request = mysql_query("SELECT * FROM fusspflege");
echo '<form id="fusspflege" method="post" action="">';
echo '<table class="fuss_admin">';
echo '<tr><th>Name</th><th>Vorname</th><th>Ort</th><th>Telefon</th><th>eMail</th><th>Uhrzeit</th><th>Datum</th><th></th><th></th></tr>';
echo '<tr><td colspan=8 id="upd"></td></tr>';
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
$dat = $row->datum;
$uhr = $row->uhrzeit;
echo '<tr><td>'.$name.'</td><td>'.$vor.'</td><td>'.$ort.'</td><td>'.$tel.'</td><td>'.$mail.'</td><td>'.$uhr.'</td><td>'.$dat.'</td>';
echo '<td><input id="delete_'.$id.'" class="delete" type="button" value="X"></td>';
echo '<td><input id="edit_'.$id.'" class="edit" type="button" value="?"></td>';
echo '</tr>';
}
echo '</table>';
echo '</form>';
echo '<div id="edit_hide"></div>';
?>
UPDATE:
<form action="" method="post" id="termin_edit">
<div>
<label>
Name:
</label>
<input type="text" value="NAME" name="name" id="nns">
</div>
<div>
<label>
Vorname:
</label>
<input type="text" value="Marianne" name="vorname" id="nvs">
</div>
<div>
<label>
Ort:
</label>
<input type="text" value="MArkt Wald" name="ort" id="nos">
</div>
<div>
<label>
Telefon:
</label>
<input type="text" value="" name="telefon" id="nts">
</div>
<div>
<label>
eMail:
</label>
<input type="text" value="info#rudolfapotheke.de" name="email" id="nms">
</div>
<input type="hidden" value="115" id="ids" name="id">
<input type="button" value="Speichern" id="sst">
</form>
Update:
This is the mootools script based on the form you gave me that should work with your html:
$('sst').addEvent('click', function(event) {
var data;
event.stop();
var myInputEl = $$('#termin_edit input');
for(var i=0; i<myInputEl.length; i++){
if(i == 0)
data = myInputEl[i].name + "=" + myInputEl[i].value;
else
data += "&" + myInputEl[i].name + "=" + myInputEl[i].value;
}
myRequest.send(data);
});
Also add alert to your Request call back for the edit just to test if the ajax worked:
onSuccess: function(responseText) {
alert("done! " + responseText);
},
onFailure: function() {
alert("failed");
}
On the php side create a new PHP file and put the following in it and have ajax target it:
<?php
print_r($_POST);
?>
The Ajax should return the $_POST array in the alert box.

Categories