I'm working on an assignment for my Web Engineering class and I'm using jQuery to make an AJAX request to my PHP file using POST. The assignment requires that "each time the [submit] button is pressed the form information must be displayed in a display portion of the same web page without reloading the page" which is why I'm using the AJAX request, but every time I try to make the AJAX request it just opens my PHP file instead up giving me a response like it's supposed to. I've looked at every resource I can find on the internet and nothing is helping me.
My javascript:
function submit() {
$.ajax({
type: "POST",
url: "assign13.php",
data: $('#registration_form').serialize(),
dataType: "json",
success: function(data) {
var jsonResponseObj = JSON.parse(data);
var table_item = document.getElementById("schedule_items");
var string = "";
for (var i = 0; i < jsonResponseObj.length; i++) {
string +=
("<tr><td>" + jsonResponseObj[i].studName0 + (jsonResponseObj[i].hasOwnProperty('studName1') ? " and " + obj[i].studName1 : "") +
"</td><td>" + jsonResponseObj[i].location +
"</td><td>" + jsonResponseObj[i].time +
"</td><td>" + jsonResponseObj[i].performace +
"</td></tr>");
}
$("#schedule_items").html(string);
}
});
}
(#schedule_items refers to tbody of a table)
Can someone please tell me what I'm doing wrong because I have no idea.
Edit: I'm not using a input type="submit", I'm using a regular button with onclick="submit()".
Also, my PHP was requested (I'm still new, so I'm sure it could look a lot better):
class festSched {
public $studName0;
public $studName1;
public $location;
public $time;
public $performance;
}
$filename = "./data/fest_sched.json"; // storing my data as a json cause I like json
$file = fopen($filename, "w+");
$sched_json = file_get_contents($filename, true); // read the whole file into a string
$schedule = json_decode($sched_json, true);
if ($schedule == NULL) {
$schedule = Array();
}
$new_entry = new festSched();
$new_entry->studName0 = $_POST['first_name'] . " " . $_POST['last_name'];
if ($_POST['performance'] == "duet") {
$new_entry->studName1 = $_POST['first_name_2'] . " " . $_POST['last_name_2'];
}
$new_entry->location = $_POST['location'] . " Room " . $_POST['room'];
$new_entry->time = $_POST['time_slot'];
$new_entry->performance = $_POST['performance'] . " for " . $_POST['skill'] . " " . $_POST['instrument'];
array_push($schedule, $new_entry);
fwrite($file, json_encode($schedule));
fclose($file);
$str = json_encode($schedule);
echo $str;