-2

I've a double form with jQuery Validate, but when the ajax call its supposed to be done, I get a error, $.validate.submitHandrer on main.js.

My code is next:

'use strict';
var titulo;
var email;
var keyword;
var landing;
var keyword2;
var landing2;
var medio;
var extra;

$("#form_pedido").validate({
    rules: {
        titulo: {
            required: true
        },
        keyword: {
            required: true
        },
        landing: {
            required: true
        }
    }, //fin rules
    messages: {
        email: {
            remote: "Este correo no esta registrado."
        }
    },
    submitHandler: function () {
        //añadir aqui codigo ajax
        titulo = $('#titulo').val();
        email = $('#email').val();
        keyword = $('#keyword').val();
        landing = $('#landing').val();
        keyword2 = $('#keyword2').val();
        landing2 = $('#landing2').val();
        medio = $('#periodico').val();
        extra = $('#texto').val();
        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: 'php/crear_publi.php',
            data: {
                email: email,
                keyword: keyword,
                landing: landing2,
                keyword2: keyword2,
                landing2: landing2,
                medio: medio,
                extra: extra
            }
        });
    }
});

$("#formulario").validate({
    rules: {
        email: {
            required: true,
            minlength: 4,
            email: true,
            remote: "php/validar_email_db.php"
        },
    }, //fin rules
    messages: {
        email: {
            remote: "Este correo no esta registrado."
        }
    },
    submitHandler: function () {
        $("#validar").click(function () {
            $("#form_pedido").fadeIn("fast", function () {
                $("#formulario").fadeOut("slow", function () {

                });
            });
        });
    }
});

//cargar medios en el select
$.ajax({
    type: "POST",
    dataType: 'json',
    url: "php/listar_medios.php",
    async: false,
    success: function (data) {
        $('#periodico').empty();
        $.each(data, function () {
            $('#periodico').append(
            $('<option></option>').val(this.id_medio).html(this.nombre));
        });
    },
    complete: {}
});

jQuery.validator.addMethod("lettersonly", function (value, element) {
    return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Por favor, solo letras");

jQuery.validator.addMethod("spanishlettersspace", function (value, element) {
    return this.optional(element) || /^[a-zA-ZñÑáéíóúÁÉÍÓÚ\s]*$/i.test(value);
}, "Por favor, solo letras y espacios");

My php code, but I dont think this is the problem:

<?php
header('Access-Control-Allow-Origin: *');
/* Database connection information */
include("mysql.php" );
/*
 * AÑADIR MEDIOS!!!!
 */
function fatal_error($sErrorMessage = '') {
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error');
    die($sErrorMessage);
}
/*
 * MySQL connection
 */
if (!$gaSql['link'] = mysql_pconnect($gaSql['server'], $gaSql['user'], $gaSql['password'])) {
    fatal_error('Could not open connection to server');
}
if (!mysql_select_db($gaSql['db'], $gaSql['link'])) {
    fatal_error('Could not select database ');
}
mysql_query('SET names utf8');
/*
 * SQL queries
 * Get data to display
 */
$titulo = $_GET["titulo"];
$email = $_GET["email"];
$keyword = $_GET["keyword"];
$landing = $_GET["landing"];
$keyword2 = $_GET["keyword2"];
$landing2 = $_GET["landing2"];
$medio = $_GET["medio"];
$extra = $_GET["extra"];

$sql1 = "SELECT id_cliente
        FROM cliente
        where email1='".$email."'";

$res1 = mysql_query($sql1);
while($row1 = mysql_fetch_array($res1, MYSQL_ASSOC))
{
$id_cliente=$row1['id_cliente'];
}

$query1 = "insert into publirreportaje (titulo,fecha_inicio,fecha_modificacion,contenido,id_cliente,id_medio,tipo,palabraClave,url,palabraClave2,url2,infoExtra) values( 
             '". $titulo . "',
              NOW(),
              NOW(),
            '', 
              " .$id_cliente . ",
            " . $medio .",
            'publirreportaje',
            '".$keyword."',
            '".$landing."',
            '".$keyword2."',
            '".$landing2."',
            '".$extra."');" ;
 log($query1);
echo $query1;

$query_res1 = mysql_query($query1);
if($query_res1){

$sql = "SELECT id_contenido
        FROM publirreportaje
        where titulo='".$titulo."'";

$res = mysql_query($sql);
while($row = mysql_fetch_array($res, MYSQL_ASSOC))
{
$id_nuevo=$row['id_contenido'];
}
}
//echo "idenuevo =>  $id_nuevo";
for ($i=0;$i<count($editores);$i++)    
{     
//echo "<br> CLinicaid " . $i . ": " . $clinicas[$i];   
$query2 = "insert into publi_editor (id_publirreportaje,id_editor) values( 
             ". $id_nuevo . ", 
            " . $editores[$i] . ")" ;
//echo"$query1";
            $query_res2 = mysql_query($query2);
} 

