0

I'm trying to make my code, test.php, execute some Javascript code if my PHP code, conditional.php, sees that something was inputted then submitted. Instead what my code does is output "Not empty" instead of "Do Something in Javascript". One strange thing I noticed is that lines 26-32 (inside the doSomething() function) in test.php are ignored and yet it prints out "Empty" and "Not empty" in the textbox nonetheless.

The reason I'm doing it this way is because the code in my actual website will need to either use a Javascript API or just PHP depending on the input to generate an output.

test.php

<!DOCTYPE html>
<html>
  <body>
    <!-- Input -->  
    <div class="form">
      <form action="test.php" method="post">
        <input type="text" id="inputText" name="inputText">
        <input type="submit">
      </form>
    </div>

    <br>

    <!-- Output -->
    <div class="txtBox">
      <textarea id="txtBox">
<?php require_once "conditional.php";?>
      </textarea>
    </div>

    <script>
        function makeRequest() {
            httpRequest = new XMLHttpRequest();

            httpRequest.onreadystatechange = doSomething() {
                // get echoed json from conditional.php
                document.getElementById("txtBox").innerHTML = httpRequest.responseText;

               /if (httpRequest.responseText == "Not Empty") {
                    // do my Javascript code
                    document.getElementById("txtBox").innerHTML = "Do something in Javascript";
                }
            };

            httpRequest.open("GET", conditional.php);
            httpRequest.send();
        }
    </script>
  </body>
</html>

conditional.php

<?php
$input = $_POST["inputText"];

if ($input != "") {
    echo json_encode("Not empty");
} else {
    echo json_encode("Empty");
}
?>
6
  • Have you tried dumping out the contents of the $_POST variable and seeing what the value is when the check should fail? Commented Feb 18, 2015 at 3:02
  • It looks like you are trying to submit your AJAX request via GET, but are accessing the form information via POST. Commented Feb 18, 2015 at 3:03
  • Okay, firstly, is conditional.php supposed to be an object + property in the javascript? If not, turn it into a string. Secondly, if you are using .responseText, do you really need json_encode? Commented Feb 18, 2015 at 3:04
  • why are you sing "GET" method in AJAX and using POST variable to retrieve it in conditional.php. Commented Feb 18, 2015 at 3:05
  • Damon Swayn, it seems that $_POST variable has the value it is meant to have. Crackertastic and noob, thank you for pointing that out. TRGWII, could you clarify the first question. With the second question I thought that I needed to use json_encode. If there is another way then I am happy to hear about it. Commented Feb 18, 2015 at 3:21

3 Answers 3

1

You code has a few things going on with it that are stopping you from getting the behavior you are after.

First, you are trying to send data via GET but access it via POST. Second, your form data isn't actually getting sent with your AJAX call. Finally, your function makeRequest() isn't actually being invoked anywhere. You are getting the text in your <textarea> because your conditional.php outputs inside of it.

In your case you need to remove the form's capabilities to submit (since you are doing it by AJAX), invoke your makeRequest() function, send the data, get the response and edit the <textarea>.

Another thing to consider, instead of comparing text return values, why not use HTTP response codes? It works nice for these situations and you can set it with PHP.

Here is your two files modified a bit to achieve what you are after.

test.php

<!DOCTYPE html>
<html>
  <body>

    <!-- Input -->  
    <div class="form">
      <form onsubmit="makeRequest(); return false;">
        <input type="text" id="inputText" name="inputText">
        <input type="submit">
      </form>
    </div>

    <br>

    <!-- Output -->
    <div class="txtBox">
      <textarea id="txtBox">
      </textarea>
    </div>

    <script>
        function makeRequest() {
            httpRequest = new XMLHttpRequest();            
            httpRequest.onreadystatechange = function() {
                if(httpRequest.readyState == 4) {
                    document.getElementById("txtBox").value = httpRequest.responseText;
                    if (httpRequest.status == 200) {
                        // do my Javascript code
                        document.getElementById("txtBox").value = "Do something in Javascript";
                    } else {
                        document.getElementById("txtBox").value = "Empty";
                    }
                }
            };
            httpRequest.open("POST", "conditional.php", true);
            httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            httpRequest.send("inputText=" + document.getElementById("inputText").value);
        }
    </script>

  </body>
</html>

conditional.php

<?php

if (isset($_POST["inputText"]) && $_POST["inputText"] != "") {
    http_response_code(200);
} else {
    http_response_code(400);
}

?>

Note that http_response_code() is available in PHP >= 5.4 - any versions before that and you will have to use the header() function instead.

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

2 Comments

