红酒泡绿茶 2015-09-15 17:45
浏览 118

Ajax提交的表单未保存到数据库中

I have a form with different inputs. On submit i use Ajax to send the data to a MySQL table. If the inputs are blank the jQuery validate plugin stops the submit action.

The POST submit works because i use Firebug and the response Ajax tells me that; but the data doesn't save in my database.

I don't know which part is causing the problem because in JS it doesn't tell me any issue.

My HTML/JS code looks like this:

$(document).ready(function() {
    $("#ok").hide();

    $("#formula").validate({
        rules: {
    nombre: {required: true},
    mail: {required: true},
    estado: {required: true},
    imagen: {required:true,
    extension:'jpeg|png|jpg|gif'},
    checa:{required:true}
        },
        messages: {
            nombre: "Debe introducir su nombre.",
            mail:"Introduce una dirección de e-mail válido.",
            estado : "Debes seleccionar tu estado donde resides.",
            imagen : "Selecciona una imagen válida, jpg, jpeg, png o gif.",
            checa: "Debes aceptar los terminos de uso y la política de privacidad"
        },
        submitHandler: function(form){
            var dataString = 'nombre='+ nombre
                        + 'mail=' + mail        
                        + '&estado=' + estado
                        + '&imagen=' + imagen
                        + '&checa=' + checa 
            $("#ok").show();
            $.ajax({
                type: "POST",
                url:"envia.php",
                data: dataString,
                success: function(msg){
                            $("#ok").html("<strong>Mensaje enviado existosamente, nos pondremos en contacto a la brevedad.</strong>");
                            document.getElementById("nombre").value="";
                            document.getElementById("mail").value="";
                            document.getElementById("estado").value="";
                            document.getElementById("imagen").value="";
                            document.getElementById("checa").value="";
                            setTimeout(function() {$('#ok').fadeOut('fast');}, 3000);
                }
            });
        }
    });
});
<section class="wrapper">

    <form method="post" name="formulario" id="formula" enctype="multipart/form-data">
        <div id="ok"></div>
        <label>Nombre:</label>
        <input type="text"  name="nombre" id="nombre" />
        <label>Email:</label>
        <input type="email" name="mail" id="mail" />
        <label>Estado:</label>
        <!--<div class="styled-select">-->
        <select name="estado" id="estado">
            <option value="">Selecciona tu estado:</option>
            <option>Aguascalientes</option>
            <option>Baja California</option>
            <option>Baja California Sur</option>
            <option>Campeche</option>
            <option>Chiapas</option>
            <option>Chihuahua</option>
            <option>Coahuila</option>
            <option>Colima</option>
            <option>Distrito Federal</option>
            <option>Durango</option>
            <option>Guanajuato</option>
            <option>Guerrero</option>
            <option>Hidalgo</option>
            <option>Jalisco</option>
            <option>México</option>
            <option>Michoacán</option>
            <option>Morelos</option>
            <option>Nayarit</option>
            <option>Nuevo León</option>
            <option>Oaxaca</option>
            <option>Puebla</option>
            <option>Querétaro</option>
            <option>Quintana Roo</option>
            <option>San Luis Potosí</option>
            <option>Sinaloa</option>
            <option>Sonora</option>
            <option>Tabasco</option>
            <option>Tamaulipas</option>
            <option>Tlaxcala</option>
            <option>Veracruz</option>
            <option>Yucatán</option>
            <option>Zacatecas</option>
        </select>
       <!--</div>
       <div id="file">Chose file</div>-->
        <input type="file" name="imagen" id="imagen" class="upload" />
        <input type="checkbox" name="checa" id="checa" value="Acepto">Acepto los terminos y condiciones y la politica de privacidad

    <input name="URLBack" type="hidden" id="URLBack" value="<?php echo "hhtp://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; ?>" />
    <input name="input" id="enviar" type="submit" value="Enviar" />
    </form>
</section>

And my PHP file looks like this:

include 'conexion.php';
$con = conexion();

$nombre=substr($_POST['nombre'],0,2);
$sql= "SELECT MAX(id) FROM base_de_datos";
  $rs=mysql_query($sql);
  if(isset($rs) && mysql_num_rows($rs)>0)
  {
      $row=mysql_fetch_row($rs);
      $num=$row;
      mysql_free_result($rs);     
   }

$tumb = implode($num); 

$sumando = $tumb + 1;   

if ($_FILES["imagen"]["error"] > 0){
    echo "ha ocurrido un error";
} else {
    $permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
    $limite_kb = 2000;

    if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 2048){

        $ruta = "imagenes/" . $_FILES['imagen']['name'];

        if (file_exists($ruta)){

            echo $_FILES['imagen']['name'] . ", este archivo existe";
        }
            else{
                $temp = explode(".", $_FILES["imagen"]["name"]);
                $newfilename = 'contest'. $sumando . '.' . end($temp);
                move_uploaded_file($_FILES["imagen"]["tmp_name"], "imagenes/" . $newfilename);
            } 
        }

}

$caracteres = "AABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
$numerodeletras=10;
$cadena = "";
for($i=0;$i<$numerodeletras;$i++)
{
    $cadena .= substr($caracteres,rand(0,strlen($caracteres)),1); 
}

$serie=$nombre.$sumando;
$este= date("Y/m/d");
echo $serie;

$_GRABAR_SQL = "INSERT INTO base_de_datos (nombre,email,estado,imagen,condiciones_de_uso,clave,fecha) VALUES ('$_POST[nombre]','$_POST[mail]','$_POST[estado]','$newfilename','$_POST[checa]','$serie','$este')";
mysql_query($_GRABAR_SQL);

$query=mysql_insert_id();

$headers  = "MIME-Version: 1.0 
";
$headers .= "Content-type: text/html; charset=utf-8  
";
$headers .= "Return-Path: ".$_POST['nombre']." <".$_POST['mail'].">  
";
$headers .= "From: OMA Plaza <noreply@example.com>  
";
$headers .= "Reply-To: ".$_POST['nombre']." <".$_POST['nombre'].">  
";
$headers .= "X-Priority: 1
"; 
$mail = mysql_real_escape_string($_POST['mail']);
if ( function_exists( 'mail' ) )
{
    echo 'mail() is available';
}
else
{
    echo 'mail() has been disabled';
}
$asunto = "";
$confir = "Su mensaje fue enviado exitosamente, nos pondremos en contacto con usted a la brevedad";
$mensage = "---------------------------------- 
";
    $mensage.= "            Contacto               
";
    $mensage.= "---------------------------------- 
";
    $mensage.= "Nombre:   ".$_POST['nombre']."
";
    $mensage.= "Clave Confirmación:    ".$serie."
";
    $mensage.= "Email: ".$_POST['mail']."
"; 

          mail ($mail, $asunto, $mensage, $headers);
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 微信会员卡等级和折扣规则
    • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
    • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
    • ¥15 gdf格式的脑电数据如何处理matlab
    • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
    • ¥100 监控抖音用户作品更新可以微信公众号提醒
    • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
    • ¥70 2048小游戏毕设项目
    • ¥20 mysql架构,按照姓名分表
    • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分