简体   繁体   中英

How do I get response data from php with ajax (one file)?

I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1

This is my code:

<?php
if (isset($_POST['table'])) {
    $file = file("testing.txt");
    if (in_array($_POST['table'], $file)) { 
        echo "1"; 
    } else { 
        echo "0"; 
    } 
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
    var text;
    document.getElementById('button').onclick = function () {
        text = document.getElementById('text').value;
        post(text);
    };
    function post(vally) {
        var table = vally;
        $.post('test.php', {table:table}, function(data) {

        })
        .done(function (data) {
            if (data == 1) {
                console.log("the output is 1")
            } else {
                console.log("the output isn't 1")
            }
        });
        console.log('posted');
    }
</script>
</body>
</html>

testing.txt:

abc
def
ghi

The response I get if i console.log(data) :

0<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
    var text;
    document.getElementById('button').onclick = function () {
        text = document.getElementById('text').value;
        post(text);
    };
    function post(vally) {
        var table = vally;
        $.post('test.php', {table:table}, function(data) {

        })
        .done(function (data) {
            if (data == 1) {
                console.log("the output is 1")
            } else {
                console.log(data)
            }
        });
        console.log('posted');
    }
</script>
</body>
</html>

I have tried using .done(), .fail() and .always() but I always get the output isn't 1 (I am using JQuery 3.2.1).

Can someone tell me what I'm doing wrong?

EDIT : I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.

The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.

  1. Move your PHP code in anoter file, say 'ajax.php'
  2. And change your $.post() settings to call ajax.php instead of test.php .

So the Ajax request will only receive the '0' or '1' string.

Notice how your AJAX response is the entire page , prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:

<?php
if (isset($_POST['table'])) {
    $file = file("testing.txt");
    if (in_array($_POST['table'], $file)) { 
        echo "1"; 
    } else { 
        echo "0"; 
    } 
}
?>

Then make your AJAX call to that page:

$.post('checkTable.php', {table:table})

Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)

Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.

Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1 , and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.

This is the finished code:

<?php
if (isset($_POST['table'])) {
    $file = file("testing.txt");
    $file = array_filter(array_map('trim', $file));
    if (in_array($_POST['table'], $file) == true) { 
        echo "1"; 
    } else { 
        echo "0"; 
    } 
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
    var text;
    document.getElementById('button').onclick = function () {
        text = document.getElementById('text').value;
        post(text.trim());
    };
    function post(vally) {
        var table = vally;
        console.log(vally);
        $.post('test.php', {table:table}, function(data) {
            var cut = data.slice(0, 1);
            if (cut == 1) {
                console.log("the output is 1")
            } else {
                console.log(cut);
            }
        });
        console.log('posted');
    }
</script>
</body>
</html>

I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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