I have a Javascript form that makes a Post to a table to generate an invoice of products everything does a great job.
I need to validate that one of my data (the product code) is not already in my data to avoid double records when generating the invoice.
Could you help me?
Here the Code of the form:
$(document).ready(function(){
load(1);
});
function load(page){
var q= $("#q").val();
$("#loader").fadeIn('slow');
$.ajax({
url:'./ajax/productos_factura.php?action=ajax&page='+page+'&q='+q,
beforeSend: function(objeto){
$('#loader').html('<img src="./img/ajax-loader.gif"> Cargando...');
},
success:function(data){
$(".outer_div").html(data).fadeIn('slow');
$('#loader').html('');
}
})
}
function agregar (id)
{
var precio_venta=document.getElementById('precio_venta_'+id).value;
var cantidad=document.getElementById('cantidad_'+id).value;
//Inicia validacion
if (isNaN(cantidad))
{
alert('Esto no es un numero');
document.getElementById('cantidad_'+id).focus();
return false;
}
if (isNaN(precio_venta))
{
alert('Esto no es un numero');
document.getElementById('precio_venta_'+id).focus();
return false;
}
//Fin validacion
$.ajax({
type: "POST",
url: "./ajax/agregar_facturacion.php",
data: "id="+id+"&precio_venta="+precio_venta+"&cantidad="+cantidad,
beforeSend: function(objeto){
$("#resultados").html("Mensaje: Cargando...");
},
success: function(datos){
$("#resultados").html(datos);
}
});
}
function eliminar (id)
{
$.ajax({
type: "GET",
url: "./ajax/agregar_facturacion.php",
data: "id="+id,
beforeSend: function(objeto){
$("#resultados").html("Mensaje: Cargando...");
},
success: function(datos){
$("#resultados").html(datos);
}
});
}
$("#datos_factura").submit(function(){
var id_cliente = $("#id_cliente").val();
var id_vendedor = $("#id_vendedor").val();
var condiciones = $("#condiciones").val();
if (id_cliente==""){
alert("Debes seleccionar un cliente");
$("#nombre_cliente").focus();
return false;
}
VentanaCentrada('./pdf/documentos/factura_pdf.php?id_cliente='+id_cliente+'&id_vendedor='+id_vendedor+'&condiciones='+condiciones,'Factura','','1024','768','true');
});
$( "#guardar_cliente" ).submit(function( event ) {
$('#guardar_datos').attr("disabled", true);
var parametros = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax/nuevo_cliente.php",
data: parametros,
beforeSend: function(objeto){
$("#resultados_ajax").html("Mensaje: Cargando...");
},
success: function(datos){
$("#resultados_ajax").html(datos);
$('#guardar_datos').attr("disabled", false);
load(1);
}
});
event.preventDefault();
})
$( "#guardar_producto" ).submit(function( event ) {
$('#guardar_datos').attr("disabled", true);
var parametros = $(this).serialize();
$.ajax({
type: "POST",
url: "ajax/nuevo_producto.php",
data: parametros,
beforeSend: function(objeto){
$("#resultados_ajax_productos").html("Mensaje: Cargando...");
},
success: function(datos){
$("#resultados_ajax_productos").html(datos);
$('#guardar_datos').attr("disabled", false);
load(1);
}
});
event.preventDefault();
})
The data I take from this file in Ajax:
<?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/* Connect To Database*/
require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
// escaping, additionally removing everything that could be (html/javascript-) code
$q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
$aColumns = array('codigo_producto', 'nombre_producto');//Columnas de busqueda
$sTable = "products";
$sWhere = "";
if ( $_GET['q'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".$q."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
include 'pagination.php'; //incluyo archivo de paginacion
//variables de paginacion
$page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
$per_page = 5; //cuantoas regis
$adjacents = 4; //gap between pages after number of adjacents
$offset = ($page - 1) * $per_page;
//Count the total number of row in your table*/
$count_query = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable $sWhere");
$row= mysqli_fetch_array($count_query);
$numrows = $row['numrows'];
$total_pages = ceil($numrows/$per_page);
$reload = './index.php';
//main query to fetch the data
$sql="SELECT * FROM $sTable $sWhere LIMIT $offset,$per_page";
$query = mysqli_query($con, $sql);
//loop through fetched data
if ($numrows>0){
?>
<div class="table-responsive">
<table class="table">
<tr class="warning">
<th>Código</th>
<th>Producto</th>
<th><span class="pull-right">Cant.</span></th>
<th><span class="pull-right">Precio</span></th>
<th class='text-center' style="width: 36px;">Agregar</th>
</tr>
<?php
while ($row=mysqli_fetch_array($query)){
$id_producto=$row['id_producto'];
$codigo_producto=$row['codigo_producto'];
$nombre_producto=$row['nombre_producto'];
$precio_venta=$row["precio_producto"];
$precio_venta=number_format($precio_venta,2,'.','');
?>
<tr>
<td><?php echo $codigo_producto; ?></td>
<td><?php echo $nombre_producto; ?></td>
<td class='col-xs-1'>
<div class="pull-right">
<input type="text" class="form-control" style="text-align:right" id="cantidad_<?php echo $id_producto; ?>" value="1" >
</div></td>
<td class='col-xs-2'><div class="pull-right">
<input type="text" class="form-control" style="text-align:right" id="precio_venta_<?php echo $id_producto; ?>" value="<?php echo $precio_venta;?>" >
</div></td>
<td class='text-center'><a class='btn btn-info'href="#" onclick="agregar('<?php echo $id_producto ?>')"><i class="glyphicon glyphicon-plus"></i></a></td>
</tr>
<?php
}
?>
<tr>
<td colspan=5><span class="pull-right">
<?php
echo paginate($reload, $page, $total_pages, $adjacents);
?></span></td>
</tr>
</table>
</div>
<?php
}
}
? >