How can I call PHP from dayClick? - php

I need to save a date in my database through fullcalendar dayclick function, because I'm working with days and not with events.
I have my marcarsenhas.php where I display the calendar and my insert.php where I program the Insert.
I have a Select example that is working so I will provide you everything.
marcarsenhas.php (Where I display the calendar / Showing only the script)
<script>
$(document).ready(function() {
var day;
var iduser = $("#iduser").attr("valor");
//alert($("#iduser").attr("valor"));
//funcionar
$('#calendar').fullCalendar({
selectable: true,
editable: false,
events: {
url: 'getdados.php',
data: {iduser : iduser},
//data: {d : dia, m : mes, a: ano, id : iduser},
success: function(){
// alert("ok");
/*var data_array = $.parseJSON(data);
$("#response").empty().append( data );
$("#id_oc").empty().append( data_array['idoc'] );
$("#design").empty().append( data_array['design'] );
$("#qtd").empty().append( data_array['qtd'] );
//$("#box_detail").html(data_array["design"]);*/
}
},
dayClick: function(date, jsEvent, view) {
//alert(date.format());
var d = new Date(date._d);
var dia = d.getDate();
var mes = d.getMonth()+1;
var ano = d.getFullYear();
day=$(this).closest('.'+(view.type=='month'?'fc-row':'fc-time-grid')).find('.fc-bg td:eq('+$(this).closest('td').index()+')').data('date');
// if (checkDay.dia() == 6 || checkDay.dia() == 0) alert('Weekend!');
console.log(day);
//alert(day);
$(this).css('background-color', 'green');
$.ajax({
type: 'POST',
url: 'insert.php',
data: {dia : dia, mes : mes, ano : ano, iduser : iduser},
success: function(data){
alert(data);
}
});
}, //end dayclick
});
});
insert.php
<?php
include('connection.php');
$dia = mysqli_real_escape_string($conn, $_POST['dia']);
$mes = mysqli_real_escape_string($conn, $_POST['mes']);
$ano = mysqli_real_escape_string($conn, $_POST['ano']);
$iduser = mysqli_real_escape_string($conn, $_POST['iduser']);
if(empty($_POST['dia']) || empty($_POST['mes']) || empty($_POST['ano']) || empty($_POST['iduser'])){
echo"<script language='javascript' type='text/javascript'>alert('Erro!');</script>";
exit();
}
if(isset($_POST['dayClick'])) { // I know that this doesn't work, it's only to guide you
if(!empty($_POST['dia']) || !empty($_POST['mes']) || !empty($_POST['ano']) || !empty($_POST['iduser'])){
$query = "INSERT INTO `t_marcacoes` (dia, mes, ano, iduser) VALUES ('$dia','$mes','$ano','$iduser')";
$successok = mysqli_query($conn, $query);
}
}
header('Location:marcarsenhas.php');
?>
getdados.php (The php file where I do the Select)
<?php
//echo "entrei";
require_once('connection.php');
$dados = array();
$_POST["iduser"] = 5;
if(isset($_POST["iduser"]) ){
$iduser = $_POST["iduser"];
$query = "SELECT id, iduser, dia, mes, ano, ismarcado FROM t_marcacoes WHERE iduser = ".$iduser;
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)){
$dia=$row['dia'];
$mes=$row['mes'];
$ano=$row['ano'];
$date = date('Y-m-d', strtotime($ano.'-'.$mes.'-'.$dia));
$temp = array(
'start' => $date,
'end' => $date,
'overlap' => true,
'rendering' => 'background',
'color' => '#15a515',
'editable' => false
);
array_push($dados, $temp);
}
}
echo json_encode($dados);
?>

Related

PHP no results message still showing when posting data via ajax

