没有错误时,我的页面不会刷新。
我用过:
window.location.reload(true);
当data.success
返回True时,假定将被执行。
我是PHP和AJAX的新手,所以我使用this作为指南。我知道如何处理信息到服务器,但我想在不离开页面的情况下显示消息。
PHP:
<?php
// connects to "ajax" database
mysql_connect("localhost", "root", "password");
mysql_select_db("ajax");
// assigns variables to fields
$name = $_POST['name'];
$email = $_POST['email'];
$superheroAlias = $_POST['superheroAlias'];
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['superheroAlias']))
$errors['superheroAlias'] = 'Superhero alias is required.';
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = @mysql_query($sql);
header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'superheroAlias' : $('input[name=superheroAlias]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true,
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if (!data.success) {
// handle errors for name ---------------
if (data.errors.name) {
$('#name-group').addClass('has-error'); // add the error class to show red input
$('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.superheroAlias) {
$('#superhero-group').addClass('has-error'); // add the error class to show red input
$('#superhero-group').append('<div class="help-block">' + data.errors.superheroAlias + '</div>'); // add the actual error message under our input
}
} else {
window.location.reload(true);
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
答案 0 :(得分:1)
您的代码中存在许多错误。首先,只有在出现错误时执行AJAX调用的原因是因为您在没有任何错误时重新定位页面。
header("location: /");
是你的罪魁祸首。您可以在输出任何JSON之前重新定位页面。其次,当成功的$ _POST传输时,您的$data
变量不包含[success]
密钥。因此,即使您不重新定位,您仍然不会输出任何有用的数据。 第三个,你从未保存过MySQL数据库的链接,只是实例化了它。此外,您还希望使用mysqli_
,因为mysql_
已被弃用。
将前两行代码更改为:
$link = new mysqli( "localhost", "root", "password", "ajax" );
将if-statement
更改为此:
if ( ! empty( $errors ) ) {
$data["errors"] = $errors;
$data["success"] = false;
} else {
$data["success"] = true;
$data["errors"] = $errors; // There are none, so this isn't neccessary
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$link->query( $sql );
}
顺便说一句,我希望这仅用于演示目的,因为这是一些可怕的验证/卫生。如果不是,这里有一些有用的链接:
http://www.phpro.org/tutorials/Validating-User-Input.html - 有关卫生/验证的深入教程 http://php.net/manual/en/book.mysqli.php - 您的MySQLi库指南。
答案 1 :(得分:0)
从其他部分的php文件中删除header("location: /");
。
我认为这会重定向页面,所以,你的回答并不像你想要的那样。
答案 2 :(得分:0)
Here If condition fails then check for $data in else and remove header from else.
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$sql = "INSERT INTO inputs SET name = '$name', email = '$email', alias = '$superheroAlias'";
$query = @mysql_query($sql);
$data['success'] = false;
//header("location: /");
}
// return all our data to an AJAX call
echo json_encode($data);