Hi Crackertastic, thank you for your answer. Within the scope of the question as I stated it, without any knowledge of how I will apply this to my website, the answer is very helpful. I just have one question. How could I modify the code so that if the input begins with http:// then I would process the input in PHP and return the output and fill the text area with that output? If I am not mistaken, I would have to use something different from http_response_code.
@cycloidistic Could you elaborate on what you mean by "Begins with http://"? In the conditional.php file you would echo whatever you like and then access with httpRequest.responseText. I used the response code in your case because it is a clearer way to test the result of your conditional in your PHP and is available in AJAX with httpRequest.status. You can echo a JSON payload like you were doing before if that is comfortable. As for the http_response_code() if you have PHP 5.4 or better, you are set. If not, use the header() function
0

test.php

<!DOCTYPE html>
<html>
  <body>
    <!-- Input -->  
    <div class="form">
      <form method="post">
        <input type="text" id="inputText" name="inputText">
        <input type="button" value="Ok" onclick="makeRequest();" >
      </form>
    </div>

    <br>

    <!-- Output -->

<div class="txtBox">
  <textarea id="txtBox">
  </textarea>
</div>

<script>
function makeRequest() {
    if (document.getElementById("inputText").value != "") {
        httpRequest = crearXMLHttpRequest();

        function crearXMLHttpRequest() {
            var xmlHttp = null;
            if (window.ActiveXObject)
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            else
                if (window.XMLHttpRequest)
                    xmlHttp = new XMLHttpRequest();
            return xmlHttp;
        }

        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                // get echoed json from conditional.php
                document.getElementById("txtBox").innerHTML = httpRequest.responseText;

                if (httpRequest.responseText == "Not Empty") {
                    // do my Javascript code
                    document.getElementById("txtBox").innerHTML = "Do something in Javascript";
                }
            }
        };

        httpRequest.open("GET", "conditional.php?inputText=" + document.getElementById("inputText").value, true);
        httpRequest.send(null);
    }
    else {
        //Do javascript code
    }
}
</script>
  </body>
</html>

And your conditional.php looks like this:

<?php
$input = $_GET["inputText"];

if ($input != "") {
    echo "Not empty";
} else {
    echo "Empty";
}
?>

6 Comments

I copy pasted your code, saved it and then ran it. It might have been something I've done but with empty and not empty the button doesn't do anything. The text "Empty" and "Not empty" are not printed out in the text area like before
I forgot the end tags, thank you for mentioning that. Now, I used your code (with end tags) and made your modifications. Still does the same thing.
Ok, i edit the code, i modify some lines of javascript
I've tried it. It now says "Empty" when I don't put something in and "Empty " when I do put something in. One thing that would help me a lot is if you could explain I could modify your code in order to execute Javascript code in one case and execute PHP code in the other case? One example could be when not empty execute some javascript code and when empty execute some PHP code.
In that case, you first need evaluate if (document.getElementById("inputText").value == ""), if sentence is true, do the javascript process, if is false, you need to executes the ajax, and then your php code executes
|
0

ok first off you aren't posting data to conditional.php at all. Your form action is pointing at test.php:

so Change:

<div class="txtBox">
      <textarea id="txtBox">
<?php require_once "conditional.php";?>
      </textarea>
    </div>

to:

<div class="txtBox">
      <textarea id="txtBox">
<?php if($_SERVER['REQUEST_METHOD'] == 'POST'){
         if($_POST['inputText'] != ''){?>
          <script type="text/javascript">
                alert("this is when something is pressedeven including space");//here goes your javascript function or any html
          </script>
        <?php } 
         else{
          echo "when nothing is inputed. Empty" // this is the php
         }
       } ?>
      </textarea>
</div>

5 Comments

Hi noob, despite using GET httpRequest.open("GET", conditional.php); it seems that the data is still posting. I echoed $input in conditional.php to make sure that was the case. Secondly your suggestion to change the line of code resulted in opening a new page. I'm sorry that I didn't mention this, but I would like to stay on the same page on only change the text in the textbox after clicking submit. Thank you for your answer :)
I've tried it. First of all, you were missing a semicolon at the end of echo $_POST['inputText']. I tried to edit it but I have to edit at least 6 characters for it to submit. With the semicolon, your suggestions just cut and pastes the input into the text area.
With the edit when something is typed there is no output. When something is typed it prints out "Do something in Javascript". How could I modify this code in order to execute Javascript code in one case and execute PHP code in the other case? One example could be when not empty execute some javascript code and when empty execute some PHP code.
It looks like you are very close. Assuming I deleted my original <script>...</script> code and put in your code, the page is blank. Using link it seems like the semicolon in "<script>;" or the } the line below it are causing some troubles. If that was fixed then I think it would work.
Never mind, I've got it sorted. Thank you for your help noob :)

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.