how to get the responseText from echo in php

Tags: , , ,



I’m trying to return a value from PHP to JavaScript through responseText. The idea is if mysqli_num_rows($rslt) != 0, responseText = 1, or if mysqli_num_rows($rslt)= 0, to do an insert and responseText = 0, and then in JavaScript I get the responseText. How can I achieve that, because I tried with echo, but I couldn’t find a solution.

JavaScript code:

const request = $.ajax({
            url: "Gab.php",
            type: "POST",
            dataType: 'json',
            data: {username: username, password: password,email:email},
            success: function(data){
                console.log(data);
            }
        });
        
        request.done(done);
        request.fail("Couldnt register the user");
        
        
        //event.preventDefault();
    }}
    
    function done(responseText){
        console.log(responseText);
        if(responseText == 0){
            alert("Successful Registration");
            window.location.assign("index.php");
            }else{
            alert("There is a username or email already registered. Change that USERNAME OR EMAIL!!!");
        }
    }

PHP code:

//connect to db 
include 'debug.php';

$Uusername=$_POST["username"];
$Uemail=$_POST["email"];
$Upassword1=$_POST["password"];

//cleanup for db:
$username = mysqli_real_escape_string($db, $Uusername);
$email = mysqli_real_escape_string($db, $Uemail);
$password_1 = mysqli_real_escape_string($db, $Upassword1);

//check db for existing user or email
$user_check="SELECT Usersusername,Usersemail FROM users WHERE Usersusername = '$username' or Usersemail = '$email'" ;
$rslt = mysqli_query($db,$user_check);
$exist = mysqli_num_rows($rslt);

if(mysqli_num_rows($rslt) != 0){    
    echo 1;
    //$PHPVar = 1;
    }else{
    $pwd= password_hash($password_1,PASSWORD_DEFAULT);
    $result = "INSERT into users(Usersusername,Usersemail,Userspwd) VALUES ('$username','$email','$pwd')"; 
    mysqli_query($db,$result);
    echo 0;
    //$PHPVar = 0;  
}   

Answer

Perhaps the following might help – I rearranged things a little and corrected the js functions and sent a basic JSON string as the responseText for convenience

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['username'],$_POST['password'],$_POST['email']) ){
        ob_clean();
        # imagine the SQL query has been executed OK but for randomness here the response will
        # be either 1 or 0 ...
        
        $i=mt_rand(0,1);
        
        exit(json_encode(array('status'=>$i)));
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
        <script src='//code.jquery.com/jquery-latest.js'></script>
        <script>
            let username='fred';
            let password='banana';
            let email='fred@bedrock.com';
        
        
            function done( r ){
                console.log(r);
                
                if( r.status == 0 ){
                    alert('Successful Registration');
                    //window.location.assign('index.php');
                }else{
                    alert('There is a username or email already registered. Change that USERNAME OR EMAIL!!!');
                }
            }
        
            $.ajax({
                url:location.href,  //'Gab.php'
                type: 'POST',
                dataType: 'json',
                data: {'username': username, 'password':password, 'email':email },
                success: function(data){
                    console.log(data);
                    done( data )
                },
                error:function(err){
                    alert(err)
                }
            });
        </script>
    </head>
    <body>
        
    </body>
</html>


Source: stackoverflow