我最近开始学习表单提交的AJAX,但似乎我仍然缺少必要的东西,因为提交的数据不会像它想象的那样转到PHP文件。我不明白为什么它不会工作。
HTML:
<div class="col-md-6">
<form class="form" action="../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php">
Eesnimi:
<input name="eesnimi" id="eesnimi" class="required" type="text">
Perekonnanimi:
<input name="pernimi" id="pernimi" class="required" type="text">
E-Post:
<input name="email" id="email" class="required" type="email">
Telefoni number:
<input name="nr" id="nr" class="required" type="text">
Teema:
<input name="teema" id="teema" class="required" type="text">
Sõnumi sisu:
<textarea name="sisu" id="sisu" class="required"></textarea>
<div></div>
<input type="submit" id="sub" value="Edasta">
</form>
</div>
JQUERY / AJAX
$('#sub').click(function(){
$('.form').submit();
var eesnimi = $('#eesnimi').val();
var pernimi = $('#pernimi').val();
var email = $('#email').val();
var nr = $('#nr').val();
var teema = $('#teema').val();
var sisu = $('#sisu').val();
$('.form').validate({
rules:{
eesnimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
pernimi: {
required: true,
nowhitespace: true,
lettersonly: true
},
email: {
required: true,
email: true
},
nr: {
required: false,
integer: true
},
teema: {
required: true
},
sisu: {
required: true
}
},
messages:{
eesnimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
pernimi: {
required: valituhiErr,
nowhitespace: tuhikErr,
lettersonly: nonumbersErr
},
email: {
required: valituhiErr,
email: emailErr
},
nr: {
required: valituhiErr,
integer: onlynumbersErr
},
teema: {
required: valituhiErr,
},
sisu: {
required: valituhiErr,
}
},
submitHandler: function(){
$.ajax({
type: "POST",
url: "../wp-content/themes/tempo/cfgs/js/scrollmagic/contact.php",
data: $('.form').serialize(),
success: function (o) {
console.log(o);
}
});
}
});
return false;
});
PHP:
<?php
print_r($_POST);
?>
我只是在尝试,似乎验证工作正常,但提交功能不会,因为服务器不能从我的ajax请求中收到任何内容而且它不会显示任何内容在控制台上。
答案 0 :(得分:1)
试试这个:jquery
var data = {
eesnimi = $('#eesnimi').val();
pernimi = $('#pernimi').val();
email = $('#email').val();
nr = $('#nr').val();
teema = $('#teema').val();
sisu = $('#sisu').val();
};
$.ajax({
type : "post",
dataType : "JSON",
url : "register.php",
data : data,
success : function(result)
{
if (result.hasOwnProperty('error') && result.error == '1'){
var html = '';
$.each(result, function(key, item){
if (key != 'error'){
html += '<li>'+item+'</li>';
}
});
//show in html
PHP
eesnimi = $_POST['eesnimi']
pernimi = ...
email =...
nr = ...
teema = ...
sisu = ...
//connect db
//sqlquery you want validate
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
if ($row['eesnimi']==$eesnimi ){
$errors['eesnimi '] = ...;
}
// like this
if (count($errors) > 1){
$errors['error'] = 1;
die (json_encode($errors));
}
//insert into db
}
希望这个帮助