Search code examples
phpjavascriptjquerystrlen

My jQuery and PHP give different results on the same thing?


Annoying brain numbing problem.

I have two functions to check the length of a string (primarily, the js one truncates as well) heres the one in Javascript:

$('textarea#itemdescription').keyup(function() {
    var charLength = $(this).val().length;
    // Displays count
    $('span#charCount').css({'color':'#666'});
    $('span#charCount').html(255 - charLength);

    if($(this).val().length >= 240){
        $('span#charCount').css({'color':'#FF0000'});
    }
    // Alerts when 250 characters is reached
    if($(this).val().length >= 255){
        $('span#charCount').css({'color':'#FF0000'});
        $('span#charCount').html('<strong>0</strong>');

        var text = $('textarea#itemdescription').val().substring(0,255)
        $('textarea#itemdescription').val(text);
    }
});

And here is my PHP to double check:

if(strlen($_POST["description"])>255){
    echo "Description must be less than ".strlen($_POST["description"])." characters";
    exit();
}   

I'm using jQuery Ajax to post the values from the textarea. However my php validation says the strlen() is longer than my js is essentially saying. So for example if i type a solid string and it says 0 or 3 chars left till 255. I then click save and the php gives me the length as being 261.

Any ideas?

Is it to do with special characters, bit sizes that js reads differently or misses out? Or is it to do with something else? Maybe its ill today!... :P

Update: I added var_dump($_POST['description']) to see what was passed and it was returning escape slashes e.g. what\'s going on? I have tried adding stripslashes(); to no avail... where are they coming from?

UPDATE 2 - PROBLEM SOLVED:

Basically I think I just realised my server has magic quotes turned on... grr So I have stripped slashes before processing now. Bit annoying but it will have to do!!

Thanks for your help!

Thanks, Stefan


Solution

  • The easiest way to debug this is simply from your PHP script, by using: var_dump($_POST['description']

    I suggest you also use view source in your browser to see any escape code, special char codes, etc...