Insert two records

4

I have a problem, adding a record saves it in duplicate in the following way:

actualPorcentaje 10 | marcaid 0
actualPorcentaje 0  | marcaid 4

This form allows me to update the prices through a percentage, after selecting a brand.

<form id="formProductos" 
      action="<?php echo base_url() ?> index.php/actualizacion/adicionar" method="post">

    <label for="">Porcentaje a actualizar</label>
    <input type="text" placeholder="Escriba el % de actualización" id="actualPorcentaje" name="actualPorcentaje"  />

</form> 

<?php

 echo '<a id="enviar" href="'.base_url().'index.php/actualizacion/adicionar/'.$marcaid.'"> Actualizar Precios</a>';  

?>


$(document).ready(function(){

    $("#enviar").click(function(event){ 

        $.ajax({
             type: "POST",
             data: $('#formProductos').serialize(),
             url: "<?php echo base_url();?>index.php/actualizacion/adicionar",
             dataType: 'json',
             success: function(data)
             {
                 if(data.result == true){
                     $('.results').html(data);
                 }                          
                 else{                          
                     alert('Ocurrió un error al agregar un producto.');                         
                 }
             }
        });
    });
});

Function to insert records in model.php

function add($table,$data){
    $this->db->insert($table, $data);

    if ($this->db->affected_rows() == '1') 
    { 
        return TRUE; 
    }
    return FALSE;
}  

Function to add records in controller.php

function adicionar(){ 
    $this->load->library('pagination'); 
    $config['base_url'] = base_url().'index.php/actualizacion/gerenciar/'; 
    $config['total_rows'] = $this->actualizacion_model->count('actualprecios'); 
    $config['per_page'] = 10; 
    $config['next_link'] = 'Próxima'; 
    $config['prev_link'] = 'Anterior'; 
    $config['full_tag_open'] = '<div class="pagination alternate"><ul>'; 
    $config['full_tag_close'] = '</ul></div>'; 
    $config['num_tag_open'] = '<li>'; 
    $config['num_tag_close'] = '</li>'; 
    $config['cur_tag_open'] = '<li><a style="color: #2D335B"><b>'; 
    $config['cur_tag_close'] = '</b></a></li>'; 
    $config['prev_tag_open'] = '<li>'; 
    $config['prev_tag_close'] = '</li>'; 
    $config['next_tag_open'] = '<li>'; 
    $config['next_tag_close'] = '</li>'; 
    $config['first_link'] = 'Primeira'; 
    $config['last_link'] = 'Última'; 
    $config['first_tag_open'] = '<li>'; 
    $config['first_tag_close'] = '</li>'; 
    $config['last_tag_open'] = '<li>'; 
    $config['last_tag_close'] = '</li>'; 

    $this->pagination->initialize($config);      
    $this->data['results'] = $this->actualizacion_model->get('actualprecios','idActualizacion, actualPorcentaje,actualFecha','',$config['per_page'],$this->uri->segment(3)); 

    $this->load->library('form_validation'); 
    $this->data['custom_error'] = '';  

    $marcaid = $this->uri->segment(3); 
    $this->data['productos'] = $this->actualizacion_model->getProductosById($marcaid); 

    $productos = $this->data['productos'];                                             
    $dataInicial = date("Y").'-'.date("m").'-'.date("d"); 
    $usuario = $this->session->userdata('logado'); 
    $actualPorcentaje = $this->input->post('actualPorcentaje'); 

    $data = array(                 
        'actualPorcentaje' => $actualPorcentaje , 
        'actualFecha' => $dataInicial, 
        'marcaid' => $marcaid, 
        'usuarioid' => $usuario,  
    ); 

    if ( is_numeric($id = $this->actualizacion_model->add('actualprecios', $data, true)) ) { 

        foreach ($productos as $p) { 
            $idProdutos = $p->idProdutos;         
            $precoVenda = $p->precoVenda; 
            $precioAnterior = $p->precoVenda; 
            $precoVenda = $precoVenda *(1 + $actualPorcentaje / 100); 
            $sql = "UPDATE produtos set precioAnterior = ?, precoVenda = ? WHERE idProdutos = ?"; 
            $this->db->query($sql, array($precioAnterior, $precoVenda, $idProdutos)); 
        } 
        $this->session->set_flashdata('success','El registro de Actualización de Precios se agregó correctamente!!!'); 
        redirect(base_url().'index.php/actualizacion/gerenciar/');      

    } else { 
        $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured.</p></div>'; 
    }         
    $this->data['view'] = 'actualizacionp/actualizacion'; 
    $this->load->view('tema/topo', $this->data); 
} 
    