if (!$query_res1||!$res||!$query_res2) {
   // $mensaje  = 'Error en la consulta de inserts: ' . mysql_error() . "\n";
   // $estado = mysql_errno();
    if (mysql_errno() == 1062) {
        $mensaje = "Imposible añadir el articulo, num articulo ya existe";
        $estado = mysql_errno();
    } else {
        $mensaje = 'Error en la consulta: ' . mysql_error() ;
        $estado = mysql_errno();
    }
}
else
{
    $mensaje = "Insercion correcta";
    $estado = 0;
}
$resultado = array();
 $resultado[] = array(
      'mensaje' => $mensaje,
      'estado' => $estado
   );
echo json_encode($resultado);
?>

Thanks everybody

Sparky
  • 98,165
  • 25
  • 199
  • 285
  • You code is vulnerable to [SQL-injection](http://stackoverflow.com/q/60174/2257664). – A.L Apr 14 '15 at 15:11
  • which browser you used? – shaN Apr 14 '15 at 15:14
  • there is one trailing `,` after closing `rules>email` in second form it will cause issues in IE – shaN Apr 14 '15 at 15:18
  • @shaN, only in VERY old versions of IE that nobody uses anymore... IE 7 and below. Otherwise, I agree that trailing commas are sloppy but the OP likely just stripped out some superfluous code for posting. – Sparky Apr 14 '15 at 15:21
  • 1
    So what is the exact error message?? It would also be ideal if you'd have taken the time to format your code for better readability. And where is the ***rendered*** HTML of these two forms? – Sparky Apr 14 '15 at 15:25
  • @Sparky sure it's, but i didnt post it for too much code :/ – Pablo Cacho Apr 14 '15 at 15:27
  • It's up to you to [make a **minimal** code example of the problem](http://stackoverflow.com/help/mcve). How are we supposed to find the mistake if we can't see it? See: http://stackoverflow.com/help/mcve – Sparky Apr 14 '15 at 15:28
  • @Sparky the exact error message is main.js:45 $.validate.submitHandler – Pablo Cacho Apr 14 '15 at 15:29
  • 1
    You never stated line 45 in your OP, but how exactly would we know which is line 45 inside your `main.js` file anyway? Your console would show you line numbers. You have to put more effort into asking the question. – Sparky Apr 14 '15 at 15:32
  • @shaN, I know you were just trying to help, but your edit changed the OP's code. Everyplace the OP had a `true`, your cleanup changed it into a `!0`. I'll have to roll the whole thing back and re-edit. – Sparky Apr 14 '15 at 15:50
  • @Sparky havent meant to cause any trouble, but `!0` is same as `true` right? – shaN Apr 14 '15 at 19:00
  • @shaN, yes, but who uses `!0` in place of `true`? Cleaning up the code does not mean changing it into something else. I simply used "tidyUp" within jsFiddle to fix indentations and spacing... not one character changed from the OP's original intent. – Sparky Apr 14 '15 at 19:20
  • @Sparky line 45 is the ajax call: $.ajax({.... – Pablo Cacho Apr 15 '15 at 07:20
  • Which `ajax` call? Your OP has three. Getting the requisite information from you should not be this difficult. Did you see my answer below? – Sparky Apr 15 '15 at 14:54

1 Answers1

1

You would absolutely never put a click handler inside the submitHandler function, and it's probably what's breaking things.

submitHandler: function() {
    $( "#validar" ).click(function() { // <- REMOVE
        $( "#form_pedido" ).fadeIn( "fast", function() {
            $( "#formulario" ).fadeOut( "slow", function() {

            });
        });
    });   // <- REMOVE     
}

How can the click handler fire when the submitHandler is already capturing the click of the submit button? The submitHandler fires when the submit button is clicked AND the form is valid. With that click handler, nothing inside your submitHandler is going to do anything but sit there.

Otherwise, without seeing any of the HTML of your two forms, it's impossible to determine what other errors you've made.


You do not need to manually gather the value of every field...

submitHandler: function() {
    //añadir aqui codigo ajax
    email = $('#email').val();
    ....
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'php/crear_publi.php',
        data: {
            email: email,
            .... 

        }
....

Simply pass the form argument into the submitHandler and use jQuery serialize()...

submitHandler: function(form) {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: 'php/crear_publi.php',
        data: $(form).serialize()
....
Sparky
  • 98,165
  • 25
  • 199
  • 285