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){
        request.done(done);"Couldnt register the user");
    function done(responseText){
        if(responseText == 0){
            alert("Successful Registration");
            alert("There is a username or email already registered. Change that USERNAME OR EMAIL!!!");

PHP code:

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


//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;
    $pwd= password_hash($password_1,PASSWORD_DEFAULT);
    $result = "INSERT into users(Usersusername,Usersemail,Userspwd) VALUES ('$username','$email','$pwd')"; 
    echo 0;
    //$PHPVar = 0;  


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

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['username'],$_POST['password'],$_POST['email']) ){
        # imagine the SQL query has been executed OK but for randomness here the response will
        # be either 1 or 0 ...
<!DOCTYPE html>
<html lang='en'>
        <meta charset='utf-8' />
        <script src='//'></script>
            let username='fred';
            let password='banana';
            let email='';
            function done( r ){
                if( r.status == 0 ){
                    alert('Successful Registration');
                    alert('There is a username or email already registered. Change that USERNAME OR EMAIL!!!');
                url:location.href,  //'Gab.php'
                type: 'POST',
                dataType: 'json',
                data: {'username': username, 'password':password, 'email':email },
                success: function(data){
                    done( data )

Source: stackoverflow