I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.
This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $row["comment"];
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
}
}else{
$comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}
When the comment form is submitted it calls this function.
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
success: function (response) {
document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
$("#summernote").summernote("reset");
},
});
}else {
alert('Please enter a comment');
}
return false;
});
This is the post_comment.php page
if(isset($_POST['comment'])){
$comments = "";
$comment=$_POST['comment'];
$member_id =$_POST['member_id'];
$post_id =$_POST['post_id'];
if(isset($comment)) {
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = $entry_id
ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();
if ($stmt_result->num_rows > 0) {
while($row = $stmt_result->fetch_assoc()) {
$comment = $comment;
$comment_date = date_create($row['comment_date']);
$comment_date = date_format($comment_date, ' l jS F Y H:i');
$comment_author = $row["member_screen_name"];
$comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
echo $comments ;
};
exit;
}
}
}else {
header("location: /blog");
exit;
}
If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.
Try return the response from the server as json. Plus remove the exit and header on your server side.
<script type="text/javascript">
$('#submit').click(function (e) {
e.preventDefault();
if (!$('#summernote').summernote('isEmpty')) {
var comment = document.getElementById("summernote").value;
var member_id = 1;
var post_id = 1;
$.ajax ({
type: 'post',
url: 'post_comment.php',
data: {
comment:comment,
member_id:member_id,
post_id:post_id,
},
dataType : "json",
encode : true,
success: function (data) {
$.each(data, function(index, element){
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>");
});
$("#summernote").summernote("reset");
$('.alert').empty();
},
});
}else {
alert('Please enter a comment');
}
return false;
});
</script>
Then your server side.
<?php
if (isset($_POST['comment'])) {
$comment = $_POST['comment'];
$member_id = $_POST['member_id'];
$post_id = $_POST['post_id'];
$commentsArray = array();
$stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $post_id, $member_id, $comment);
$stmt->execute();
$entry_id = mysqli_insert_id($conn);
$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
FROM comments comm
JOIN members m
ON comm.member_id = m.id
WHERE comm.entry_id = ?
AND comm.id = ?
ORDER BY comm.comment_date DESC");
$sql->bind_param("ii", $post_id, $entry_id);
$sql->execute();
$sql_result = $sql->get_result();
if ($stmt_result->num_rows > 0) {
while ($row = $stmt_result->fetch_assoc()) {
$comment_date = date_create($row['comment_date']);
$commentsArray[] = array(
'comment' => $comment,
'post_date' = date_format($comment_date, ' l jS F Y H:i');
'comment_author' => $row['member_screen_name']
);
}
}
echo json_encode($commentsArray);
}
Also use the network tab on your browser console to see the response coming from the server.
it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.
update your code after the success
$('.alert-primary').hide()

Bootstrap Graph not rendered while using a dynamic query

The graph executes correctly when i use a static query. But when i use a dynamic query it doesnt render even when the query returned is same to the static query.
//$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
Here the commented code doesnot works but the other one works though they throw the same query when i checked on my console.
//code in pie.php
$("#submitgraph").click(function()
{
var graph_type=$("#graph_type").val();
var field_one=$("#field_type1").val();
var field_two=$("#field_type2").val();
$.ajax({
url: "http://localhost/ac/data/data.php?field1="+field_one+"&field2="+field_two,
type: "GET",
async: true,
success: function(response){
console.log(response);
setTimeout(function(){
if(graph_type=="piechart")
{
document.getElementById("pie_draw").style.display = "block";
}
}, 1000);
}
});
});
////code in data.php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `". $_GET["field2"] ."`, COUNT(*) as defectCount FROM `defects` GROUP BY `". $_GET["field2"] ."`";
//the commented code works
//$sql = "SELECT `user_13`, COUNT(*) as defectCount FROM `defects` GROUP BY `user_13`";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
echo json_encode($data);
?>
//code in data_a.js
//Flot Pie Chart
$(function() {
//var data ;
$.ajax({
url : "data/data.php",
type : "GET",
dataType: 'json',
success : function(data){
var datas = [];
for(i=0;i<data.length;i++) {
var obj = {
label : data[i].user_13,
data : data[i].defectCount
};
datas.push(obj);
}
var plotObj = $.plot($("#flot-pie-chart"), datas, {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
});
}
});
});
I Think one of the problem is that your ajax request type is
type : "POST"
in code in pie.php
but in your data.php your request type become GET
Try to change the
$_GET["field2"]
to
$_POST["field2"]
let me know if it works.

AJAX: am I inserting data correctly?

I read many of the similar threads here to see what I'm doing wrong, but my AJAX call seems correct. What am I missing here? No alert is popping up, so I assume it's the JS side.
$("#SignupSubmit").click(function()
{
var fName = $("#txtSignFName").val();
var lName = $("#txtSignLName").val();
var email = $("#txtSignEmail").val();
var pw = $("#txtPW").val();
if( fName == "" || lName == "" || email == "" || pw == "" )
{
alert();
}
else
{
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
fName:fName,
lName:lName,
email:email,
pw:pw
},
success: function(response) {
alert(response);
}
});
}
});
And the PHP (is this correct?):
<?php
require "../connectionPages/localConnect.php";
$fName = $_POST["fName"];
$lName = $_POST["lName"];
$email = $_POST["email"];
$pw = $_POST["pw"];
if($fName == null || $lName == null || $email == null || $pw == null)
$message = "missing required data";
else
{
$SQL = "INSERT INTO `customer/User` (custFName,
custLName,
custEmail,
custPassword)
VALUES ('$fName', '$lName','$email', '$pw')";
$mysqli->query($SQL);
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$SQL = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
$res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
json_encode($res);
}
else {
$message = "Unable to insert record: " . $mysqli->error;
}
$mysqli->close();
}
First phase update the below code in the data part.
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
And you are trying to get last inserted id. is it? if so use
$mysqli->insert_id;
instead of select query
Do this in AJAX
$.ajax({
type: "POST",
url: "actionPages/signUp.php",
dataType: 'json',
data: {
"fName":fName,
"lName":lName,
"email":email,
"pw":pw
},
success: function(response) {
var res=eval(response);
alert(res.id);
}
});
And in your PHP page. Do this:
if($mysqli->affected_rows > 0)
{
$message = "Record successfully inserted <br><a href='..'>Back to Main Page</a>";
$lastid = $mysqli->insert_id; /* $SQL = "SELECT max(custID) as ID FROM `customer/User`"; */
// $res = $mysqli->query($SQL) or trigger_error($mysqli->error."[$SQL]");
echo json_encode(array('id'=>$lastid));
}
I hope it helps

How to update only one field on a table with specific id

