AJAX returning a white space from PHP echo

Issue

This is a problem I been having several times, and I always ignore because I cant find a solution.

Basically every time I echoed a value back to Javascript using AJAX, the first value will contain a space (extra character) this is annoying because if I want to check if that value exist sometimes I cant due to the space.

Normally the values returned is something like this

 Value1
Value2
Value3

Here is the code below. I suggest to ignore the function seperate_ajx_data as I dont think the problem is located there.

results[0] is giving a white space plus the value!
What could be the issue of having a space in the first value?

PHP code:

$machine = null;
$sql = mysqli_query($connection, "SELECT......");
while($row = mysqli_fetch_array($sql)){
    $machine .= $row['MACHINE']."+";
    $machine .= $row['COUNT(MACHINE)']."/";
}
echo $machine;

JavaScript code:

function get_machine_vals(id){
    var ht = new XMLHttpRequest();
    var url = "....";
    var val = "....="+id;
    ht.open("POST", url, true);
    ht.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ht.onreadystatechange = function(){
        if(ht.readyState == 4 && ht.status == 200){
            var val = ht.responseText;
            var results = seperate_ajx_data(["/","+"],val);
            var el = document.getElementById("machine_dropdown");
            var opts = el.options;
            for(var i =0;i<results.length;i++){
                var tmp = results[i];
                alert(tmp + " " + tmp.length);
                switch (results[i]){
                    case "Test":
                        opts[0].innerHTML = "Seko "+results[i+1];
                        break;
                }
            }

        }
    };
    ht.send(val);
}

function seperate_ajx_data(symbols, val){
  var tmp_storage = [];
  var tmp_spliter = val.split(symbols[0]);
  var results = [];
  for(var x = 0;x<tmp_spliter.length;x++){
    tmp_storage = tmp_spliter[x].split(symbols[1]);
    for(var y = 0;y<tmp_storage.length;y++){
        results.push(tmp_storage[y]);
    }
  }
  return results;
}

Solution

This is unfortunately one of those "gotchas" when working with PHP. The errant character might come from a space after a closing PHP tag. A contrived example:

<?php

 ... do some work ...

?> <?php

... do some work, but note errant space between the tags

Possible fixes?

  • Don’t close the PHP tag

  • Use a different transfer mechanism that is space-tolerant, for example JSON or XML.

  • Strip (or "trim") your values client side. In context of your code:

     var val = (ht.responseText || '').trim();
    

Answered By – hunteke

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published