Solved

Where does the trailing space come from?

Posted on 2013-11-07
15
335 Views
Last Modified: 2013-11-10
http://plungjan.name/SO/load.php

The following code will fail if I do not trim the data.

Why does the PHP return "1 " or "0 " instead of "1" or "0" ?

<?php //load.php
if(isset($_POST["id"])){
  $myid = $_POST['id'];
  if($myid == "1"){
    echo "1";
  }else if($myid == "0"){
    echo "0";
  }
}
else {
?>
<!DOCTYPE html>
<html>
<head>
<title>Post something</title>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/javascript">
$(function() {
  $('#submit').click( function(){
    $.post('load.php', {"id":$('#id').val()}, function(data){
        window.console&&console.log(data,data=="1");
        var val = $.trim(data);
        if(val == "1"){
            $('#resurl').html('Success');
        }else if (val == "0"){
            $('#resurl').html('Failure');
        }else{
            $('#resurl').html('Unknown:[<span>'+val+'</span>]');
        }
    });
  });
});
</script>
</head>
<body>
<input id="id" />
<div id="resurl"></div>
<input type="button" id="submit" />
</html>
<? } ?> 

Open in new window

0
Comment
Question by:Michel Plungjan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
  • +2
15 Comments
 
LVL 13

Expert Comment

by:duncanb7
ID: 39630044
There is typing error, please re-run again

<?php //load.php
if(isset($_POST["id"])){
  $myid = $_POST['id'];
  if($myid == "1"){
    echo "1";
  }else if($myid == "0"){
    echo "0";
  }
}
else {

}
?>
<!DOCTYPE html>
<html>
<head>
<title>Post something</title>
<script src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script type="text/javascript">
$(function() {
  $('#submit').click( function(){
    $.post('load.php', {"id":$('#id').val()}, function(data){
        window.console&&console.log(data,data=="1");
        var val = $.trim(data);
        if(val == "1"){
            $('#resurl').html('Success');
        }else if (val == "0"){
            $('#resurl').html('Failure');
        }else{
            $('#resurl').html('Unknown:[<span>'+val+'</span>]');
        }
    });
  });
});
</script>
</head>
<body>
<input id="id" />
<div id="resurl"></div>
<input type="button" id="submit" />
</html>

Open in new window


window.console&&console.log("=="+data+"==",data=="1");

it show "1" and "0" not "1 " && "0 " if
using window.console&&console.log("=="+data+"==",data=="1");
0
 
LVL 75

Author Comment

by:Michel Plungjan
ID: 39630068
I do not understand what you mean.
I do not see any typing error.
I log data and the boolean data == "1" which is false since the data returned is "1 " and not "1"
0
 
LVL 13

Expert Comment

by:duncanb7
ID: 39630071
on line 10 on your first post
0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 
LVL 75

Author Comment

by:Michel Plungjan
ID: 39630110
I changed to

 window.console&&console.log(">>"+data+"<<",data=="1",data=="1 ");

>>1 << false true

So I do not understand what you mean by line 10?
0
 
LVL 35

Assisted Solution

by:Robert Schutt
Robert Schutt earned 400 total points
ID: 39630126
I copy/pasted the initially posted code into a file and there is actually a space as last character in the code, AFTER the last "}" of the else.
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 39630136
PS: that could have been an unrelated issue, only in the post, but with that file I saw the problem and when I removed the space there, the problem disappeared.
0
 
LVL 43

Accepted Solution

by:
Chris Stanyon earned 100 total points
ID: 39630163
@robert_schutt is bang on the money but beat me to posting. When you do an AJAX request the response is whatever the script outputs, and you have a space right at the end of your script (after the closing ?> tag). This also gets sent the to AJAX response.

If you're after checking against a number, then consider using parseInt(data)
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39630188
Actually, just an update to what I said - the space is after the closing php tag, not the one after the closing if bracket. One of the easiest ways to avoid this is to just leave off the closing PHP tag (but only if it's the end of your document). Finish your page like this:

<input type="button" id="submit" />
</html>
<? }

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39630200
This made sense for me.  Please see:
http://www.laprbass.com/RAY_temp_mplungjan.php

<?php // RAY_temp_mplungjan.php
error_reporting(E_ALL);

if(isset($_POST["id"]))
{   // FILTER / NORMALIZE THE REQUEST DATA
    $myid = trim($_POST['id']);

    // USING THE FILTERED DATA
    if($myid == "1")
    {
        echo "1";
    }
    elseif($myid == "0")
    {
        echo "0";
    }
    else
    {   // UNKNOWN
        echo $myid;
    }
}
else {
?>
<!DOCTYPE html>
<html>
<head>
<title>Post something</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $('#submit').click( function(){
    id = $("#id").val();
    $.post('RAY_temp_mplungjan.php', {id:id}, function(data){
      var val = $.trim(data);
      if(val == "1"){
        $('#resurl').html('Success');
      }else if (val == "0"){
        $('#resurl').html('Failure');
      }else{
        $('#resurl').html('Unknown:[<span>' + val + '</span>]');
      }
    });
  });
});
</script>
</head>
<body>
<input id="id" />
<div id="resurl"></div>
<input type="button" id="submit" />
</html>
<? } ?>

Open in new window

HTH, ~Ray
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39630241
In this post, line 22 opens a control structure, line 23 stops the PHP interpreter.  Then some HTML is sent to the browser.  PHP needs to know when the control structure ends.  That is line 52.  It starts PHP, provides the end of the control structure and then stops PHP.

If the "short open tag" is not set, you would need the complete <?php instead of just the <? to start the PHP interpreter.

I probably would have written this a little differently, but I was in a hurry and just working from what had been posted with the question.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39630925
0
 
LVL 75

Author Comment

by:Michel Plungjan
ID: 39631973
Thanks for the participation.

I do not exactly see how the code Ray posted is any different than mine, however I understand now that the spurious space came from

} ?>_ <=== here

and that I could delete it or just do

} /* end of php */

which is what I did. Hence I accept this answer as the solution to my issue

Learned something new.
0
 
LVL 13

Expert Comment

by:duncanb7
ID: 39632039
I think ChrisStanyon's answer to this thread is much completed and fast
by taking out php closing tab to solve mplungjan's issue completely
(no need to take care of how many space is left before ?>)


If I am wrong, I am sorry and please ignore my post

Duncan
0
 
LVL 75

Author Comment

by:Michel Plungjan
ID: 39632766
Robert's solution was first, but Chris' explanation was better.

thanks for pointing that out
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question