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,
) {
    // 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);

    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

        // Update the 'brochure' property to store the PDF file name
        // instead of its contents
        $em = $this->getDoctrine()->getManager();
        $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->setContent(array("result" => 0, "errors" => $errors));
    } else {
        $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);
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(), // formData,
            cache: false,
            success: function(response) {
                console.log(' >> >> Upload successful: ', response);

                    '<a href="#" class="btn btn-default" ' +
                    'onclick="handleImageClick(\''+response.newPhoto+'\');">' +
                    '<img src="'+window.location.origin+'/'+response.newPhoto+'" width="250" height="auto" />' +

                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;

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 enter image description here

What am I missing?




I'm not sure but it looks like your ajax call goes to your functionmanage_groups() .

In your ajax call :

url: $(this).attr('action'),

It looks like your form comes from your manage_groups() function, so your call goes inside this function.

Try this :

 url: "/upload/foto"

Hope it will works

People are also looking for solutions to the problem: php - Why I have value of 0 even i didn't put any values?


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.