William Frederick
William Frederick

Reputation: 1

jQuery/PHP - Having more than one PHP block creates extra character of output when read by jQuery .ajax

I've managed to boil this problem down to the bare essentials: So I've got two simple .php files:

TEST.PHP

<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>My Page</title>

<script src='/root/js/jquery-1.6.3.js'></script>
<script>

$(document).ready(function() {

$.ajax({

        url : 'test_ajax.php',
        type : 'GET',
        timeout : 10000,
        dataType : 'text',
        data : { 'param' : 'whatever' },
        success : function(data,status,jqXHR) {
            $('#status').html(data.length+"-"+data);
        },
        error : function(jqXHR,textStatus,errorThrown) {
            $('#status').html("Error: "+textStatus+" , "+errorThrown);
        },
        complete : function(jqXHR,textStatus) {
        }

    });

}); // end ready

</script>

</head>

<body>
    <p id='status'>
    </p>
</body>
</html>

and TEST_AJAX.PHP

<?php
?>

<?php
echo "ok";
?>

The data that should be returned from TEST_AJAX.PHP is "ok". However, what is being retrieved by the jQuery/ajax code is a THREE character string which is outputted as " ok" (although the character at [0] is not equal to " ").

This ONLY happens if I have the two php blocks in TEST_AJAX. If I delete the first block, leaving only the second one, then it returns "ok" as a two character string, as it should.

What on earth is going on here? AFAIK, it should be perfectly acceptable to have multiple php blocks in a .php file - even though it's obviously unnecessary in this simplified example.

Upvotes: 0

Views: 125

Answers (3)

otternq
otternq

Reputation: 56

White space in the PHP blocks is ignored, but the space between the PHP blocks will always be returned. You may have better luck printing a json string like:

{'response':'ok'}

Then change your data type to json in your ajax request, and accessing the response with data.response

That way any extra spaces will not affect parsing

Upvotes: 0

Michel Feldheim
Michel Feldheim

Reputation: 18250

PHP is a templating language. Everything outside of your tags will be not parsed and returned literally.

Example

<html>
..
    <body>
        <?php echo "Hello world"; 

// white space within the tags

?>
    </body>
</html>

Will return

<html>
..
    <body>
        Hello world
    </body>
</html>

Upvotes: 0

Johannes Mittendorfer
Johannes Mittendorfer

Reputation: 1252

Note that there is a blank line between the two php blocks. It also get's displayed. Change it to

<?php
?><?php
echo "ok";
?>

and it should be fine.

Upvotes: 4

Related Questions