I have a table with multiple fields and i want to update only one when same ID.The code that im using to update is next
<?php
require('db.php');
mysql_query("SET NAMES 'utf8'");
date_default_timezone_set('UTC');
include("auth.php"); //include auth.php file on all secure pages
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$id=$_REQUEST['id'];
$query = "SELECT * from base where `id`='$id'";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$scantime = date("Y-m-d H:i:s");
$trn_date = date("Y-m-d H:i:s");
$id=$_REQUEST['id'];
$surname =$_REQUEST['surname'];
$name= $_REQUEST['name'];
$company_name=$_REQUEST['company_name'];
$firm= $_REQUEST['firm'];
$visitors= $_REQUEST['visitors'];
$barcode= $_REQUEST['barcode'];
$submittedby = $_SESSION["username"];
$update="update base set `scantime`='$scantime' where `id`='$id'";
mysql_query($update) or die(mysql_error());
}
?>
To search data i using ajax autocomplete function
require_once 'config.php';
mysql_query("SET NAMES 'utf8'");
if($_POST['type'] == 'country_table'){
$row_num = $_POST['row_num'];
$surname = $_POST['name_startsWith'];
$query = "SELECT custId,id,name, surname, company_name, firm,barcode,trn_date,scantime FROM base where UPPER(surname) LIKE '".strtoupper($surname)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['barcode'].'|'.$row['surname'].'|'.$row['name'].'|'.$row['company_name'].'|'.$row['firm'].'|'.$row['trn_date'].'|'.$row['scantime'].'|'.$row['id'].'|'.$row['custId'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
And to fill data to input fields
$('#barcodescanr').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'barcodescanr',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#name_1').val(names[2]);
$('#company_name_1').val(names[3]);
$('#surname_1').val(names[1]);
$('#firm_1').val(names[4]);
$('#info').val(names[5]);
$('#scanbartime').val(names[6]);
$('#Id').val(names[7]);
$('#custId').val(names[8]);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The problem that i have is that when i press submit to form it doesnt update scantime .
Thank you

What the url code can be write in the view file to call the function in Laravel Controller?

$('#calendar').fullCalendar({
events: JSON.parse(json_events),
//events: [{"id":"14","title":"New Event","start":"2015-01-24T16:00:00+04:00","allDay":false}],
utc: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
droppable: true,
slotDuration: '00:30:00',
eventReceive: function(event){
var title = event.title;
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&startdate='+start+'&zone='+zone,
type: 'POST',
dataType: 'json',
success: function(response){
event.id = response.eventid;
$('#calendar').fullCalendar('updateEvent',event);
},
error: function(e){
console.log(e.responseText);
}
});
$('#calendar').fullCalendar('updateEvent',event);
console.log(event);
},
This is the code that i found online about, i dont understand abou the url part .Because i am using the Laravel, i not sure what to write in the url part.
I have create a controller and model, just not sure how to pass the data into in and store in database.
This is the process.php can this transform into controller and model?
$type = $_POST['type'];
if($type == 'new')
{
$startdate = $_POST['startdate'].'+'.$_POST['zone'];
$title = $_POST['title'];
$insert = mysqli_query($con,"INSERT INTO calendar(`title`, `startdate`, `enddate`, `allDay`) VALUES('$title','$startdate','$startdate','false')");
$lastid = mysqli_insert_id($con);
echo json_encode(array('status'=>'success','eventid'=>$lastid));
}
if($type == 'changetitle')
{
$eventid = $_POST['eventid'];
$title = $_POST['title'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'resetdate')
{
$title = $_POST['title'];
$startdate = $_POST['start'];
$enddate = $_POST['end'];
$eventid = $_POST['eventid'];
$update = mysqli_query($con,"UPDATE calendar SET title='$title', startdate = '$startdate', enddate = '$enddate' where id='$eventid'");
if($update)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'remove')
{
$eventid = $_POST['eventid'];
$delete = mysqli_query($con,"DELETE FROM calendar where id='$eventid'");
if($delete)
echo json_encode(array('status'=>'success'));
else
echo json_encode(array('status'=>'failed'));
}
if($type == 'fetch')
{
$events = array();
$query = mysqli_query($con, "SELECT * FROM calendar");
while($fetch = mysqli_fetch_array($query,MYSQLI_ASSOC))
{
$e = array();
$e['id'] = $fetch['id'];
$e['title'] = $fetch['title'];
$e['start'] = $fetch['startdate'];
$e['end'] = $fetch['enddate'];
$allday = ($fetch['allDay'] == "true") ? true : false;
$e['allDay'] = $allday;
array_push($events, $e);
}
echo json_encode($events);
}
?>
Here is the my logic for Laravel.
routes.php
Route::get('/', function() {
return View::make('hello');
});
Route::get('calender', 'CalendarController#showEvent');
Route::post('calendar/add', 'CalendarController#postAdd');
Controller :
CalendarController.php
class CalendarController extends BaseController {
function showEvent() {
return View::make('display_event');
}
function postAdd() {
echo json_encode($_POST);
}
}
View Script: display_event.php
Download View : Click Here
Please compare html with
http://192.241.236.31/themes/preview/smartadmin/1.4.1/ajaxversion/#ajax/calendar.html (Ajax calender view)
View load by ajax :
http://192.241.236.31/themes/preview/smartadmin/1.4.1/ajaxversion/ajax/calendar.html
Hope this will work for You.
Just try it
Url :"<?php echo action('YourController#getIndex');?>",
You can Replace getIndex to any method you

Categories