0

I'm doing validation with ajax, I'm starting with ajax now what is the problem:

  1. When i use a div like this <div id="success"></div>, my screen duplicates my original form but with ajax form...when i remove this div "success" everything is ok.

  2. When I need doing some validation in my form i call my function in ajax but it doesn't show me any message.

this is my form

add.ctp

<div id="success"></div>

<div class="form" >
<h3>Registro de Compra de Grano </h3>
<?php echo $this->Form->create('SoyaProductorCompra');?>
    <fieldset>
        <?php 

        echo $this->Form->input('proveedor_carnet', array('label' => 'Cantidad en tonelada(s) métrica(s) del producto  (TM)', 'id'=>'proveedor_carnet'));

        echo $this->Form->input('producto', array(
            'options' => array( 
                'GRANO DE SOYA' => 'Grano de Soya',
                'GRANO DE GIRASOL' => 'Grano de Girasol'
                ), 'label'=>'Tipo de Grano'
        ));

        echo $this->Form->input('toneladas', array('label' => 'Cantidad en tonelada(s) métrica(s) del producto  (TM)', 'id'=>'toneladas'));
        echo $this->Form->input('preciodolar', array(
            'label' => 'Precio en Dolares Americanos por tonelada métrica (TM / $us)',
            'style'=>'width:500px; height:30px;',
            'default'=>0));
        echo $this->Form->input('total', array('label' => 'Total en Dolares Americanos ($us)', 'default'=>0));
        echo $this->Form->input('nrofactura', array('label' => 'Numero Factura', 'style'=>'width:500px; height:30px;','id'=>'total'));        
    ?>

    <div id="sending" style="display:none;">
        <?php echo $this->html->image('ajax-loader.gif', array('alt' => 'Cargando...')); ?>
    </div>

    <?php
        echo $this->Js->submit('Agregar Existencia', array(
          'before'=>$this->Js->get('#sending')->effect('fadeIn'),
          'success'=>$this->Js->get('#sending')->effect('fadeOut'),
          'update'=>'#success'
          )); 
    ?>              
    </fieldset>
<?php echo $this->Form->end(); ?>
</div>

validation.js

here is mi second problem I'm trying that my function show me a message error after this

echo $this->Form->input('proveedor_carnet', array('label' => 'Cantidad en tonelada(s) métrica(s) del producto  (TM)', 'id'=>'proveedor_carnet'));

But my function doesn't show me any message

$(document).ready(function(){

    $('#proveedor_carnet').blur(function(){
        $.post(
            '/cake/soyaproductorcompras/validate_form',
            { field: $('#proveedor_carnet').attr('id'), value: $('#proveedor_carnet').val() },
            handleNmeValidation
            );
    });

    function handleNmeValidation(error){
        if(error.length > 0){
            if($('#proveedor_carnet-notempty').length == 0){
            $('proveedor_carnet').after('<div id="proveedor_carnet-notEmpty" class="error-message">' + error + '</div>');

            }
        }else{
            $('#proveedor_carnet-notEmpty').remove();
        }
    }
});

