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">
<!--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']);
            $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);

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>
    <h4 class="modal-title" id="myModalLabel"><i class="fa fa-building"></i> Agregar Empresa</h4>

<!-- Modal Body -->
<div class="modal-body">
    <p class="statusMsg"></p>                    
    <?= $this->Form->create($empresa, ['type' => 'file']); ?>
            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']);

<!-- 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']) ?>
<?= $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(){
            async: true,
            cache: false,
            url: '/beepro/empresas/add',
            //dataType: 'json',
            beforeSend: function(xhr) {
            success: function(response) {
                //alert('Wow, Esto esta funcionando!');                
                if (response.success == true){
                    $.each(, 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);
            error: function(response) {
                alert('Ups, Esto no esta Funcionando ' + response.responseText.message);               

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!

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


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);


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!!!