Jump to content

php is concatenating 2 values in its return


Gilbert

Recommended Posts

Hi all,  I have a php file to check a users input and it seems pretty straight-forward as far as logic goes, but the  variable seems to be concatenating the "badEntry" onto its return value.  I've been over it and over it and can't seem to see what's wrong.   I originally had $userInput as the only return variable, but when I started having trouble I added the $toReturn variable to hopefully make it clear what I was doing wrong.   Didn't help.  I enter 'sakde12345' and I get that back with 'BadEntry' concatenated to it - looks like this - sakde12345BadEntry.   My callback function is supposed to see if the return value is equal to 'BadEntry' and of course it isn't because it somehow includes the original input in front of it.   It's returning this for either 'good' or 'bad' input.  Can anyone figure out how I've miscoded or what?                 I also had a question about the debugger in chrome when I was running the js that called this php in the xmlhttprequest.   The debugger traced thru everthing OK, but when it came to the 'onreadystatechange', it went to the 'xhr.open' line, jumped back to the onreadystatechange ( which became 1) but then it jumped to the requestheader line, then the .send line, then it jumped back to the js function that called the xhr request, then it jumped all the way back to the button in html that submitted the input.  That kind of surprised me to see that - is the program just gathering information to proceed or something like that?   I know it's kind of a weird question, but I'd like to understand what is going on.  Thanx for any help, and I appreciate your patience!!!

 

<?php

$toReturn = "";
$userInput = "";
$chars = [];
$i = 0;

if ($_SERVER["REQUEST_METHOD"] == "POST"){
  $userInput = $_POST["userID"];             // Get variable passed to xmlhttp call
  $userInput = test_input($userInput);       // Run it thru easy data cleaner
  $userInput = strtolower($userInput);      // change all to lower case
  $toReturn = $userInput;
  $chars = str_split($userInput);             // split input into single characters
    if (strlen($userInput) != 10) {           // is the input exactly 10 chars long
        $toReturn = "BadEntry";  
    } else {
      if (substr($userInput,0,3) != "sak") {  // are the 1st 3 letters 'sak'
        $toReturn = "BadEntry";
      } else {
        if (is_not_Char($chars[3]) || is_not_Char($chars[4])) { // are the 4th & 5th chars letters - name initials
          $toReturn = "BadEntry";
        } else {
          for ($i = 5; $i < 10; $i++){
            if (is_not_Numb($chars[$i])) {    // are the last 5 chars Numbers
              $toReturn = "BadEntry";
            }
          }
        }
      }
    }     
}
echo $toReturn;

function is_not_Char($examp){
    $charBool = false;
    if ($examp < chr(97) || $examp > chr(122)) {    // is it a lowercase letter - ascii 97 - 122
        $charBool = true;
    }
    echo $charBool;
}
function is_not_Numb($examp){
    $charBool = false;
    if ($examp < chr(48) || $examp > chr(57)) {   // is it a number - ascii 48 - 57  ( 0 - 9 )
        $charBool = true;
    }
    echo $charBool;
}
function test_input($data) {      // standard data cleansing tools
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  echo $data;
}
?>

 

Link to comment
Share on other sites

Absolutely correct - it works like a charm - Thank You very Much!!  I've been a little hazy on which to use where.  I know return is supposed to send back a value whereas echo sends back a string maybe with html in it.   Do I have that correct?   And can you add anything to that so I can get it straight in my head.   Thanx again, Gil

Link to comment
Share on other sites

echo is used to show something to use user. The return keyword is used to send data from a function to the code that called the function.

  • Like 1
Link to comment
Share on other sites

Thank you.  I think I have it straight, but I just came up with another fly in my ointment.  I can't figure what's wrong here - I get 'undefined' when I look at 'goodInput'.  I have followed the w3 examples doing an xmlhttprequest specifying a callback function; usually w3 will put the responseText into a 'demo' element and assign it with innerHTML    So I took it one step further and thought why can't you cut out the middleman and use a 'return' to send back the responseText and assign it to a variable.   I am checking for valid input and am only going to get one response back so it seemed logical (to me).   I have tested a similar function with a callback and it worked well, but with 4 more lines needed for the callback.   Here's my code for the calling function and the xhr function; is it possible to do it this way?     The userInput I enter is in the correct form and should return as is.

// userInput is from a prompt input box and passed to this function
// not worried about security here - just functionality

function validateInput(userInput) {
        var sendMe = "userID=" + userInput;
        var goodInput = loadPHPwithReturn("checkUserInput.php", sendMe);
        return goodInput;     // goodInput is either = to the input or 'BadEntry" which I deal with on return
    }

//Load an XMLHttpRequest with Return of Response Text

    function loadPHPwithReturn(url, sendMe) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            return this.responseText;
        }
        };
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(sendMe);
    }

 

Link to comment
Share on other sites

is it possible to do it this way?

No.  XHR requests are asynchronous, which means that the browser does not wait for them to finish before continuing.  When you try to return that value, the request to the server hasn't even finished yet, it runs in the background.

If you look at your code carefully, you'll notice that your loadPHPwithReturn function does not return a value, that function does not have a return statement.  That's why it says undefined.  The return statement you think is there is not inside that function, it's inside the onreadystatechange function.  So you have the onreadystatechange function returning a value, but that value doesn't get returned anywhere.  The internal stuff which handles the ajax request and calls the readystatechange function doesn't do anything with whatever that function returns.

This is the nature of asynchronous things - they run in the background and finish at some point in the future.  The purpose of the onreadystatechange callback is so that you can figure out when it has finished, and do whatever you want with the result.

  • Thanks 1
Link to comment
Share on other sites

Thank you very much - great explanation!   I have programmed in 'normal' languages for some time now, but I have to start thinking in abstracts more with asynchronous stuff going on.   I appreciate  all the help from good, experienced coders like yourself.    Gil

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...