使用php中的AJAX在警告框后刷新页面

时间:2017-05-18 01:07:11

标签: php html ajax

我在我的php脚本中进行表单验证,以一列为例,如果未填写用户名,则会弹出一个警告窗口并说出"请输入您的用户名" ,用户点击"确定"后,整个页面刷新,但表格上的信息也将被重置。

所以我想在刷新页面后保留用户输入的内容,如何使用AJAX将代码嵌入到php中?

        //username validation            
        if (empty($username)) {
        $error = true;
        echo '<script language="javascript">';
        echo 'alert("Please enter your username")';
        echo '</script>';
        //refresh the page
        header("Refresh:0; url=register.php");

该网站是在php文件中,html代码是嵌入在php下的东西,这是html中的表单

                <div id="account">
                 <form method="POST">
                    <p><span class="error">* required field.</span></p>
                    Username: 
                    <input type="text" name="Username">
                    <span class="error">* </span><br>
                    <!--other fields..-->
                    <input type="reset" value="Reset">
                    <input type="submit" value="Submit" name="signup_button">   
                </form>
            </div>

4 个答案:

答案 0 :(得分:0)

class firstviewcontroller: UIViewController{
    var photos2: [ImageSource]?
    @IBOutlet weak var Label: UIlabel!
    @IBOutlet weak var Image: UIImage!
}

class alertviewcontroller: UIViewController{
    @IBAction func Save(_ sender: Any) {
        dismiss(animated: true, completion: nil)
        let storyboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
        let firstViewController: firstviewcontroller = storyboard.instantiateViewController(withIdentifier: "firstviewcontroller") as! firstviewcontroller

        if let image = firstViewController.Image { 
            imageview.image = image
        }
        if let label = firstViewController.Label {
            label.text = Label.text
        }
    }
}

...或

<?php
if(isset($_POST['signup_button'])){
  $Username = $_POST['Username'];
}
?>

(或使用localStorage,而不是window。https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

然后,当页面加载时,检查是否(&#39;窗口。&#39; + VarYouWantToKeep)

如果有,请将其设置为值=&#34;&#34;对应的表单字段

答案 1 :(得分:0)

试试这个(考虑到你将$ username设置为$ _POST [“Username”];)

import matplotlib.pyplot as plt
import numpy as np

# List of subplot's description
description = ['''Lorem ipsum dolor sit amet, consectetur adipisicing elit,
    sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''','''
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. ''', '''Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
    pariatur.''',''' Excepteur sint occaecat cupidatat non proident, sunt in
    culpa qui officia deserunt mollit anim id est laborum.''']

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

# Four axes, returned as a 2-d array
f, axarr = plt.subplots(2, 2)
axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Title One')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Title Two')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Title Three')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Title Four')
# Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)
# Adjusting height between subplots and adding bottom space
plt.subplots_adjust(hspace = .4, bottom = .2)
# Print position and adding description manually
x0, y0 = axarr[0,0].get_position().x0, axarr[0,0].get_position().y0
f.text(x0,y0-.05,description[0])
x0, y0 = axarr[0,1].get_position().x0, axarr[0,1].get_position().y0
f.text(x0,y0-.05,description[1])
x0, y0 = axarr[1,0].get_position().x0, axarr[1,0].get_position().y0
f.text(x0,y0-.05,description[2])
x0, y0 = axarr[1,1].get_position().x0, axarr[1,1].get_position().y0
f.text(x0,y0-.05,description[3])

plt.show()

答案 2 :(得分:0)

要存储变量数据,您需要在PHP中使用$_SESSION变量。确保session_start()位于PHP页面的顶部。

这是一个基本的例子:

//this PHP page contains the HTML form
<form>
  <input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>

//ajax
$.ajax({
  url:'validate.php',
  type:'POST',
  data:{name:inputName}
 }).done(function(data){
  alert(data);
});

//php page
session_start();

if(!isset($_POST['name'])){
  //set session variable
  $_SESSION['email'] = $_POST['email'];
  //this will be sent back to PHP page with HTML
  echo 'Please enter username';
}

答案 3 :(得分:0)

我在这里编写了一个带有bootstrap的超酷登录页面,如你所料。在您的html文件中链接bootstarp cdn。这将显示按钮下的错误,而不是显示Windows经典警报框。我还包括ajax请求和php响应以及一些验证。

<强>的login.html

<div class="container">   
    <div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">

        <form class="form-horizontal" role="form" action="#" method="">  
            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                <input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">                        
            </div>

            <br>

            <div class="input-group">
                <span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
                <input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">                        
            </div>

            <br>

            <div class="form-group">
                <div class="col-lg-6">
                    <button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
                </div>

                <div class="col-lg-6">
                     <button class="btn btn-success-outline btn-block" type="reset">Clear</button>
                </div>
            </div>
            <br>

            <div id="login-feedback" class="btn-block"></div>
        </form>
    </div> 
</div>

<强> myStyle.js

<script type="text/javascript">
        $(document).ready(function()
        {
            $('#login').click(function()
            {
                var uname=$('#username').val();             
                var pword=$('#password').val();

                if(uname!='' && pword!='')              
                {
                    $('#login-feedback').text('validating....');
                    $.post("login-check.php",{username:uname,password:pword},function(data)
                    {       
                        if(data=="success")
                        {   

                            $('#login-feedback').fadeTo(200,0.1,function()
                            {
                                $(this).html(data).css('color','green').fadeTo(1000,1,function()
                                {
                                    document.location='index.php';
                                });
                            });                     
                        }
                        else
                        {
                            $('#login-feedback').fadeTo(200,0.1,function()
                            {
                                 $(this).html(data).css('color','red').fadeTo(900,1);
                                 //reset form
                                 $('#login').trigger("reset");
                            });
                        }

                    });
                return false;
                }
                else
                {
                    $('#login-feedback').text("Please enter all fields").css('color','purple');
                }
            });
        });
    </script>

<强>登录-check.php

<?php

   //include connextion file;
    if(!isset($_SESSION))
        session_start();

    $username=trim($_POST['username']);
    $password=$_POST['password'];

    $username=mysqli_real_escape_string($con,$username);
    $password=mysqli_real_escape_string($con,md5($password));

    if(($username) && ($password))
    {
        $query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
        $rows = mysqli_num_rows($query);

        if ($rows>= 1) 
        {
            $fetch_result = mysqli_fetch_array($query);
            session_regenerate_id(true);

            $_SESSION['username']=$fetch_result['username']; 
            $_SESSION['status']=$fetch_result['status'];
            // Close session variable assigns
            session_write_close();
            echo "success";
        } 
        else 
        {
            echo 'Login failed';
        }

        mysqli_close($con);
    }
    ?>