...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 29, 2012

PHP UTF-8 Encoding in HTML Input Box

Question by Wasim

Here what is in database

Seilpendel für Tragsysteme

now i am loading it into textbox via AJAX but what loads into textbox is

Seilpendel f�r Tragsysteme

but i want correct string Seilpendel für Tragsysteme into inputbox

i have tried

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

but not its working

Answer by mcdado

Make sure the db is encoded in UTF8, or use utf8_encode() or utf8_decode() when loading data from db or when writing back.

Answer by Starx

The correct way solving this problem is to configure database to use UTF8 as their character encoding in and out.

RUN The following query after connecting to the database, one time and everything should start working.

SET NAMES 'utf8';
Read more

Query update result in huge unexpected number

Question by user1251004

I have some problems with my hiscore table. Some players have got a lot of points really fast, more then possible. I post two code below:

The first one is the one I currently use, which cause the problem:

$name = mysql_real_escape_string($_POST['name']); 
$set = mysql_real_escape_string($_POST['set']); 


if ($set == 1 && isset($_POST['score']))
{
    $score = mysql_real_escape_string($_POST['score']); 

    $query = mysql_query("UPDATE users SET totalScore=totalScore + '$score' WHERE username='$name'"); 

    if ($query) 
    {
        echo 'success'; 
    }
    else {
        echo 'error'; 
    }

}

I tried to cast the score as an int in the code below, but the update result is a huge number (4294967295) to be set as the totalScore. The totalScore is of type int(25) and I set attribute to unsigned so a player can’t end up on the minus side.

Please help
Thanks

$name = mysql_real_escape_string($_POST['name']); 
$set = (int)$_POST['set']; 


if ($set == 1 && isset($_POST['score']))
{
    $score = (int)$_POST['score']; 

    $query = mysql_query("UPDATE users SET totalScore=totalScore + $score WHERE username='$name'"); 

    if ($query) 
    {
        echo 'success'; 
    }
    else {
        echo 'error'; 
    }

}

Answer by Starx

Its because you are adding a integer onto propably an integer datatype. There is no need of quotes and escaping, if you make sure the input is integer (which you are already doing)

"UPDATE users SET totalScore=totalScore + $score WHERE username='$name'" LIMIT 1;

Only you are updating the query based on the name, You might need to LIMIT the execution.

Read more

How can I resume setInterval after clearInterval has been called in javascript?

Question by Hcabnettek

I have this code which works ok but I would like to stop polling and clearInterval if the user is inactive (no mouse move) after say 5 iterations rather than be in a continuous loop.

var i, active = new Date, iter = 1;

$(window).on('mousemove', function(e){
active = new Date;          
});

