简体   繁体   English

如何使用 PHP 从 ajax 响应中删除 HTML 标签?

[英]How to remove HTML tags from ajax response using PHP?

I need to check from the database if email exists or not by using Ajax.我需要使用 Ajax 从数据库中检查电子邮件是否存在。 I am getting a response, but coming with some HTML content.我收到了回复,但附带了一些 HTML 内容。 I have given below my code what I have followed.我在我的代码下面给出了我所遵循的。

My Ajax code:我的 Ajax 代码:

var username_state = false;
var email_state = false;
$('#username').on('blur', function(){
    var username = $('#username').val();
    if (username == '') {
        username_state = false;
        return;
    }
    $.ajax({
        url: 'user_list.php',
        type: 'post',
        data: {
            'username_check' : 1,
            'user_name' : username,
        },
        success: function(response){
            $("html").html($("html", response).html());
            if (response == 'taken' ) {
                response.find(element).remove();
                alert('hi');
                username_state = false;
                $('#username').parent().removeClass();
                $('#username').parent().addClass("form_error");
                $('#username').siblings("span").text('Sorry... Username already taken');
            }
            else if (response == 'not_taken') {
                username_state = true;
                $('#username').parent().removeClass();
                $('#username').parent().addClass("form_success");
                $('#username').siblings("span").text('Username available');
            }
        }
    });
});     

My php Code我的 php 代码

$db = mysqli_connect('localhost', 'root', '', 'my_assesment');

if (isset($_POST['username_check'])) {
$username = $_POST['user_name'];
// echo  $username;
$sql = "SELECT * FROM user_information
            WHERE user_name='".$_POST["user_name"]."'";
//echo  $sql;
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results) > 0) {
    //$response = true;
    echo "taken";   
}else{
    $response = false;
  echo 'not_taken';
}

This is am getting response这是得到回应

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" 
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- jQuery -->
not_taken

Looking at the output you are receiving my guess is that the ajax request is being sent to the same page.查看您收到的输出,我的猜测是 ajax 请求被发送到同一页面。 If that is the case then initially wrap the entire username checking code within a suitable if test and ensure that any HTML buffer content is disposed of completely before sending the response to the ajax callback.如果是这种情况,那么最初将整个用户名检查代码包装在合适的if测试中,并确保在将响应发送到 ajax 回调之前完全处理任何 HTML 缓冲区内容。

/*
    Test that the request is a POST request and that
    the variables you are expecting have been sent.
    
    As you are using data sent by the client you MUST
    take precautions to mitigate SQL injection attacks.
    
    Use a Prepared statement rather than directly embedding
    user supplied data in the SQL.
*/
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( 
    $_POST['username_check'],
    $_POST['user_name']
)){

    $db = mysqli_connect('localhost', 'root', '', 'my_assesment');
    $sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
    $stmt=$db->prepare( $sql );
    $stmt->bind_param('s',$_POST['user_name']);
    $stmt->execute();
    $stmt->store_result();
    $rows=$stmt->num_rows;
    $stmt->close();
    
    $response=( $rows > 0 ) ? 'taken' : 'not_taken';
    
    # flush buffer to remove any other HTML / text content
    ob_clean();
    
    #exit completely from this logic branch
    exit( $response );
}

The test page I used to try to figure out the fault in the callback was exactly as follows.我曾经尝试找出回调中的错误的测试页面如下。 Essentially rather than respecting the checkbox to do a test and querying the db a random integer determines if the status is taken or not_taken simply to test the logic in the callback.本质上,不是尊重复选框来进行测试和查询数据库,而是随机整数确定状态是否被taken或不not_taken只是为了测试回调中的逻辑。

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( 
        $_POST['username_check'],
        $_POST['user_name']
    )){
        /*
        $db = mysqli_connect('localhost', 'root', '', 'my_assesment');
        $sql='SELECT `user_name` FROM `user_information` WHERE `user_name`=?';
        $stmt=$db->prepare( $sql );
        $stmt->bind_param('s',$_POST['user_name']);
        $stmt->execute();
        $stmt->store_result();
        $rows=$stmt->num_rows;
        $stmt->close();
        */
        $rows=mt_rand(0,1);
        $response=( $rows > 0 ) ? 'taken' : 'not_taken';
        
        ob_clean();
        exit( $response );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>?Username Check Test Page</title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <style>
            label{display:block;padding:1rem;}
            .form_success{background:rgba(0,255,0,0.25)!important;}
            .form_error{background:rgba(255,0,0,0.25)!important;)}
        </style>
    </head>
    <body>
        <form name='usercheck'>
            <label>Username:<input type='text' id='username' name='user_name' value='geronimo' /></label>
            <label>Username Check:<input type='checkbox' name='username_check' value=1 /></label>
        </form>
        <script>
            var username_state = false;
            var email_state = false;
            
            $('#username').on('blur', function(){
            
                var username = $('#username').val();
                if (username == '') {
                    username_state = false;
                    return;
                }
                
                $.ajax({
                    url: location.href, //  'user_list.php' ~ same page here!
                    type: 'post',
                    data: {
                        'username_check' : 1,
                        'user_name' : username,
                    },
                    success: function(response){
                        alert(response);
                        // no idea what this is doing
                        // $("html").html($("html", response).html());
                        if (response == 'taken' ) {
                            // this caused issues for me... no error as such but prevented further processing
                            // response.find(element).remove();
                            alert('hi - choose another username');
                            username_state = false;
                            $('#username').parent().removeClass();
                            $('#username').parent().addClass("form_error");
                            $('#username').siblings("span").text('Sorry... Username already taken');
                        }
                        else if (response == 'not_taken') {
                            username_state = true;
                            alert('ok - that user name is fine');
                            $('#username').parent().removeClass();
                            $('#username').parent().addClass("form_success");
                            $('#username').siblings("span").text('Username available');
                        }
                    }
                });
            }); 

        </script>
    </body>
</html>

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

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