# Problem with form submission or ajax jQuery

**URL:** <https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705>\
**Category:** Need Help\
**Created:** [October 3, 2019, 6:07pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705 "2019-10-03T18:07:23Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 3, 2019, 6:07pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/1 "2019-10-03T18:07:23Z")

</div>

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!

 ![Captura%20de%20pantalla%20de%202019-10-03%2012-04-32](https://canada1.discourse-cdn.com/flex029/uploads/cakephp/original/2X/d/df12f2895aefc5cc3943a015c388dd6839b6266e.png)

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [October 3, 2019, 10:57pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/2 "2019-10-03T22:57:12Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 4, 2019, 12:32am UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/3 "2019-10-04T00:32:49Z")

</div>

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

 ![Captura%20de%20pantalla%20de%202019-10-03%2018-31-10](https://canada1.discourse-cdn.com/flex029/uploads/cakephp/original/2X/6/6f4dcbfe2c6222aef5a2232819387cb5e3c9b8a3.png)

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [October 4, 2019, 3:34pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/4 "2019-10-04T15:34:15Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 4, 2019, 3:49pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/5 "2019-10-04T15:49:21Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [October 4, 2019, 4:04pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/6 "2019-10-04T16:04:49Z")

</div>

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

> <https://stackoverflow.com/questions/5289078/parse-json-from-jquery-ajax-success-data>

---

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 4, 2019, 4:06pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/7 "2019-10-04T16:06:47Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 4, 2019, 6:38pm UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/8 "2019-10-04T18:38:46Z")

</div>

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](https://canada1.discourse-cdn.com/flex029/uploads/cakephp/original/2X/f/f8a4bd8199c6a5a8297e2e8b9aeb778ffb81b3a3.png)

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!

---

<div class="post-metadata">

**Author:** ![Zuluru](https://yyz1.discourse-cdn.com/flex029/user_avatar/discourse.cakephp.org/zuluru/32/1230_2.png) [@Zuluru](https://discourse.cakephp.org/u/Zuluru)\
**Post date:** [October 5, 2019, 3:44am UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/9 "2019-10-05T03:44:06Z")

</div>

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:

```auto
echo json_encode($response);

```

try

```auto
return $this->response->withStringBody(json_encode($response));

```

---

<div class="post-metadata">

**Author:** ![maxaval](https://avatars.discourse-cdn.com/v4/letter/m/e8c25b/32.png) [@maxaval](https://discourse.cakephp.org/u/maxaval)\
**Post date:** [October 5, 2019, 4:27am UTC](https://discourse.cakephp.org/t/problem-with-form-submission-or-ajax-jquery/6705/10 "2019-10-05T04:27:33Z")

</div>

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