php - Getting html as response when posting form using ajax
My mistake should be easy to spot by a more experienced developer so here's hoping you can help me out.
I have a form created in a controller method:
public function manage_groups(
Request $request,
Globals $globals,
$_locale,
$_id
) {
// manage group logic omitted
// ...
$newPhoto = new Photo();
$photoForm = $this->createForm(PhotoType::class, $newPhoto, array(
'action' => $this->generateUrl('admin_upload_foto'),
'method' => 'POST'
));
// ...
return $this->render('admin/groups/manage_groups.html.twig', array(
'photoform' => $photoForm->createView()
// ...
));
}
The action url points to this controller method:
/**
* Matches /admin/upload/foto
* @Route(
* "/upload/foto",
* name="admin_upload_foto")
* @Method({"POST"})
* @return JsonResponse
*/
public function upload_photo(
Request $request
) {
$response = new JsonResponse();
$newPhoto = new Fotos();
$photoForm = $this->createForm(PhotoType::class, $newPhoto);
$photoForm->handleRequest($request);
if ($photoForm->isSubmitted() && $photoForm->isValid()) {
// $file stores the uploaded PDF file
$file = $newPhoto->getFile();
// Generate a unique name for the file before saving it
$fileName = md5(uniqid()).'.'.$file->guessExtension();
// Move the file to the directory where activity photos are stored
$file->move(
$this->getParameter('activity_photo_directory'),
$fileName
);
// Update the 'brochure' property to store the PDF file name
// instead of its contents
$newPhoto->setFile($this->getParameter('activity_photo_reletive_directory')."/".$fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($newPhoto);
$em->flush();
$response->setStatusCode(200);
$response->setContent(array("result" => 1, "newPhoto" => $newPhoto->getFile(), "category" => $newPhoto->getCategorie()));
} else if ($photoForm->isSubmitted()) {
$errors = array();
$errors[] = $photoForm['categorie']->getErrors();
$errors[] = $photoForm['file']->getErrors();
$response->setStatusCode(400);
$response->setContent(array("result" => 0, "errors" => $errors));
} else {
$response->setStatusCode(400);
$response->setContent(array("result" => 0, "errors" => "Het foto-formulier is niet verzonden naar de server"));
}
$response->headers->set('Content-Type', 'application/json');
return $response;
}
The page loads correctly and the form can be submitted using the following ajax:
dialogUploadPhoto.find('form').submit((event) => {
// const formData = new FormData();
// formData.append('photo-file', dialogUploadPhoto.find('input[type="file"]')[0].files[0]);
// formData.append('photo-categorie', $('photo-categorie').val());
const formData = new FormData(this);
// formData.append('photo-categorie', dialogUploadPhoto.find('photo-categorie').val());
// formData.append('photo-file', dialogUploadPhoto.find('input[type="file"]')[0].files[0]);
console.log(' >> >> >> Uploading image', formData);
event.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(), // formData,
cache: false,
success: function(response) {
console.log(' >> >> Upload successful: ', response);
dialogSelectPhoto.find("div:first-child").prepend(
'<a href="#" class="btn btn-default" ' +
'onclick="handleImageClick(\''+response.newPhoto+'\');">' +
'<img src="'+window.location.origin+'/'+response.newPhoto+'" width="250" height="auto" />' +
'</a>');
dialogUploadPhoto.dialog( "close" );
},
error: function (xhr, desc, err){
let errors = 'Unknown error occurred';
if (xhr.responseJSON.errors instanceof Array) {
errors = "<ul>";
if (xhr.responseJSON.errors[0]) {
errors += "<li>Categorie: " + xhr.responseJSON.errors[0] + "</li>";
}
if (xhr.responseJSON.errors[1]) {
errors += "<li>Foto: " + xhr.responseJSON.errors[1] + "</li>";
}
errors += "</ul>";
} else {
errors = xhr.responseJSON.errors;
}
dialogUploadPhotoError.find("#dialogUploadPhotoErrorMessage").html(errors);
dialogUploadPhotoError.dialog('open');
}
});
});
I've tried a couple of things, the ajax returns a success with the page in plain html but the controller method isn't called (breakpoint not hit)
As requested
Here is a screenshot of the tcp package response
What am I missing?
Answer
Solution:
I'm not sure but it looks like your ajax call goes to your function
manage_groups()
.In your ajax call :
It looks like your form comes from your manage_groups() function, so your call goes inside this function.
Try this :
Hope it will works