I am trying to access some data in php file sent via jquery ajax method but I get an error of Undefined Index.
sender.php
$('#slot1').click(function(){
var selectedDate = $('#selectedDate').html();
var timeSlot = $('#timeSlot1').html();
var hm = timeSlot.slice(0, 5);
var seconds = ':00';
var time = hm seconds;
$.ajax({
url: 'insertBookings.php',
type: 'post',
data: {date: selectedDate, timeslot: time},
async: false,
success: function(data) {
alert(data);
}
})
})
reciver.php
<?php
$date = $_POST['date'];
echo date;
?>
CodePudding user response:
Consider testing with the following.
$('#slot1').click(function() {
var selectedDate = $('#selectedDate').text().trim();
var timeSlot = $('#timeSlot1').text().trim();
var selectedTime = timeSlot.slice(0, 5) ":00";
$.ajax({
url: 'insertBookings.php',
type: "POST",
data: {
"date": selectedDate,
"timeslot": selectedTime
},
async: false,
beforeSend: function() {
console.log("Sending Date: " selectedDate ", Time: " time);
},
success: function(data) {
console.log("Received: ", data);
},
error: function(xhr, status, error) {
console.log("Error:", status, error);
}
});
});
No major changes, yet I switched from .html()
to .text()
. The former will gather more than just the text if there is anything. Since you did not provide a Minimal, Reproducible Example, this is a precaution to ensure you're not capturing incorrect items before sending them.
I also added some extra Ajax code to help see each part as it happens.
In your PHP, you have a syntax error too. You are missing a $
before date
.
<?php
$date = $_POST['date'];
echo $date;
?>