i = setInterval(function(){
    if(new Date().getTime() - active.getTime() < 1000){
     console.log("sending active event to server.....");
             iter = 1;  
    else{
      iter++;
        if(iter >= 5){
           clearInterval(i);
        }
     }          
}, 2000);   

right now it checks every two seconds in this example. I would like to check the active date say 5 times and if its expired 5 iterations in a row, call clearInterval(i)… so something inside the mousemove callback should reinitialize the setInterval only if it’s currently not running. How can I accomplish this? Thanks for any tips and samples. I’d like to keep using an anonymous function if possible.

Answer by Starx

Seperate the Interval function

function intFunc(){
    if(new Date().getTime() - active.getTime() < 1000){
     console.log("sending active event to server.....");
             iter = 1;  
    else{
      iter++;
        if(iter >= 5){
           clearInterval(i);
        }
     }          
};

Now, call them on the two places you need

var i;
$(window).on('mousemove', function(e){
  active = new Date;          
  i = setInterval(intFunc, 2000);

});
i = setInterval(intFunc, 2000);
Read more

Javascript confirmbox + form inside it

Question by Waldema

I’m having a PHP/MySQL giftlist and people can click “reserve”-button to reserve one piece of gift. Thing is that in that list there is gift which has been wished like 10 times. So to reserve all 10 pieces of certain gift one has to click the reserve-button 10 times and javascript always confirm if one is willing to reserve one piece of that gift.

What I’m now after is that change that javascript confirm to confirm+form which will send data to action.php.

In HTML it would look like this:

<p>How many piece of gift are you willing to reserve?</p>
<form action="action.php" method="post">
    <input type="text" name="giftammount" />
</form>

And when confirm returns true it will submit the answer and action.php will do the magic for MySQL table.

So, is this even possible technically? Not that i’ve tried, i’ve spent several hours wondering this but can’t figure this out.

Answer by codeM0nK3Y

If you’re using jQuery UI then the dialog widget could be just what you need:

Use a modal dialog to require that the user enter data during a multi-step process. Embed form markup in the content area, set the modal option to true, and specify primary and secondary user actions with the buttons option.

Take a look at the jQuery UI page for an example and basic code

Answer by Starx

Javascript confirm box and a form are two totally different things.

One way you can solve this, is creating a modal box and simulating a confirm box + confirm dialog effect.

Few other functions like alert(), confirm() and prompt() only take text but not HTML

Read more

Reference and datatype checking, are these the same?

Question by Jon Lennart Aasenden

I have a simple function in my library that checks the validity of an object reference (object here meaning, a reference to a created HTML element, mostly DIV’s). It looks like this:

function varIsValidRef(aRef) {
    return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
}

While experimenting i found that this has the same effect:

function varIsValidRef(aRef) {
    return (aRef) && typeof(aRef) == "object";
}

I understand there are some controversies regarding the short hand () test? While testing against various datatypes (null, undefined, integer, float, string, array) i could find no difference in the final outcome. The function seem to work as expected.

Is it safe to say that these two versions does the exact same thing?

Answer by Wouter J

No, in my opinion these functions don’t work the same:

First option
If aRef is not undefined or null and the type of the var is object it returns true.

Second option
First we convert aRef to a boolean. Values like null, undefined and 0 become false, everything else become true. If it is true (so not one of those values) it checks if the type is object.

So the second option return false if aRef is 0, something you don’t want. And it isn’t option a elegant way to check it, because you check if an object or string or something is equal to a boolean.

And at least they don’t return the same thing. The first option returns a boolean, but the second option returns the value you put in the function if (aRef) is false:

varIsValidRef(0);
>>> 0

varIsValidRef('');
>>> ""

varIsValidRef(undefined);
>>> undefined

varIsValidref(null);
>>> null

Because JavaScript use these values as falsy values you don’t see the difference between these return values if you use if statements or something like that.

So I suggest you to use the first option.

Answer by Starx

Interesting case, but it seems logical for both to behave the same way despite being totally different. Lets see the first staement.

return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");

Here,

null and undefined both denote a false state combined with the ! infront, makes it equal to the expression aRef which will return true in case both are either not null or not undefined.

Read more

My if statement ALWAYS returns true, no matter what

Question by user1364363

This just is’t making sense to me at all.

This is my code:

boolean that = false;
        if (that == true);
        {
            System.out.println("That is " + that);
        }

And yet it will print the line even though my output is

That is false

I’m doing this in java and I’m using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What’s going on?

Answer by Peter Lawrey

A common mistake. Remove the ; at the end of the if statement.

BTW I always write the following if I use brackets and I use the code formatter of the IDE.

    if (that == true) {
        System.out.println("That is " + that);
    }

This means if you have a mis-placed ; or { it can be more obvious.

Answer by Starx

if (that == true);
              // ^ The extra colon you dont need
Read more

Using jQuery for vertical and horizontal centering

Question by JamesCharless

I’m using jQuery to horizontally center a div element that doesn’t have a default width. I’m using the following code, but it’s not working. if anyone could help me to understand why, it’d be very helpful. PS, I the height has a default height of 20, so that’s where the -10px comes from.

var w = ($(".notec").width() + 51) / 2;
$(".buttons").css("margin", "-10px 0 0 -" + w + "px");

Answer by Starx

Centering with respect to .notec. Width is not needed if the element is displaying as block element.

var h = ($(".notec").height() - $(".buttons").height()) / 2;
$(".buttons").css("margin", h+"px auto 0 auto');
Read more

Window resize issue in jQuery Popup

Question by agurchand

I started writing a very Simple jQuery Popup myself.

Here is the code

<script type="text/javascript">
 $(document).ready(function(){
    $("#pop").click(function(){
         openPopup();
    });
    $("#close").click(function(){
        closePopup();
    });
  });

function openPopup(){
$("#overlay_form").css({
    left: ($(window).width() - $('#overlay_form').width()) / 2,
    top: ($(window).width() - $('#overlay_form').width()) / 7,
    position:'absolute'
});

$("#overlay_form").fadeIn(1000);

   }
 function closePopup(){
$("#overlay_form").fadeOut(500);
}

$(window).bind('resize',openPopup);

</script>

Everything is working fine. But the problem is here in this code

   $(window).bind('resize',openPopup);

This code is to keep the popup in the center of the browser. But, even after i close the popup, if i resize the browser this code again opens up the popup.

I need to use a if condition somewhere in the code!. Where to use and how to use?.
Give me a solution please!.

Answer by Mark

Remove the .fadeIn() from the function and place it in the click handler.

$("#pop").click(function(){
  $("#overlay_form").fadeIn(1000);
  resizePop();
});


function resizePop(){
  if(!$("#overlay_form").is(':visible')){
    return;
  } 
  $("#overlay_form").css({
      left: ($(window).width() - $('#overlay_form').width()) / 2,
      top: ($(window).width() - $('#overlay_form').width()) / 7,
      position:'absolute'
  });
}

$(window).bind('resize',resizePop);

Answer by Starx

First of all bind is deprecated, use .on() from jQuery 1.7 and next, your event handling fails when the popup boxes is faded out, so limiting the resize then event handler to one function causes the script to break.

$(window).on('resize',function() {
   openPopup();
});
Read more

PHP – Summary of article

Question by user1257255

I’m working on news script and I would like to create summary function to get little of text from full text content. The function would get 200 characters of full text and then it would search for last space of these 200 characters. The function must also ignore any html or other code and show only first 200 characters of full text content.

Which function is the best for my problem and how to do that function?

Answer by mazzucci

Checkout this helper function from the CodeIgniter framework:

/**
* Character Limiter
*
* Limits the string based on the character count.  Preserves complete words
* so the character count may not be exactly as specified.
*
* @access   public
* @param    string
* @param    integer
* @param    string  the end character. Usually an ellipsis
* @return   string
*/

function character_limiter($str, $n = 500, $end_char = '&#8230;')
{
    if (strlen($str) < $n)
    {
        return $str;
    }

    $str = preg_replace("/s+/", ' ', str_replace(array("rn", "r", "n"), ' ', $str));

    if (strlen($str) <= $n)
    {
        return $str;
    }

    $out = "";
    foreach (explode(' ', trim($str)) as $val)
    {
        $out .= $val.' ';

        if (strlen($out) >= $n)
        {
            $out = trim($out);
            return (strlen($out) == strlen($str)) ? $out : $out.$end_char;
        }
    }
 }

You can use the function:

echo character_limiter($text, 200);

If you need to avoid HTML tags, you can use strip_tags function before calling the character_limiter function.

Answer by Starx

There is a simple function called substr($string, $position, $length), which can do this.

Use it like

$brief = substr($bigContent, 0, 200); //for 200 chars
Read more

returning DOM element objects as a string?

Question by Thomas T

I’m not sure how to phrase my question, so I’ll just post my code and explain what I’m trying to do:

function getNewElement(tagName, className, idName, text){
    var newElement = document.createElement(tagName);
    newElement.className = className;
    newElement.id = idName;
    newElement.innerHTML = text;

    return newElement;
}

If I call

getNewElement("div", "meow", "meow1", getNewElement("span","meow", "meow2", "blahblahblah"));

I just get

<div id="meow1" class="meow">[object HTMLSpanElement]</div>

So my question is, how would I write this to return a string with out converting (potentially expensive operation?) or ghetto patching with strings.

Update:
ghetto patch version:

function getNewElement(tagName, className, idName, text){
    return '<' + tagName + ' class=' + className + ' id=' + idName + '>' + text + '</' + tagName + '>';     
}

Achieves the functionality I wanted, but I feel like it’s not that elegant.

Answer by KooiInc

Not sure, but if you want the contents of #meow2 in the new element #meow1, using the statement as you do, this would be a solution:

function getNewElement(tagName, className, idName, contents){
    var newElement = document.createElement(tagName);
    newElement.className = className;
    newElement.id = idName;
    newElement.innerHTML = 
          typeof contents === 'string' ? contents : contents.innerHTML;
    return newElement;
}

now

getNewElement("div", "meow", "meow1", 
              getNewElement("span","meow", "meow2", "blahblahblah"));

would create a new element #meow1, with the content of a newly created element #meow2. Appended somewhere in the document it would look like:

<div class="meow" id="meow1">blahblahblah</div>

Otherwise, if you want #meow2 to be a child of #meow1, this would be a solution:

function getNewElement(tagName, className, idName, contents){
    var newElement = document.createElement(tagName);
    newElement.className = className;
    newElement.id = idName;
    if (typeof contents === 'string'){
      newElement.innerHTML = contents;
    } else {
      newElement.appendChild(contents);
    }
    return newElement;
}

Now if you would do:

document.body.appendChild(
     getNewElement("div", "meow", "meow1", 
                   getNewElement("span","meow", "meow2", "blahblahblah"))
);

this would be the result:

 <div class="meow" id="meow1">
  <span class="meow" id="meow2">blahblahblah</span>
 </div>

Answer by Starx

Change your function to take multiple type in parameter text

function getNewElement(tagName, className, idName, text){
    var newElement = document.createElement(tagName);
    newElement.className = className;
    newElement.id = idName;
    newElement.innerHTML = 
          typeof text === 'string' ? text: text.outerHTML;
    return newElement;
}
Read more
...

Please fill the form - I will response as fast as I can!