简体   繁体   English

如何从PHP函数运行JavaScript AJAX请求?

[英]How can I run a JavaScript AJAX request from a PHP function?

Currently the success of my PHP if statement just reloads the page: 目前,我的PHP if statement成功重新加载了页面:

header('Location: index.php');

Added: link to the site here http://marmiteontoast.co.uk/fyp/login-register/index.php 添加:链接到此处的网站http://marmiteontoast.co.uk/fyp/login-register/index.php

However I want to run a JavaScript basic AJAX request instead to load a page register-success.php into the div: 但是我想运行JavaScript基本的AJAX请求,而不是将页面register-success.php加载到div中:

function loadSuccess()
{var xmlhttp;
if (window.XMLHttpRequest)
  {xmlhttp=new XMLHttpRequest();}
else
  {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
  {if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {document.getElementById("login-register-wrapper").innerHTML=xmlhttp.responseText;}}
xmlhttp.open("GET","register-success.php",true);
xmlhttp.send();}

However I am unsure about this combination of JavaScript and PHP and how to implement it 但是我不确定JavaScript和PHP的组合以及如何实现它

1) Is there some sort of PHP function I can wrap around a piece of JS to make it enact it? 1)是否有某种PHP函数可以包裹一段JS以使其生效?

2) Is there a way to do a simple AJAX call like this in PHP instead? 2)有没有办法在PHP中像这样进行简单的AJAX调用? Or something that mimics it? 还是模仿的东西?

Here is the function that validates my form. 这是验证我的表格的功能。 If the form validates, I need to reload with AJAX and call in register-success file 如果表单通过验证,则需要重新加载AJAX并调用register-success文件

<?php
    session_start();
    require 'functions.php';

    if(isset($_POST['sign-up'])){
        // username
        if (isset($_POST['username'])){
            $username = mysql_real_escape_string(trim($_POST['username']));
            $_SESSION['status']['register']['username'] = $username;

            if(strlen($username) > 3){
                    if(strlen($username) < 31){
                        if(user_exists($username) === true){
                            $_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
                        } else{
                            // passed
                            // continue
                        }
                    } else {
                        $_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
                    }
                } else {
                    $_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
                }
        } else {
            $_SESSION['status']['register']['error'][] = 'The username is not entered.';
        }

        if (isset($_POST['password'])){
            $password = mysql_real_escape_string(trim($_POST['password']));

            if(strlen($password) >= 8){
                    $password = hash_function($password);
                } else {
                    $_SESSION['status']['register']['error'][] = "Your secret password is too short. You should make a password with at least 8 letters.";
                }

        } else {
            $_SESSION['status']['register']['error'][] = "You haven't put in a password.";
        }

        // Email address
        if (!empty($_POST['email_address'])){
            $email_address = mysql_real_escape_string(trim($_POST['email_address']));
            $_SESSION['status']['register']['email_address'] = $email_address;
            if(strlen($email_address) > 10){ // email address less than 10
                    if(strlen($email_address) < 161){ // if longer than 160

                        if(email_valid($email_address) == false){ // email address invalid format
                                $_SESSION['status']['register']['error'][] = "The email address has been put in wrong. Please check and try again.";
                            }
                            else{
                                // passed min length, passed max length, passed validation
                                // Continue
                            }
                    }
                    else 
                    {
                        $_SESSION['status']['register']['error'][] = 'The email address is too long.';
                    }
                } 
                else
                {
                    $_SESSION['status']['register']['error'][] = "The email address is too short. It can't be shorter than 10 letters.";
                }
        }
        else{// passed (no email input)
        }

        if (isset($_POST['tos'])){
            $_SESSION['status']['register']['tos'] = $_POST['tos'];
            if(empty($_SESSION['status']['register']['error'])){
                if(register($email_address, $username, $password) === true){

                    // Success!!
                    $_SESSION['status']['register']['success'] = true;

                    // Sends an email

                    send_email($email_address);

                } else {
                    echo mysql_error();
                    die();
                    $_SESSION['status']['register']['error'][] = "Something went wrong. We're sorry. Please try again.";
                }
            } else {}
        } else {
            $_SESSION['status']['register']['error'][] = "You have to agree to the House Rules to be able to sign up.";
        }

        header('Location: index.php');
    } else {
        // success script with AJAX goes here
    }

    ?>

You need to write javascript code outside PHP Block, so after ?>. 您需要在PHP Block外部编写javascript代码,所以在?>之后。 Ajax call are made from client side, so only with javascript. Ajax调用是从客户端进行的,因此只能使用javascript。

To simplify your code, you can use a javascript lib, like jQuery, so the code is more simple: 为了简化代码,您可以使用jQuery之类的javascript库,因此代码更简单:

$('#login-register-wrapper').load('register-success.php');

You can made this with PHP like Kamehameha Answer, using ob_get_contents(). 您可以使用ob_get_contents()将PHP像Kamehameha Answer一样实现。

In this case, without parameters from html page, the result is the same, the content from processed. 在这种情况下,如果没有来自html页面的参数,则结果是相同的,所处理的内容也是如此。

Edit: 编辑:

Based in comments, you need to redirect to 'index.php' with some parameter, like: 基于注释,您需要使用一些参数重定向到“ index.php”,例如:

header('Location: index.php?success=1');

So, in index.php, you can write some like this: 因此,在index.php中,您可以编写如下代码:

if (isset($_GET['success']) && $_GET['success'] == 1) {
    echo '<script>function loadSuccess()
{var xmlhttp;
if (window.XMLHttpRequest)
  {xmlhttp=new XMLHttpRequest();}
else
  {xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function()
  {if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {document.getElementById("login-register-wrapper").innerHTML=xmlhttp.responseText;}}
xmlhttp.open("GET","register-success.php",true);
xmlhttp.send();}</script>';
}

Edit: 编辑:

In tag body, you need to call javascript function loadSuccess(). 在代码主体中,您需要调用javascript函数loadSuccess()。 Like this: 像这样:

<body onload="loadSuccess()">

You would simply have to create a extra .php file that only has the register-logic in it. 您只需要创建一个额外的.php文件,其中仅包含register-logic。 Assuming you have a form with all the data in it, you would then use javascript to make a submit button and send all the data (for example via get or post) to this .php file on your server using a ajax request. 假设您有一个包含所有数据的表单,然后您将使用javascript创建一个提交按钮,并使用ajax请求将所有数据(例如,通过get或post)发送到服务器上的此.php文件。 answer would only be the html you want to include in your wrapper. 答案只会是您要包含在包装中的html。 This response from the server would then simply be displayed by modifying the dom of your current site 然后,只需修改当前站点的dom,即可显示服务器的此响应

It's really simple ! 真的很简单! do the following : 请执行下列操作 :

  • Add this line to your php code so it can run on the success of your PHP Function : 将此行添加到您的php代码中,以便它可以在您的PHP函数成功运行时运行:

echo " document.getElementById('success').click(); "; 回声“ document.getElementById('success')。click();”;

  • Now add this HTML line into your page , so it can load the 现在,将此HTML行添加到您的页面中,以便它可以加载
 <a id="success" style="visibility:hidden;">Success</a> <script> var el = document.getElementById('success'); el.onclick = loadSuccess(); </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM