I encountered this really strange issue where my php method is sending back a json response after successfully saving the record into the database but the response is being printed on the screen instead of going to the Ajax callback. This is causing it to fail the Ajax callback and the subsequent code. The same code with the same method signatures and responses is working for other classes but it’s failing for this instance.
This is the jQuery that is requesting for the post action:
$(document).ready(function() {
validateForm();
$('#addOrganisationForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
sendCreateOrganisationRequest(new FormData(this));
} else {
console.log('Form validation failed.');
}
});
});
function validateForm() {
$("#addOrganisationForm").validate({
rules: {
name: {
required: true,
},
websiteUrl: {
required: true,
url: true
},
description: {
required: true,
},
industry: {
required: true,
maxlength: 30
}
},
errorElement: "span",
errorClass: "text-danger",
});
}
function sendCreateOrganisationRequest(formData) {
console.log('Sending request...');
$.ajax({
url: '/organisations/create',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(response) {
if (response.success) {
console.log('Organisation created successfully!');
if (isAuthenticated) {
window.location.href = '/organisations/getAll';
} else {
alert('Organisation created successfully!');
$('#addOrganisationForm')[0].reset();
}
} else {
processErrors(response.error);
}
},
error: function(xhr, status, error) {
console.error('Failed request:', status, error);
let response = JSON.parse(xhr.responseText);
processErrors(response.error);
}
});
}
function processErrors(errors) {
console.log('Processing errors...', errors);
let errorMessages = {};
if (errors) {
if (errors.name) {
errorMessages.name = errors.name;
}
if (errors.website_url) {
errorMessages.websiteUrl = errors.website_url;
}
}
$('#addOrganisationForm').validate().showErrors(errorMessages);
}
This is the createOrganisation method:
public function createOrganisation(string $name, string $description, string $websiteUrl, string $industry): void
{
try {
$duplicates = $this->organisationMapper->checkDuplicate($name, $websiteUrl);
if (!empty($duplicates)) {
renderJson(['error' => $duplicates], 400);
return;
}
$organisation = new Organisation();
$organisation->setName($name);
$organisation->setDescription($description);
$organisation->setWebsiteUrl($websiteUrl);
$organisation->setIndustry($industry);
$organisationSaved = $this->organisationMapper->save($organisation);
renderJson(['success' => $organisationSaved], $organisationSaved ? 200 : 404) ;
} catch (Exception $e) {
renderJson($e->getMessage(), 500);
}
}
This is the route for handling the request.
$this->router->post('/organisations/create', function() {
$controller = new OrganisationController($this->pdo);
$controller->createOrganisation(
$_POST['name'],
$_POST['description'],
$_POST['websiteUrl'],
$_POST['industry']
);
});
I tried debugging using print_r and error_log statements and can’t find what is causing it to print the response instead of sending the response directly to the Ajax callback.
I also tried changing using if/else and variable assignment with explicit type checks in the controller method instead of ternary but didn’t change anything.
6