Это jQuery, который запрашивает действие публикации:
Код: Выделить всё
$(document).ready(function() {
validateForm();
$('#addOrganisationForm').on('submit', function(e) {
e.preventDefault();
if ($(this).valid()) {
const formData = {
name: $('#name').val(),
websiteUrl: $('#websiteUrl').val(),
description: $('#description').val(),
industry: $('#industry').val(),
};
sendCreateOrganisationRequest(formData);
} else {
console.log('Form validation failed.');
}
});
});
function sendCreateOrganisationRequest(formData) {
console.log('Sending request...');
$.ajax({
url: '/organisations/create',
type: 'POST',
contentType: false,
processData: false,
data: formData,
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);
}
});
}
Код: Выделить всё
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);
}
}
Код: Выделить всё
// Helper method to send json responses
function renderJson(array | string $data, int $statusCode): void
{
header('Content-Type: application/json');
http_response_code($statusCode);
echo json_encode($data);
}
Я также пробовал менять, используя if/else и присваивание переменных с явной проверкой типа в методе контроллера вместо троичного, но ничего не изменилось.>
Подробнее здесь: https://stackoverflow.com/questions/789 ... -to-screen