I have a php script which returns 0.28
. This is then fetched to HTML using AJAX, and inserted into a span. The problem is, it is inserted with 5 spaces and what appears to be a newline. jQuery then sees that as a change and updates the existing span with the new value when there is no change. It appears that the whitespace does not come from the php. I have tried:
Dumping the php variable:
string(4) "0.28"
This is how my browser returns it
<span id="response1" style="display: inline;">*5spaceshere*
0.28</span>
This is my script
$(function () {
function update() {
$.ajax({
type: "GET",
url: "balancefetch.php",
dataType: "html",
success: function (response) {
var trimmedResponse = $.trim(response)
if (trimmedResponse != $("#response1").html()) {
$("#response1").fadeOut(200, function () {
$("#response1").html(response);
$("#response1").fadeIn();
});
} else {}
}
});
}
setInterval(update, 5000);
update();
});
And my html
<div id="balance-div"><!--
--><p class="balance">Balance<span id="response1">Loading...</span></p><!--
--></div>
php
$balance = ltrim($balance);
echo $balance;
$balance
holds 0.26
So after testing and going trough several methods finding where the problem is, the source for this problem was found.
The main part why not using technics like trim
or a RegEx to remove whitespaces is, because that would fix the current problem, but not the source, so this would be just a bad workaround, so it was important to find the source.
The source problem was inside the configuration file, which had some whitespaces inside it and after including it inside the script, which is loaded via AJAX, the whitespaces also were included.
Solution: Remove the whitespaces of the config file and/or just remove the ?>
PHP-Ending Tag.
For further debuging steps, look into the comment section of the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With