I php code that will insert into database but it always returns false even if it is inserting values into the database.
Here is my code: PHP
<?php
require_once 'connection.php';
if (isset($_POST['borrowBook']))
{
newBorrowRequest();
}
function newBorrowRequest()
{
$b_id = $GLOBALS['db']->real_escape_string($_POST['b_id']);
$userID = $GLOBALS['db']->real_escape_string($_POST['userID']);
$dateBorrowed = $GLOBALS['db']->real_escape_string($_POST['dateBorrowed']);
$remarks = $GLOBALS['db']->real_escape_string($_POST['remarks']);
$sql = "INSERT INTO `tbl_requestbook`(`b_id`, `userID`, `dateBorrowed`, `remarks`) VALUES ('$b_id','$userID','$dateBorrowed','$remarks')";
if($GLOBALS['db']->query($sql))
{
$GLOBALS['db']->close();
header("location:../../admin/Book-Items.php?r=success", true);
}
else
{
header("location:../../admin/Book-Items.php?r=failed", true);
}
}
>?
And here is my Ajax Code:
<script>
$("#borrowBook").click(function(event) {
var bookID = $("#bookBorrow").val();
var userID = $("#borrowBook").val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$.ajax({
url: '../assets/php/functions-book.php',
type: 'POST',
data: {borrowBook: 'true', b_id: bookID, userID: userID, dateBorrowed: output, remarks: $("#remarks").val() },
success: function(result) {
window.location.reload();
},
error: function(result) {
//window.location.reload();
console.log(result);
}
});
});
</script
There is something wrong with the php query, it will not iterate with the condition thus, it will call the ajax error function.
[EDITED]
I solved this by changing 'header("location:../../admin/Book-Item.php?r=success");' to 'header("location:../../admin/Book-Items.php?r=success");'. It was a wrong call.
My problem now is, after success the header remains. It can't be replace by the new header that I want to change. I already changed the php code to the latest.
I have implemented the following autoload code. It fetches result from database but it keeps looping the same result over and over.
php code
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$keywords = $_GET['keywords'];
$sql = "SELECT * FROM blog_posts WHERE postCat LIKE '".$keywords."' ORDER BY postID ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['postTitle'] . '</h3>';
}
}
?>
Try this
<?php
$keywords = 'events';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var keywords = '<?php echo $keywords; ?>'; // Changed
var busy = false;
var limit = 15;
var offset = 0;
function displayRecords(lim, off) {
// Changed/New
var data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html,textStatus,jqHXR) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No records found.</button>').show()
} else {
$("#loader_message").css('display','none');
$("#loader_message").html(html);
}
window.busy = false;
},
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
$('#result').on('scroll', function() { if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { busy = true; offset = limit + offset; setTimeout(function() { displayRecords(limit, offset); }, 500); } })
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
this is loading same contents over and over because on each ajax call you are sending same 'data' which is
var data = {
'limit': limit,
'offset': offset,
'keywords': keywords,
};
Change the function to use new limit and offset
function displayRecords(lim, off) {
data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
...
...
i'm having trouble with fullcalendar. im not sure whether it is my php or mysql code. the calendar displays and i can add a new event but the event does not stick to the calendar. the event data does get inserted into the database but again it does not appear on the actual calendar itself.
here is the code i have so far:
index.php
<!DOCTYPE html>
<html>
<head>
<title>FullCalendar</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel='stylesheet' type='text/css' href='css/style.css' />
<link rel='stylesheet' type='text/css' href='css/fullcalendar.css' />
<link rel='stylesheet' type='text/css' href='css/jquery-ui-1.8.11.custom.css' />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="js/jquery-ui-1.8.11.custom.min.js"></script>
<script src='js/fullcalendar.min.js'></script>
<script src="js/jquery-ui-timepicker-addon.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/* global variables */
var event_start = $('#event_start');
var event_end = $('#event_end');
var event_type = $('#event_type');
var calendar = $('#calendar');
var form = $('#dialog-form');
var event_id = $('#event_id');
var format = "MM/dd/yyyy HH:mm";
/* button to add events */
$('#add_event_button').button().click(function(){
formOpen('add');
});
/** cleaning function form */
function emptyForm() {
event_start.val("");
event_end.val("");
event_type.val("");
event_id.val("");
}
/* opening form types*/
function formOpen(mode) {
if(mode == 'add') {
/* hide button Delete , Edit and display the Add*/
$('#add').show();
$('#edit').hide();
$("#delete").button("option", "disabled", true);
}
else if(mode == 'edit') {
/* hide the Add button , display the Edit and Delete*/
$('#edit').show();
$('#add').hide();
$("#delete").button("option", "disabled", false);
}
form.dialog('open');
}
/* date time picker */
event_start.datetimepicker({hourGrid: 4, minuteGrid: 10, dateFormat: 'mm/dd/yy'});
event_end.datetimepicker({hourGrid: 4, minuteGrid: 10, dateFormat: 'mm/dd/yy'});
/* initialize full calendar */
calendar.fullCalendar({
firstDay: 1,
height: 500,
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
monthNames: ['January','Feburary','March','April','May','June','July','August','September','October','November','December'],
monthNamesShort: ['Jan.','Feb.','Маr','Apr.','May','Jun','Jul','Aug.','Sept.','Oct.','Nov.','Dec.'],
dayNames: ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturdat"],
dayNamesShort: ["Su","Mo","Tu","We","Th","Fr","Sa"],
buttonText: {
prev: " ◄ ",
next: " ► ",
prevYear: " << ",
nextYear: " >> ",
today: "today",
month: "month",
week: "week",
day: "day"
},
/* time format output before the event name*/
timeFormat: 'H:mm',
/* click event handler for a particular day */
dayClick: function(date, allDay, jsEvent, view) {
var newDate = $.fullCalendar.formatDate(date, format);
event_start.val(newDate);
event_end.val(newDate);
formOpen('add');
},
/* handler for event click */
eventClick: function(calEvent, jsEvent, view) {
event_id.val(calEvent.id);
event_type.val(calEvent.title);
event_start.val($.fullCalendar.formatDate(calEvent.start, format));
event_end.val($.fullCalendar.formatDate(calEvent.end, format));
formOpen('edit');
},
/* record source */
eventSources: [{
url: 'ajax.php',
type: 'POST',
data: {
op: 'source'
},
error: function() {
alert('Error connecting to the data source!');
}
}]
});
/* form handler */
form.dialog({
autoOpen: false,
buttons: [{
id: 'add',
text: 'add',
click: function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
start: event_start.val(),
end: event_end.val(),
type: event_type.val(),
op: 'add'
},
success: function(id){
calendar.fullCalendar('renderEvent', {
id: id,
title: event_type.val(),
start: event_start.val(),
end: event_end.val(),
allDay: false
});
}
});
emptyForm();
}
},
{ id: 'edit',
text: 'edit',
click: function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: event_id.val(),
start: event_start.val(),
end: event_end.val(),
type: event_type.val(),
op: 'edit'
},
success: function(id){
calendar.fullCalendar('refetchEvents');
}
});
$(this).dialog('close');
emptyForm();
}
},
{ id: 'cancel',
text: 'cancel',
click: function() {
$(this).dialog('close');
emptyForm();
}
},
{ id: 'delete',
text: 'delete',
click: function() {
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: event_id.val(),
op: 'delete'
},
success: function(id){
calendar.fullCalendar('removeEvents', id);
}
});
$(this).dialog('close');
emptyForm();
},
disabled: true
}]
});
});
</script>
</head>
<body>
<div id="calendar"></div>
<button id="add_event_button">Add Event</button>
<div id="dialog-form" title="Событие">
<p class="validateTips"></p>
<form>
<p><label for="event_type">type</label>
<input type="text" id="event_type" name="event_type" value=""></p>
<p><label for="event_start">start</label>
<input type="text" name="event_start" id="event_start"/></p>
<p><label for="event_end">end</label>
<input type="text" name="event_end" id="event_end"/></p>
<input type="hidden" name="event_id" id="event_id" value="">
</form>
</div>
</body>
</html>
ajax.php
<?php
$con=mysqli_connect("localhost","root","","fullcalendar");
$start = $_POST['start'];
$end = $_POST['end'];
$type = $_POST['type'];
$op = $_POST['op'];
$id = $_POST['id'];
switch ($op) {
case 'add':
$sql = 'INSERT INTO events (
start,
end,
type)
VALUES
("' . date("Y-m-d H:i:s", strtotime($start)) . '",
"' . date("Y-m-d H:i:s", strtotime($end)) . '",
"' . $type . '")';
if (mysqli_query($GLOBALS["___mysqli_ston"], $sql)) {
echo ((is_null($___mysqli_res = mysqli_insert_id($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
}
break;
case 'edit':
$sql = 'UPDATE events SET start = "' . date("Y-m-d H:i:s", strtotime($start)) . '",
end = "' . date("Y-m-d H:i:s", strtotime($end)) . '",
type = "' . $type . '"
WHERE id = "' . $id . '"';
if (mysqli_query($GLOBALS["___mysqli_ston"], $sql)) {
echo $id;
}
break;
case 'source':
$sql = 'SELECT * FROM events';
$result = mysqli_query($GLOBALS["___mysqli_ston"], $sql);
$json = Array();
while ($row = mysqli_fetch_assoc($result)) {
$json[] = array(
'id' => $row['id'],
'title' => $row['type'],
'start' => $row['start'],
'end' => $row['end'],
'allDay' => false
);
}
echo json_encode($json);
break;
case 'delete':
$sql = 'DELETE FROM events WHERE id = "' . $id . '"';
if (mysqli_query($GLOBALS["___mysqli_ston"], $sql)) {
echo $id;
}
break;
}
i'd appreciate it if there could be any constructive input or help with this issue.
Hey guys thanks for the help. I had a look at the ajax like charlietfl said and I got a few errors thrown. They were mainly errors about the database connection but seeing as the events are getting inserted to the table it didn't seem correct. I double checked the syntax of the php and mysql and it turns out I was using a few mysql functions that have been depreciated in the newest version of php. It was recommended I changed it to match the PDO or mysqli structure to see if it would work and it did. Thanks for everybody's inputs i really appreciate it.
I am having problems with a jquery. The code below is not triggered when the php page loads. I attempt to check the value of a field in a database table and do a redirect if the returned value is 0. I have been struggeling with this for hours and I have really searched around to find the answer. Any help is appreciated.
<script type="text/javascript">
$jQn(document).ready(function(){
var do_checking;
var status = 1;
var ui = "";
if(status == 1){
$jQn.blockUI.defaults.overlayCSS.opacity=.3;
$jQn.blockUI({
message: ui,
css: {
border: '10px solid #888',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
color: '#fff',
width: '50%',
left: '25%',
cursor: 'wait',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'-moz-opacity':.10,
opacity:.10,
padding:'15px'
}
});
do_checking = setInterval(check_search_status, 1000);
} else {
document.location = 'https://mysite.com/result.php';
}
});
function check_search_status(){
$jQn.ajax({
type: 'POST',
url: 'https://mysite.com/checksearchstatus.php',
data: {
id: '$owner'
},
dataType: 'json',
success: function(response){
if(response.status == 0){
clearInterval(do_checking);
document.location = 'https://mysite.com/result.php';
}
}
});
}
</script>
Here is the code of the separated php file
$con = mysql_connect($db_host,$db_username,$db_password);
if (!$con)
{
die('Feil ved tilkobling av: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$response = array('status' => '');
$user_id = $_POST['id'];
// Build SQL
$first_search_sql = "SELECT `firstsearch` FROM `class_users` WHERE id = '".$user_id."'";
$first_search_result = $db->query($first_search_sql);
// Fetch result
$first_search_row = $first_search_result->fetch();
// Free result
$first_search_result->freeResult();
$response['status'] = $first_search_row['firstsearch'] ;
echo json_encode($response);
A friend of mine had given me this snippet for a js file that can be useful for me:
$.ajax({
type: "POST",
url: "../CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Patient Name already exists!', 'Error');
return;
}
else {
$.ajax({
type: "POST",
url: "../NewPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "','gender':'" + _gender + "','birthDate':'" + _bday + "','ssn':'" + _ssn + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _id = response.d;
if (_id.length != 0) {
$('#patientName').removeAttr('disabled');
$('#patientName').val(_lname + ", " + _fname + " " + _mname);
$('#patientId').val(_id[0].patientID);
$('#dateOfBirth').val(_bday);
$('#referringDoctor').removeAttr('disabled');
$('#referringDoctor').focus();
$('#patientAge').val(_id[1]);
$('#ptLastName').val('');
$('#ptFirstName').val('');
$('#ptMiddleName').val('');
$('#ptGender').val('');
// $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
$('#ptSSN').val('');
}
// if (_id == true) {
// }
insertCallback(_id);
// $('#diagnosis tbody>tr:last').attr('dinfo', '_IEDiagnosis|' + _id);
},
failure: function (msg) {
alert(msg);
}
});
}
}
});
I'm using PHP but I'm new to using JSON. Is there a way to return a true value for "response.d" in my PHP file:
success: function (response) {
var _id = response.d;
}
Here's my logic but don't know the code to use:
$lastname = isset($_REQUEST['lastName'])?$_REQUEST['lastName']:'';
$firstname = isset($_REQUEST['firstName'])?$_REQUEST['firstName']:'';
$middlename = isset($_REQUEST['middleName'])?$_REQUEST['middleName']:'';
$response = array();
mysql_connect ("localhost", "root") or die ('Error: ' . mysql_error());
mysql_select_db ("healthpal");
$query = "SELECT Lastname, Firstname, MiddleName FROM db_patients WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";
$qrytest = mysql_query($query);
if (isset($qrytest)) {
//"response.d" will be true if the query return not NULL
}
Try something like this:
header('Content-type: application/x-json');
echo json_encode( array( 'd' => true ) );
What you need is the php json_encode function:
json_encode(array('response'=>'true')));
You have to construct JSON string in your PHP file, some thing like this
{"result":"true"}
this constructed JSON string should return as PHP response. In Javascript parse the JSON as,
var obj = eval(response)
if(obj.result == 'true'){
//Do your code here
}