Problem with form submission or ajax jQuery

I have an application in the CakePHP framework in its version 3.8.4 creating a modal with the form to add, with the following code:

In the index.ctp view I add this line at the start of file:

<!-- overlayed element -->
<div class="modal fade" id="dialogModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            
        </div>
    </div>
</div>
<!--End overlayed element-->

and in the add button it looks like this:

<?= $this->Html->link(__(''), ['controller' => 'empresas', 'action' => 'add'], ['class' => 'btn btn-success btn-sm fa fa-plus', 'data-toggle' => 'modal', 'data-target' => '#dialogModal', 'title' => 'Agregar Empresa']) ?>

and my controller like that

public function add()
{
    $empresa = $this->Empresas->newEntity();

    if ($this->request->is('post')) {
        $empresa = $this->Empresas->patchEntity($empresa, $this->request->getData());

        $empresa->usercreate = $this->Auth->user('username');
        
        if ($this->Empresas->save($empresa)) {
            $response['status']  = 'success';
            $response['message'] = __("La Empresa se guardo Correctamente!");
            $response['data']    = $this->request->getData();
            $response['id']      = $empresa->id;                
            $this->Flash->success(__('La Empresa se guardo correctamente!.'));
            echo json_encode($response);

            //return $this->redirect(['action' => 'index']);
        }else{
            $errors              = $empresa->errors();
            $response['status']  = 'error';
            $response['message'] = __("La Empresa no se guardo. Porfavor intente de Nuevo.");
            $response['data']    = compact('errors');                
            $this->Flash->error(__('La Empresa no se guardo. Porfavor intente de Nuevo.'));
            echo json_encode($response);
        }      
    }
    $this->set(compact('empresa'));
}

add form view this way (add.ctp)

<!-- Modal Header -->
<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal">
        <span aria-hidden="true">&times;</span>
        <span class="sr-only">Close</span>
    </button>
    <h4 class="modal-title" id="myModalLabel"><i class="fa fa-building"></i> Agregar Empresa</h4>
</div>

<!-- Modal Body -->
<div class="modal-body">
    <p class="statusMsg"></p>                    
    <?= $this->Form->create($empresa, ['type' => 'file']); ?>
        <fieldset>
            <?php
            echo $this->Form->control('nombre');
            echo $this->Form->control('licencia');
            echo $this->Form->control('fechaini');
            echo $this->Form->control('fechafin');
            echo $this->Form->control('photo', ['type' => 'file', 'class' => 'filestyle', 'data-buttonName' => 'btn-prymary', 'data-buttonText' => 'Examinar']);
            ?>
        </fieldset>             
</div>

<!-- Modal Footer -->
<div class="modal-footer">
    <?= $this->Form->button(__("Agregar"), ['class' => 'btn btn-success', 'onclick' => 'testajaxaddv3()']); ?>
    <?= $this->Form->button(__('Cerrar'), ['class' => 'btn btn-danger', 'data-dismiss' => 'modal']) ?>
</div>
<?= $this->Form->end() ?>

and in this same add the following script to the end of the file

<script type="text/javascript">
    /*
    sends the form to the controller, ensure form fields names match up 
    with escpected values.
    */
    function testajaxaddv3(){
   
        jQuery.ajax({
            type:'POST',
            async: true,
            cache: false,
            url: '/beepro/empresas/add',
            //dataType: 'json',
            data:jQuery('form').serialize(),
            beforeSend: function(xhr) {
                $(".error-message").remove();
                $(".has-error").removeClass('has-error');
            },
            success: function(response) {
                //success   
                console.log(response.success);
                //alert('Wow, Esto esta funcionando!');                
                if (response.success == true){
                    //console.log(response);
                    $("#dialogModal").hide();
                    location.reload()
                }else{
                    $.each(response.data, function(model, errors) {
                        for (var fieldName in this) {
                            var element = $("[name='"+fieldName+"']");
                            $.each(this[fieldName], function(label, text){
                                text_error = text ;
                            });
                            var create = $(document.createElement('span')).insertAfter(element);
                            create.addClass('error-message help-block').text(text_error);
                            create.parent().addClass('has-error');
                        }
                    });
                };               
            },
            error: function(response) {
                alert('Ups, Esto no esta Funcionando ' + response.responseText.message);               
                console.log(response);
            }
        });
    }
</script>

The problem is in the return of the ajax request since when I ask you to access the response object it returns undefined and does not enter the conditional that is within the success; I am a rookie in CakePHP and even more so in ajax and jQuery because this is my first attempt.

I would appreciate any possible help!

Instead of console.log(response.success);, what do you get if you just console.log(response);?

This is an image when I change console.log(response);

So, it seems (unsurprisingly) that response is not an object, but a JSON-encoded object. You’ll need to extract that before you can access the success property.

How can I do that? I’m apreciate any help!
Thank’s

Google ajax receive json data? Here’s one result for that which might be useful.

Than’s for you help, I try yo do it!

I have tried to use JSON.parse (response), but I have noticed that like what cakePHP returns in the response, the content of the form also comes and when this function arrives at the beginning of the form it gives an error, I do not know if this will have something that See the access to the JSON content that I receive from cakePHP.
I attached an image of the console to see if someone can help me with this issue

Captura%20de%20pantalla%20de%202019-10-04%2012-35-03

from the blue mark the form begins, or someone who can contribute an idea from the first code since the code keeps saving the record correctly!

You’re echoing your JSON output, but not returning, so the regular rendering still happens later in the process. Also, controllers should never directly output anything. Instead of:

echo json_encode($response);

try

return $this->response->withStringBody(json_encode($response));
1 Like

Thank’s Zuluru I change the code inti controller to
retiran $this->response->withStringBody(json_encode(responde));

And in the add.ctp adding
var responde = JSON.parse(response);

And done!!!