How can I connect and Store results into table? - javascript

I am using FullCalendar.io and have allowed users to be able to select an event and it posts successfully to the webpage. Below is the code for the calendar logic.
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'dayGrid', 'interaction' ],
//Behavior of calendar object
selectable: true,
selectMirror: true,
unselectAuto: true,
eventLimit: true,
header:
{
left: 'prevYear,prev',
center: 'title',
right: 'next,nextYear'
},
footer:
{
center: 'today'
},
//Logic for clicking on a date
dateClick: function(event_click)
{
var event_name = prompt("Enter a title for this event", "New Event");
//Add event to the calendar
calendar.addEvent({
title: event_name,
start: event_click.date,
allDay: true
});
},
//Logic for clicking on an event
eventClick: function(event_click)
{
alert(event_click.event.title + ' event removed'),
//Remove event from calendar
event_click.remove(),
calendar.render()
}
});
calendar.render();
});
I also have a php file that connects to a database and has an insert statement shown below.
<?php
$server_name = "localhost";
$username = 'root';
$password = 'root'
$db_name = 'testCalendardb';
$table_name = 'Event';
//Opens connection to the db
function openConn()
{
try {
$conn = new PDO("mysql:host=$server_name;dbname=$db_name", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to DB";
return $conn;
} catch(PDOException $exception) {
echo "Connection Failed: Error: ".$exception->getMessage();
}
}
function insert($date, $name) {
try {
$conn = openConn();
$sql = "INSERT INTO $table_name(date, name) VALUES (:date, :name)";
$sql->bindParam(':date', $date);
$sql->bindParam(':name', $name);
$conn->exec($sql);
echo "New Record Added";
} catch(PDOException $exception) {
echo $sql."<br>".$exception->getMessage();
}
}
//Closes the door
function closeConn($conn)
{
$conn = null;
}
?>
My problem is I am having great difficulty trying to store the events inside of the mysql database. I have looked at many tutorials online, and I have the foundation to do web development. I feel like I am missing a step to actually send the data to the database that I cannot find in any tutorial. The tutorials i do use are out of date and don't really apply to the up-to-date versions of mysql/php/js.
To summarize, How can i use my php script to insert events into my database?
I would appreciate any help.

It sounds like you'll want to create an AJAX script to send data to your php file.
Something like:
//jquery required for this approach
$.ajax({
url: 'add_events.php',
data: 'event_name='+ title+'&event_date='+ start2 +'&event_end='+ end2,
type: "POST"
});
Then in your php file you can add this to get the data stored in php variables:
$event_date = $_GET['event_date'];
$event_name = $_GET['event_name'];
Then your function becomes something like:
function insert() {
try {
$table_name = 'Event';
$conn = openConn();
$sql = "INSERT INTO $table_name(date, name) VALUES ($event_date, $event_name)";
$conn->execute($sql);
echo "New Record Added";
} catch(PDOException $exception) {
echo $sql."<br>".$exception->getMessage();
}
}
insert();
Hope this helps or helps get you on the right track.
*edited to include function calls and address typo and other issues pointed out by Dharman.
**Also
Looking over the javascript, it looks like you have code to delete an event as well. You will also need to add an ajax request to look up and delete the row for any created event.
I would recommend having the Event table structure to follow something like:
id, event_name, event_start, event_end, user_id
That way when you write the delete row function you'll have the information you'll need to delete the appropriate record.

You need to add at the end of the dataClick function in js file:
//AJAX function to comunicate to PHP script
$.ajax({
type: "POST",
url: your_url_php_script.php,
data: {name:event_name, date: event_click.date},
success: function (data) {
console.log(data);
},
dataType: json
});
Change a little the insert php function:
function insert($date, $name) {
try {
$conn = openConn();
$sql = "INSERT INTO $table_name(date, name) VALUES (:date, :name)";
$sql->bindParam(':date', $date);
$sql->bindParam(':name', $name);
$conn->exec($sql);
return "New Record Added";
} catch(PDOException $exception) {
return $sql."<br>".$exception->getMessage();
}
}
And also you need to add this to the end of your php script:
....
//Closes the door
function closeConn($conn)
{
$conn = null;
}
$name= $_POST['name'];
$date = $_POST['date'];
$query_result = insert($date, $name);
$result = array('name' => $_POST['name'], 'date' => $_POST['date'], 'message' =>$query_result);
//Always Return Encode the array into JSON for debuging
echo json_encode($result);
?>
This code isn't tested

Related

Deleting row on sql database with Javascript

I want to delete a row from my html page
I am using this function
function delete_row(no)
{
var row=document.getElementById("frm"+no).value;
var data= {};
data.row = row;
$.ajax({
url: 'delete_formation.php',
type: 'POST',
data: data,
success: function(output){
//alert(output);
}
});
document.getElementById("row"+no+"").outerHTML="";
}
My delete_formation.php contains a php script to delete that row in my sql database :
<?php
/* Connexion à une base MySQL avec l'invocation de pilote */
$pdo = 'mysql:dbname=TDW;host=127.0.0.1';
$user = 'root';
$password = '00000000';
try {
$pdo = new PDO($pdo, $user, $password);
} catch (PDOException $e) {
echo 'Connexion échouée : ' . $e->getMessage();
}
$d=$_POST['row'];
try {
// sql to delete a record
$sql = 'DELETE FROM Types_formation WHERE type_id="'.$d.'"';
echo $sql ;
// use exec() because no results are returned
$pdo->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}?>
This is not working, and it seems that my js script is not getting that text where id="frm1" (for exemple)
Using var row=document.getElementById("frm"+no).innerText;
instead of var row=document.getElementById("frm"+no).value; will solve this problem
I think you are pass value in ajax data variable and you get data $_post['row'] but you need $_post['data']['row'].
If this is not work than I will give full example.

Query result in the error response in the JQuery function

I have a problem, clicking in a < tr > of a table I call a javascript function which in turn calls a function in php to get data in a database. The click on the table row works, sql works, and from the console.log command I know there is an answer in reponseText. but it does not work and I get the error back, I'll post the code. I hope you can help me.
file config.php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
file cards.php
<?php
class card
{
private $_db;
function __construct($db){
$this->_db = $db;
}
public function view_card_id($id)
{
$rows = array();
$statement = $this->_db->prepare('SELECT * FROM card_details WHERE card_id = :card_id');
$statement->execute(array(':card_id' => $id));
$numrows = $statement->fetch(PDO::FETCH_ASSOC);
if($numrows < 1) {
$this->error = "Error";
return false;
} else {
$statement->bindColumn("card_id", $cid);
$statement->bindColumn("a", $a);
$statement->bindColumn("b", $b);
$rows[] = array('card_id' => $numrows['card_id'], 'a' => $numrows['a'], 'b' => $numrows['b']);
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$row = array('card_id' => $cid, 'a' => $a, 'b' => $b);
$rows[] = $row;
}
return $rows;
}
}
file index.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
?>
html code ....
<script src="/js/Cards.js" type="text/javascript"></script>
file Cards.js
$('#table-cards tr').click(function() {
var id = $(this).find("a").text();
$.ajax({
type: 'POST',
url: '/classes/cardsFunc.php',
dataType:'text',
data: {functionname: "view_card", id: id },
success: function(response){
//Use response
alert("Server echo: "+response);
console.log(response);
},
error: function(msg){
console.log(msg);
alert("Error: "+msg);
}
});
});
In the Cards.js file, once the $ .ajax function is called, it does not return to success but to error, but in the console.log I see the array of the executed query under the responseText entry.
that is, in the error response, I see the result of the query, which in theory should be in the response of success.
I also tried to use
$.post('/classes/cardsFunc.php', { functionname: 'view_card', id: id }, function(data){
});
but nothing
file cardsFunc.php
<?php
//include config
require_once($_SERVER['DOCUMENT_ROOT'].'config.php');
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>
thank you for the time you have dedicated to me
I noticed that if I recreate the connection to the db in the file cardsFunc.php, everything works, but I do not understand why, since everything is in the config.php file.
Like this:
file cardsFunc.php
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','');
define('DBNAME','toor');
try{
//create PDO connection
$db = new PDO("mysql:host=".DBHOST.";charset=utf8mb4;dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
//include the user card, pass in the database connection
include($_SERVER['DOCUMENT_ROOT'].'cards.php');
$card = new card($db);
if(isset($_POST['functionname']) && $_POST['functionname'] == "view_card"){
$card_view = $card->view_card_id($_POST['id']);
print json_encode($card_view);
}
?>

ajax works, but it doesn't insert into my sql query (js/php)

I don't understand if ajax work this way, but data doesn't add into my mysql database. I checked network tab in my chrome browser and found data has been forwarded.
I had tried like this way
script.js:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { "name": name, "time": time }
})
});
file.php:
<?php
require_once "connect.php";
$polaczenie = #new mysqli($host, $db_user, $db_password, $db_name);
$name = $_POST['name'];
$time = $_POST['time'];
if ($polaczenie->connect_errno != 0) {
echo "Error: " . $polaczenie->connect_errno;
} else {
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, $name, $time)")) {
echo "ok";
}
}
?>
First,you had better use PrepareStatement to pass parameter instead of writing them directly into your sql.
For your current code,try change to below code
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, '".$name."', '".$time."')")) {
echo "ok";
}
You should try like as below
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time } //Remove double quote
})
});

Ajax returns success but doesn't change the database

I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"&parameter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});

pass data from java script to php file in codeigniter

I had developed a event management system using javascript php and mysql. It works perfectly in plain php but now I need to migrate it into codeigniter and need some advice on how to pass the data from js to php while in codeigniter.
My front end java script function is like this
// event creating
dp.onTimeRangeSelected = function (args) {
var name = prompt("New event name:", "Event");
dp.clearSelection();
if (!name) return;
var e = new DayPilot.Event({
start: args.start,
end: args.end,
id: DayPilot.guid(),
resource: args.resource, //Change to classroom name
text: name //Change to event name
});
dp.events.add(e);
args.text = name;
DayPilot.request(
"backend_create.php",
function(req) { // success
var response = eval("(" + req.responseText + ")");
if (response && response.result) {
dp.message("Created: " + response.message);
}
},
args,
function(req) { // error
dp.message("Saving failed");
}
);
};
The php file handling the create function is like this
<?php
require_once '_db.php';
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource)";
$stmt = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
echo json_encode($response);
?>
Now on migrating to codeignitor I moved to segregated the backend_create.php file into model and controller and it looks like this.
The controller part
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class TimecalCon extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("Timecal_model");
}
public function insert()
{
$received = json_decode(file_get_contents('php://input'));
$start = $received->start;
$end = $received->end;
$resource = $received->resource;
$name = $received->text;
$this->Timecal_model->InsertDetails($name, $start, $end, $resource);
}
The Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Timecal_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function InsertDetails($name, $start, $end, $resource)
{
$insert = "INSERT INTO events (name, start, end, resource) VALUES (:name, :start, :end, :resource) ";
$query = $db->prepare($insert);
$stmt->bindParam(':start', $start);
$stmt->bindParam(':end', $end);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':resource', $resource);
$stmt->execute();
class Result {}
$response = new Result();
$response->result = 'OK';
$response->message = 'Created with id: '.$db->lastInsertId();
return json_encode($response);
}
The issue is when I change the javascript in the view page and use it like this
.....
DayPilot.request(
"TimecalCon/insert", .......
The functionality breaks and I am unable to insert events into the db. How should I be passing the data from js to the controller in this condition?
We can send the value from javascript to controller using Ajax. I have some code of mine which may help you.
function deleteEmp(empid){
var base_url = '<?php echo site_url(); ?>';
var r=confirm("Do You Really Want to Delete? ")
if (r==true)
{
objPost= new Object();
objPost.empid = empid;
$.ajax({
url:"employee_registration/deleteEmp?empid="+empid,
type:"POST",
data:objPost,
beforeSend:function(data){
},
error:function(data){
},
success:function(data){
alert(data);
result=JSON.parse(data);
alert(result);
if(result.status == 'success'){
alert('Deleted Successfully ');
window.location.reload();
return false;
}
}
});
}else{
return false;
}
}
As you can see I have pass the empid from my view to controller using ajax which gives me result back in variable. Which in this case is json.
Try this
DayPilot.request("<?php echo base_url().'TimecalCon/insert';?>",...)
You'll have to add "url" in "autoload.php" under config folder, then check if the url being loaded is the right one if not. Try modifying base_url() a bit like adding or removing the "index.php" part in the url.
Hope This helps

Categories

Resources