I am trying to pass a value from an html table to a PHP controller through Ajax. I think the problem lies in my MVC structure, but not sure. I have previously used Ajax with no problems within a different structure, so I am pretty puzzled as to where the problem is exactly.
I am getting the value from the HTML table in my .js file like this and trying to pass it through ajax:
$(".courtBook").click(function() {
var $row = $(this).closest("tr"); // Find the row
var $time = $row.find(".courtTime").text(); // Find the text
console.log($time);
// var sLink = "index.php?page=booking&time="+$time;
// $.get(sLink, function(jData){
// alert($time);
// });
//$.post( "index.php?page=booking", { time: $time } );
$.ajax({
url: 'index.php?page=booking', //This is the current doc
type: 'POST',
data: {time: $time},
success: function(){
alert('Much success, such wow');
},
error: function(){
alert('Much wrong, such sad');
}
});
});
It grabs the right value, so that part is right. As you can see I have tried a couple of things. For now I am just trying to echo the value in the PHP to make sure the time variable is passed correctly, but nothing is showing. The php code looks like this:
if(isset($_POST['time'])){
echo "So far, so good";
$time = $_POST['time'];
echo $time;
}
This is the same file which include the view containing the html of the table. My controllers are all structured like this:
// including the model with the code for the database
include_once 'models/Booking_Table.class.php';
/* Passing information to and from the view */
// Include the view depending on the results from the database and return the view
$view = include_once 'views/booking-html.php';
return $view;
The views are php files with html in a return statement. My index is structured like this:
//load page model class definition
include_once "models/Page_Data.class.php";
//database connection
include "models/dbcon.php";
//create a new object
$pageData = new Page_Data();
//change default content - include navigation
$pageData->content = include_once"views/navigation.php";
//main navigation
$navIsClicked = isset( $_GET['page'] );
if ( $navIsClicked ) {
$controller = $_GET['page'];
} else {
//default controller
$controller = "home";
}
$pageData->content .= include_once "controllers/$controller.php";
$pageData->content .= include_once "views/footer.php";
//load the view
$pageAsHTML = include_once "views/page.php";
echo $pageAsHTML;
The reason I am including this is because I think the problem lies in the URL in the Ajax call. I have HTML forms on other pages that work just fine with the URL structure in the .js. For some reason it doesn't seem to be hitting the page in the Ajax.
Scripts, controllers, views etc. are all in their own folder in the root directory.
Can anyone tell me where I am going wrong or provide an alternative solution for passing a value from an HTML table to a PHP controller?