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
Related
I am trying to access a database and delete a review of a user, I have a method that I pass the user's ID and the ID of the review. This method functions properly using both the SQL command as well as when I call hard-coded variables, however, when I pass the code via AJAX my code says it completed successfully but does not actually do anything. Is there something special about the variables that are passed via AJAX?
This is my method:
public function deleteRating($userid, $reviewID)
{
echo "this is idUsers(IdUsers) = ".$userid." this is reviewID (ID)".$reviewID;
$conn = $this->connect("ratings");
$sql = "DELETE FROM ratedmovies WHERE IdUsers=? AND ID=?";
if(!$stmt = $conn->prepare($sql))
{
echo "False";
}
else
{
$stmt->bind_param("ss", $userid, $reviewId);
if(!$stmt->execute())
{
echo "Failed to delete";
}
else
{
echo "Sucessfull Deletion";
}
}
}
This is the code that calls the method:
<?php
session_start();
include "../Model/Includes/autoLoadCont.inc.php";
$reviews = new Review;
$ratingID = json_decode($_POST['ratingID']);
$user = $_SESSION['userId'];
$reviews->deleteRating($user, $ratingID);
?>
and this is the ajax that calls that function:
var deleteBtns = document.querySelectorAll(".deleteRating");
deleteBtns.forEach(function(button)
{
button.addEventListener("click" , function()
{
$.ajax({
type: "POST",
url: "Controller/deleteReview.php",
data: {ratingID:button.id},
success: function(result)
{
alert(result);
}
});
});
button.id;
});
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
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);
}
?>
I have a form that submits an ajax call to the controller file below which has a function defined in another file "processes.php" [that I've included]. The challenge is receiving the json response; the browser expects to find it in the controller yet it's generated within the function. How can I retrieve the response from the function and make it readable from the controller [outside its functions] so that the response can be read by the browser?
controller.php
<?php
session_start();
$_SESSION['postdata'] = $_POST;
require "constants.php";
$file = $_SESSION["Form"].".php";
require $file;
if( isset($_POST["Save"]) ){
save_record($connection);
}
process.php
<?php
$_POST = $_SESSION['postdata'];
function save_record($connection){
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
$name = mysqli_real_escape_string($connection, $_POST["name"]);
$strQuery = "INSERT INTO names (name) VALUES ('$name')";
$result = mysqli_query($connection, $strQuery); //or exit("Error in query execution attempt!");
if($result){
$data['success'] = true;
$data['message'] = 'Success!';
}
else{
$errors['errorinexecute'] = "Error in query execution attempt!";
}
mysqli_close($connection);
unset($_SESSION["postdata"]);
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else{
$data['success'] = true;
$data['errors'] = $errors;
}
// return all our data to an AJAX call
echo json_encode($data);
}
?>
You can't use:
if( isset($_POST["Save"]) ){
save_record($connection);
}
when doing AJAX, so what I did is pass the button id into the JavaScript function like so:
onclick="saveInfo(this.id)"
The button id shows whether it's a "Delete", "Save", "Edit" request and so on and then from there the PHP file can read like this:
if( $buttonId == "Save" ){
save_record($connection);
}
I came across weird problem with my site only after uploaded it to the live server. In localhost I've no issue with these.
The problem is for login and register function. Let me talk about login first.
I keyed in the credentials and found that the page is called in the f12 network tab.However that page doesn't retrieve any data! So I put aside this jquery/ajax for a while and manually checked the php pages if they return any data but still they don't.
Now the flow like this:
login form filled up by user-> ajax request from php script-> php request from class file and return to ajax -> ajax give access to admin dashboard.
Now as I told you, I excluded ajax request and only checked with php and class file. Again it doesn't return anything from the class file to the php script though I only echoed "something"! Its not even go through any function!
Then I omitted, class file, checked the php script with ajax file.I only echo "wexckdsewndxw" and changed tha datatype in ajax to 'text'..still it doesn't get any value!
So in conclusion, data between pages are not passed at all! SO I suspect its something to do with crossDomain issue as mentioned here:
How does Access-Control-Allow-Origin header work?
But not sure how this works and how I should alter my code.
My code for reference:
login-user.js
/*login user*/
<!--login form submission starts-->
$("document").ready(function(){
$("#login-user").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "login-this-user.php",
data: data,
success: function(data) {
alert(data);
console.log(data);
var i;
for (i = 0; i < data.length; i++)
{
console.log(data[i].email);
console.log(data[i].activate);
console.log(data[i].status);
if($.trim(data[i].status)=='0')
{
//alert("not verified");
$('.invalid-popup-link').trigger('click');
}else
{
//alert("verified");
location.replace("admin/dashboard.php");
}
}//end for
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
return false;
});
});
<!--login form submission ends-->
login-this-user.php
<?php
session_start();
include('config.php');
include('class.login.php');
$return = $_POST;
//$return ='{"email":"admin#gmail.com","pass":"admin","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$status = $login->checkLogin2($data["email"],$data["pass"]);
$_SESSION['user_id']=$status;
$login = new checkLogin();
$profile = $login->check_profile($data["email"]);
$activated_id=array();
foreach($profile as $k=>$v){
array_push($activated_id,array("email"=>$v['email'],"activate"=>$v['activate'],"status"=>'0'));
$_SESSION['email'] = $v['email'];
$_SESSION['activated_id'] = $v['activate'];
}
//header('Content-Type: application/json');
echo json_encode($activated_id);
?>
class
<?php
session_start();
?>
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin2($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT * FROM authsessions WHERE email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
$salt=$row['salt'];
$hashAndSalt=$row['hashpword'];
$user_id=$row['UUID'];
}
if (password_verify($this->password, $hashAndSalt)==true) {
$status = "verified";
$_SESSION['user_id'] =$user_id;
$_SESSION['logged_in']=1;
}else
{
$status = "not verified";
$_SESSION['user_id'] =0;
$_SESSION['logged_in']=0;
}
return $_SESSION['user_id'] = 1;
}
public function check_profile($param)
{
$this->email = $param;
$sql="SELECT * FROM authsessions WHERE email = '{$this->email}'";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$profile=array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$profile[] = $row;
}
return $profile;
}
}
?>