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

时间:2022-04-08 07:46:34

Currently the success of my PHP if statement just reloads the page:

目前我的PHP if语句的成功只是重新加载页面:

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? Or something that mimics it?

2)有没有办法在PHP中进行这样的简单AJAX调用?还是模仿它的东西?

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
    }

    ?>

3 个解决方案

#1


1  

You need to write javascript code outside PHP Block, so after ?>. Ajax call are made from client side, so only with javascript.

你需要在PHP Block之外编写javascript代码,所以在?>之后。 Ajax调用是从客户端进行的,所以只能使用javascript。

To simplify your code, you can use a javascript lib, like jQuery, so the code is more simple:

为了简化代码,您可以使用javascript lib,如jQuery,因此代码更简单:

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

You can made this with PHP like Kamehameha Answer, using ob_get_contents().

您可以使用像Kamehameha Answer这样的PHP,使用ob_get_contents()。

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(). Like this:

在标签体中,您需要调用javascript函数loadSuccess()。像这样:

<body onload="loadSuccess()">

#2


0  

You would simply have to create a extra .php file that only has the register-logic in it. 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. answer would only be the html you want to include in your wrapper. This response from the server would then simply be displayed by modifying the dom of your current site

您只需要创建一个仅包含寄存器逻辑的额外.php文件。假设您有一个包含所有数据的表单,那么您将使用javascript创建一个提交按钮,并使用ajax请求将所有数据(例如通过get或post)发送到服务器上的.php文件。答案只是你想要包含在你的包装器中的html。然后,通过修改当前站点的dom,可以简单地显示服务器的响应

#3


0  

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

echo“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>

#1


1  

You need to write javascript code outside PHP Block, so after ?>. Ajax call are made from client side, so only with javascript.

你需要在PHP Block之外编写javascript代码,所以在?>之后。 Ajax调用是从客户端进行的,所以只能使用javascript。

To simplify your code, you can use a javascript lib, like jQuery, so the code is more simple:

为了简化代码,您可以使用javascript lib,如jQuery,因此代码更简单:

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

You can made this with PHP like Kamehameha Answer, using ob_get_contents().

您可以使用像Kamehameha Answer这样的PHP,使用ob_get_contents()。

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(). Like this:

在标签体中,您需要调用javascript函数loadSuccess()。像这样:

<body onload="loadSuccess()">

#2


0  

You would simply have to create a extra .php file that only has the register-logic in it. 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. answer would only be the html you want to include in your wrapper. This response from the server would then simply be displayed by modifying the dom of your current site

您只需要创建一个仅包含寄存器逻辑的额外.php文件。假设您有一个包含所有数据的表单,那么您将使用javascript创建一个提交按钮,并使用ajax请求将所有数据(例如通过get或post)发送到服务器上的.php文件。答案只是你想要包含在你的包装器中的html。然后,通过修改当前站点的dom,可以简单地显示服务器的响应

#3


0  

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

echo“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>