dongluolie3487 2014-07-26 06:00
浏览 391

AJAX成功后页面不刷新

My page doesn't refresh when there are no errors.

I used:

window.location.reload(true);

That is supposed to be executed when data.success returns True.

I'm new to PHP and AJAX, so I'm using this as a guide. I know how to process info to server, but I want to display messages without leaving the page.

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();
});

});
  • 写回答

2条回答 默认 最新

  • duanjianhe1388 2014-07-26 06:17
    关注

    remove header("location: /"); from your php file in else part. I think this will redirect page so, your response is not like you want.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