Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing white-space in AJAX response

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:

  • to trim() and ltrim() the php to get rid of whitespace
  • remove php exit tag
  • white-space-collapsing: discard; in the css and using the !important tag (this is not being read and the chrome yellow alert is on it)
  • trimming the response with jquery
  • using html notes to cut the space

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

like image 476
Semger Avatar asked Jun 18 '15 09:06

Semger


1 Answers

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.

like image 199
Cagatay Ulubay Avatar answered Sep 30 '22 07:09

Cagatay Ulubay