SoyaProductorComprasController.php

   public $helpers = array('Html', 'Form', 'Js');
    public function add()
    {
        $this->loadModel('SoyaProductorCompra');
        $this->loadModel('SoyaProveedor');
        $this->loadModel('Productora');
        $this->set('productores', $this->Productora->find('first', array('conditions' => array('user_id' =>  $this->Auth->user('id')))));
        $this->set('soyaproveedores', $this->SoyaProveedor->find('list', array(
            'fields' => array('id', 'nombre')
            )));
        if ($this->request->is('post')) {
        $this->request->data['SoyaProductorCompra']['user_id'] = $this->Auth->user('id');
        $this->request->data['SoyaProductorCompra']['soya_proveedor_id'] = $this->request->data['SoyaProductorCompra']['proveedor_carnet'];
            if ($this->SoyaProductorCompra->save($this->request->data)) {
                if($this->RequestHandler->isAjax()){
                    $this->render('success', 'ajax');
                }else{
                    $this->Session->setFlash(__('La Información no fue Guardada.'));  
                    return $this->redirect(array('action' => 'index'));
                }
            }
        }
    public function validate_form(){
    $this->loadModel('SoyaProductorCompra');
    if ($this->RequestHandler->isAjax()) {
        debug($this->data['SoyaProductorCompra'][$this->params['form']['field']]);
        $this->data['SoyaProductorCompra'][$this->params['form']['field']]=$this->params['form']['value'];
        $this->SoyaProductorCompra->set($this->data);
        if($this->SoyaProductorCompra->validate()){
            $this->autoRender = FALSE;
        }else{
            $error=$this->validateErrors($this->SoyaProductorCompra);
            $this->set('error', $error[$this->params['form']['field']]);
        }
    }
}

success.ctp

<p> Guardado </p>

validate_form.ctp

<?php echo $error; ?>

the error:

POST http://localhost:8080/cake/soyaproductorcompras/validate_form 500 (Internal Server Error) jquery2.1.js:4
n.ajaxTransport.k.cors.a.crossDomain.send jquery2.1.js:4
n.extend.ajax jquery2.1.js:4
n.each.n.(anonymous function) jquery2.1.js:4
(anonymous function) validation.js:4
n.event.dispatch jquery2.1.js:3
n.event.add.r.handle
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
CoolLife
  • 1,419
  • 4
  • 17
  • 43
  • Tip: don't use the js helper, write your own js, make it json based, not "put html result here" based. It should be obvious why 1.) is true - the result of the ajax call goes in the div #success - if the result is the same form again - the form will then be on the page twice. Actually same for 2.) your ajax layout probably does not do anything with the session flash method, so flash messages stay in the session and aren't displayed. – AD7six Jun 09 '14 at 14:53
  • yes I edit this part of #success because I was doing test the correctly is #proveedor_carnet – CoolLife Jun 09 '14 at 14:56
  • There's a lot of confusion there. `$('#proveedor_carnet').attr('id')` - that's the string `proveedor_carnet`. If you update `#proveedor_carnet` you're putting the result of the ajax call **in** the form i.e. you'll end up with `
    ......` - that's not going to work.
    – AD7six Jun 09 '14 at 14:59
  • I fix it. you can see I edit the question, and continue without work. – CoolLife Jun 09 '14 at 15:05
  • I spent the weekend doing test, and never reaches the function $('#name').blur(function(){ }); I put breakpoints with firebug and never activated – CoolLife Jun 09 '14 at 15:11
  • 1
    `POST ...validate_form 500 (Internal Server Error)` - the error message will be in the error log (and in the response, probably, but since there is no error handler it's not seen by any of the js) - you need to look for and read what the error was. It is not appropriate to have a question, have it answered, and then update the question with the next (unrelated) problem you're able to see. – AD7six Jun 09 '14 at 19:44
  • `I spent the weekend doing test, and never reaches the function $('#name').blur(function(){ });` - that code isn't in the question. Perhaps that gives you an idea why nobody reading the question can give you a specific answer to solve the problem *there is information missing from the question*. – AD7six Jun 09 '14 at 19:45
  • That's because he has made 9 edits to the original post already, adding/removing staff as answers were coming in. – user221931 Jun 09 '14 at 20:32
  • Good problems remain the same during these days I was doing testing and changing code that does not mean I started so, initially i was doing testing and changing a lot of code, but does not mean that the code started with easy to resolve errors like a #name (#name is the name of a field that I create to see if something print there, but just was a test) Now the error is mine to put bad code in question. – CoolLife Jun 09 '14 at 20:59
  • Please post the HTML your browser sees of your form. That's really what the client-side code (JS/jQuery) sees and that's where we'd like to focus in order to help you out. – PeterKA Jun 16 '14 at 13:12

1 Answers1

0

AD7six briefly explained what goes wrong in his comment, let me expand.

In your HTML you have

<div id="success"></div>
<div class="form" >[...]</div>

Then you create JS code that tells your browser to append in #success whatever it receives as a reply after posting the form.

When you post your form via ajax, the controller eventually tries to save with this

if ($this->SoyaProductorCompra->save($this->request->data)) {
    [...]
}

Your code ($this->render('success', 'ajax');) that tries to display success.ctp or the one later for the failure session message, is nested inside this if, which means it will only apply if the controller is able to save the data without problems. If it doesn't (like when there is a problem in saving the data) it won't enter the if and it won't do anything but exit, rendering the typical add.ctp as it would normally do every time it is not instructed otherwise.

Going back to your browser, it will receive some html to put inside your #success div as you instructed it to do, but it will be the whole page again (add.ctp), leaving you with a structure like:

<div id="success">
    <div id="success"></div>
    <div class="form" >[...]</div>
</div>
<div class="form" >[...]</div>

Subsequent posts will make things even worse because there are now duplicate html ids (like #success) which is bad.

Assuming you now understand what is wrong, your next problem is your ajax validation attempt. This is rather weirdly routed and I don't see any #name element in your code that will trigger your validation in the first place (which makes for why you never see validation errors - assuming everything else would work). Finally there is a debug() in your validation method which will confuse things more.

user221931
  • 1,852
  • 1
  • 13
  • 16
  • yeah I fix the success with this, and #name yes no exist so I change it, continue without work. I update in my question – CoolLife Jun 09 '14 at 18:30
  • 3
    We are here to help with your original problem - not do the actual programming for you. You keep changing the code and questions. Either start a new question specific to your new problem or hire a competent programmer to guide you through. I won't bother any longer, good luck. – user221931 Jun 09 '14 at 20:30
  • sorry man I undestand but this dont work continue the same problem and in this part of
    in this part I don't edit anything my screen duplicates my original form.
    – CoolLife Jun 09 '14 at 20:58