3

How do I convert Ajax response into plain text string?I have global variable and I store the ajax response to it but when I'm going to compare it with javascript string when even they are equal It returns false.

Here is my code:

function checkUsn(){
    var usn = document.getElementById("usn").value;
    if(usn){
        $.ajax({
            type: 'post',
            url: 'checkdata.php',
            data: {
                emp_username: usn,
            },
            success: function(response){
                console.log(response);
                myGlobalContainer.usn = response; //convert it to compare with string
                $('#status').html(response);
            }
        });
    }
}

in console when I type the existing username in database it logs OK. This OK stores in myGlobalContainer.usn, but when I do comparison like code below it return false.

if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}

I will add php file.

<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);

if(isset($_POST['emp_username'])){
    $usn = $_POST['emp_username'];

    $checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $checkdata);

    if(mysqli_num_rows($query) > 0){
        echo "OK";
    }else{
        echo "Your Username not exist";
    }
    exit();
}

if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
    $pw = $_POST['emp_pw'];
    $usn = $_POST['emp_usn'];

    $get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $get_pw);

    //$get_num_rows = mysqli_num_rows($query);
    //echo $get_num_rows;

    $row = mysqli_fetch_assoc($query);
    //echo $row["emp_password"];

    // check if password is match with username
    if($pw == $row["emp_password"]){
        echo "MATCH";
    }else{
        echo "Wrong password";
    }
    exit();
}
?>

Please help Thanks!

3
  • 1
    I don't think the problem is the string comparison, response is already a string in all likeliness, the problem is probably that you are executing the code where you compare myGlobalContainer.usn == "OK" before the value is set in the Ajax callback. The callback is executed asynchronously. Commented Aug 11, 2018 at 9:22
  • Try JSON.stringify(response); Commented Aug 11, 2018 at 9:27
  • When / where exactly is your if(myGlobalContainer.usn == "OK") code executing? Commented Aug 13, 2018 at 1:17

3 Answers 3

2

I've change my code to

    success: function(response){
        console.log(response);
        myGlobalContainer.usn = response.trim(); //convert it to compare with string
        $('#status').html(response);

and It works but Guys thanks for your help very appreciated! also thanks to this question Ajax response doesn't equal what I think it should

Sign up to request clarification or add additional context in comments.

2 Comments

You must have had some whitespace (newline, etc) in your PHP that is not shown in your question.
Phil> nope - I had the same issue, and my PHP was clean - but it does need a trim in JavaScript for some reason it seems
1

By default, jQuery's ajax function will determine the type of data it is receiving from the Content-Type response header.

You can override that with the dataType parameter.

$.ajax({
    dataType: "text",
    // etc etc
});

… however, since the response seems to be "OK" and not HTML, it is likely that your PHP should be adjusted so it outputs the correct Content-Type:

<?php
    header("Content-Type: text/plain"); # Override the default (text/html)
    echo "OK";

So also make sure that the response is really simply "OK" and that you are not outputting (for example) "OK" followed by a new line.

1 Comment

Hi sir Quentin It doesn't work Even I put header("Content-Type: text/plain"); in php file and add dataType: "text", on ajax.
0

i seem you should use a function in ajax success.

var myGlobalContainer.usn = "";
function signAndCompare(str)
{
     myGlobalContainer.usn = str
     if(myGlobalContainer.usn == "OK")
         {
             console.log("true");
             return true;
          }
     console.log("false");
     return false;
 }

function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
    $.ajax({
        type: 'post',
        url: 'checkdata.php',
        data: {
            emp_username: usn,
        },
        success: function(response){
            console.log(response);
            signAndCompare(response);//this line: **compare** and sign response
            $('#status').html(response);
        }
    });
}

2 Comments

Hi sir Alireza thank you for your response. I've tried the your solution but It doesn't work
FYI, var myGlobalContainer.usn = ""; is invalid. You want var myGlobalContainer = { usn: '' } or something like that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.