asked by Maru 18.10.2016 в 01:03
source

4 answers

1

You must send everything in a single request.

I suggest:

<a href="#" id="enviar">Actualizar precios</a>

Then handle everything with javascript:

$(document).ready(function(){
  $("#enviar").click(function(event){ 
    event.preventDefault(); // para prevenir la recarga de página
    $.ajax({
      type: "POST",
      data: $('#formProductos').serialize(),
      url: "<?php echo base_url();?>index.php/actualizacion/adicionar/<?php echo $marcaid ?>",
      dataType: 'json',
      success: function(data) {
        if(data.result == true){
          $('.results').html(data);
        } else {                          
          alert('Ocurrió un error al agregar un producto.');                         
        }
      }
    });
  });
});
    
answered by 08.11.2016 в 15:51
0

The problem is that you are sending the request 2 times. Try to change

<?php
   echo '<a id="enviar" href="'.base_url().'index.php/actualizacion/adicionar/'.$marcaid.'"> Actualizar Precios</a>';  
?>

with

<?php
   echo '<a id="enviar" href="#"> Actualizar Precios</a>';  
?>

And on the other hand in your function of JS. In the first line add.

event.preventDefault()
    
answered by 18.10.2016 в 02:29
0

Well, this sends "marcaid"

<a id="enviar" href="'.base_url().'index.php/actualizacion/adicionar/'.$marcaid.'"> Actualizar Precios</a>'; 

and this sends "currentPercentage"

data: $('#formProductos').serialize(),

url: "<?php echo base_url();?>index.php/actualizacion/adicionar",

I tried to send the 2 variables in different ways from ajax but maybe I did not do it well

I also tried adding this to the form thinking that data: $ ('# formProductos'). serialize (), would cover the sending of both variables

<input type="text" id="marcaid" name="marcaid" value="<?php echo $marcaid; ?>" />

but it does not work.

    
answered by 20.10.2016 в 01:46
0

The problem is that you are sending 2 requests:

The first one is this:

<a id="enviar" href="'.base_url().'index.php/actualizacion/adicionar/'.$marcaid.'"> Actualizar Precios</a>'; 

And the second one is the event when clicking on the link:

$("#enviar").click(function(event){ 
        $.ajax({
             type: "POST",
             data: $('#formProductos').serialize(),
             url: "<?php echo base_url();?>index.php/actualizacion/adicionar",
             dataType: 'json',
             success: function(data)
             {
                 if(data.result == true){
                     $('.results').html(data);
                 }                          
                 else{                          
                     alert('Ocurrió un error al agregar un producto.');                         
                 }
             }
        });
    });

What I suggest is to remove the href from the link and leave it like this:

<a id="enviar" href="#"> Actualizar Precios</a>';

And the event like this:

$("#enviar").click(function(event){ 
        $.ajax({
             type: "POST",
             data: $('#formProductos').serialize(),
             url: "<?php echo base_url();?>index.php/actualizacion/adicionar/<?php echo $marcaid; ?>",
             dataType: 'json',
             success: function(data)
             {
                 if(data.result == true){
                     $('.results').html(data);
                 }                          
                 else{                          
                     alert('Ocurrió un error al agregar un producto.');                         
                 }
             }
        });
    });

I hope it helps you

    
answered by 13.04.2017 в 19:04