...

Hi! I’m Starx

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

Calling a method of an instance of a class

Question by Joe

Forgive me for asking such a novice question, but I can’t figure out how to call a method in PHP. Here’s what I’m trying to do (in pseudocode):

class Thing {
    public string Color() {
        return "taupe";
    }
}

Thing x = new Thing();
echo x.Color();

This should echo taupe as its result. The part I’m getting stuck on is the last line: invoking the Color method of x. How does one do this in PHP?

Answer by Jemaclus

In PHP, you would do something like:

class Thing {
   public function color() {
      return "taupe";
   }
}

$thing = new Thing;
echo $thing->color();

You were close 🙂

I suggest reading up on PHP’s OOP information here. They’ve got a lot of good information about how to set up Objects and different patterns and whatnot.

Good luck!

Answer by Starx

Here is an illustration

$x = new Thing(); //Instantiate a class

echo $x -> Color(); //call the method 
Read more

Does PHP have an equivalent of C/C++'s #ifdef?

Question by DavidH

I’m trying to define a constant, but I don’t want to redefine it if it’s already been defined.
Here’s a C sample:

#ifndef BASEPATH
#define BASEPATH /mnt/www
#endif

What is the most elegant way to do this in PHP?

Answer by rid

Use defined() and define().

if (!defined('BASEPATH')) {
    define('BASEPATH', '/mnt/www');
}

Answer by Starx

Use defined() function

if(!defined("constantname")) {
   define("constantname", "value");
}
Read more

HTML Background Image OnLoad

Question by jcmitch

I have a simple HTML page with a little JavaScript in it. The JavaScript launches onLoad in the body. The body also has a background image. The JavaScript launches before the background image is loaded. Is there a way to have the body onLoad wait for the body background image to load?

<body background="http://xxx.com/xxx.jpeg" id="myBody" onload="pageLoaded()">

Answer by Starx

If you want to make sure a script launches after all the images have been loaded, then use

$(window).load(function() {
//.......................
});

This event, will only fire once all the scripts, css, js, images have been load, unlike $(document).ready();

Read more

export variable in JavaScript

Question by Flo

Possible Duplicate:
Access a JavaScript variable from PHP

I have one JS code that return my geolocation (latitude, longitude) and I would like to reuse these information in a PHP code. My webpage has .php extention and I have set global variable but it doesn’t work.
How can I do that ?

<script type="text/javascript"> 
    function getCoordPosition(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(function(position){
                latitude = position.coords.latitude;
                longitude = position.coords.longitude;
            });
        }
    }
</script>

<?php
    echo 'Latitude is $latitude';
?>

Answer by Starx

One of the methods are from $_GET method

var test1 = "myvalue";
var link = "thispage.php";

window.location = link+"?test1="+test1;

Then read the value from the testpage.php

Another methods is $.get, or $.post request to a php page.

$.post("mypage.php", {
   myvar : "myvalue",
   "myanothervar" : "myanothervalue"
}, function(data) {
   //data contains the output from the script
});
Read more

How to get OS default encoding?

Question by alex347

What is the proper way of getting default OS encoding? For Linux it can be found here: /etc/sysconfig/i18n

If you think the best way is to read from that file, then can I rely it will work on all modern major Linux distributions? What about Windows?

Answer by Starx

The best way to detect encoding, is from the piece of text you are trying to read from.

Use mb_detect_encoding()[docs here] function

$str = "....."; //use you own logic to get the text
echo mb_detect_encoding($str);

Adding on to @Evert

Encoding happens when characters are displayed on the screen or CLI interface. It is not OS dependent, rather content specific.

Read more

Confusion about div — why is it not as wide as its contents, and how can I center it?

Question by Basit

Please note: I am new to CS. Brand new.

I want my button div to be placed horizontally inside the confirm div: example.

Right now my dialog-button div width is equal to the width of the confirm Div. Why?

I am just placing two buttons inside my Div, so it’s width should be equal to 128 (the total of two button witdh). Similarly the height should be equal to button height, but it isn’t.

Second i want that mt button-div placed center horizontally . I tried left: 50% inside my button-div. But it is aligning the left margin with the centre of the confirm div. How can i do it?

EDIT
————————————————–

enter image description here

Answer by Starx

May be I didn’t understand correctly, but if you want it inside then put it inside.

<div id="message">

    Are you sure you want to  

    <div id="dialog-button">
        <button>Ok</button>
        <button>Cancel</button>
    </div>             
</div>

Demo


Update 1

Right now my dialog-button div width is equal to the width of the confirm Div. Why?

Why, because <div>s are block tag, they always take 100% width of the containing element. It is not equal to the width of confirm Div.

To make the dialog-button take the actual width use display: inline-block as its CSS. Demo

Update 2:

To the best from what i understood. This is what you want. If not help me help you.

Update 3:

Ok, here is a demo with the image. I will leave the without image part to you. 😉

Read more

How to run multiple sql queries using php without giving load on mysql server?

Question by aslamdoctor

I have a script that reads an excel sheet containing list of products. These are almost 10000 products. The script reads these products & compares them with the products inside mysql database, & checks

  • if the product is not available, then ADD IT (so I have put insert query for that)

  • if the product is already available, then UPDATE IT (so I have put update query for that)

Now the problem is, it creates a very heavy load on mysql server & it shows a message as “mysql server gone away..”.

I want to know is there a better method to do this excel sheet work without making load on mysql server?

Answer by Starx

Ok, here is quick thought

Instead of running the query, after every check, where its present or not, add on to your sql as long as you reach the end and then finally execute it.

Example

$query = ""; //creat a query container
if($present) {
    $query .= "UPDATE ....;"; //Remember the delimeter ";" symbol
} else {
    $query .= "INSERT ....;";
}
//Now, finally run it
$result = mysql_query($query);

Now, you make one query at the last part.


Update: Approach this the another way

Use the query to handle it.

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

Reference

Read more

PHP mail function interrupting jquery .post return data

Question by SPI

I don’t really understand what’s going on here. I have a jquery script that sends form post data to a signup script, where upon an email is sent to the user signing up and the users Id is returned back to the calling jquery function where it is forwarded to yet another script for processing.

Problem: The script works great if I leave out the mail function, however, introducing it into the script blocks the variable from being returned to the calling jquery function. Any ideas what’s going on? Here is the Jquery script:

<script>
/* attach a submit handler to the form */
$("#purchaseForm").submit(function(event) {

    var intRegex = /^d+$/;


/* stop form from submitting normally */
event.preventDefault(); 


    $.post("process_signup.php", $("#purchaseForm").serialize(),function(data){
                                                if(intRegex.test(data)){
                    if(data!=0){
                        alert(data);
                    document.getElementById("bag_contents_hidden").value=data;  
                    $.post("process_order.php", $("#bag_contents").serialize(), function(data2){
                    if(data2){
                    window.location.replace("?process=100&success=1");  
                    }else{
                    window.location.replace("?process=100&fail=1"); 
                    }
                });

            }
        }

else{       //Not Important, validation stuff       


}



        });

  });

//

PHP 
                      if($oid){
               if(mail($email,$title,$message,$headers,'O DeliveryMode=b')){

                    echo $oid;
                    unset($_POST['processorder_hidden']);
                    }else{
                    echo 0; 
                          }
                }

Answer by Starx

Since you are expecting a data from the post request any errors generated by mail function is sure to create problems.

Here is a correct way to solve it

$status = @mail($to, $subject, $content); //suppress the error generated from being passed to the view

//instead handle it later
if($status) {
   //handle success
} else {
  //handle unsuccess
}
Read more

preventDefault() is not working giving object does not support this property

Question by JainNavneet

I want to set maximum length of a textbox to 7 and stop further keys entering and using preventDefault but its giving error
My Code is below

function crInputRK(ctrlid, ControlValue, size, clsName)                                    {

    var newTextBox = crE('input');
    newTextBox.type = 'text';
    newTextBox.style.fontSize = ".9em";
    newTextBox.style['width'] = size;
    newTextBox.style['height'] = '12px';
    newTextBox.style['float'] = 'none';
    newTextBox.style['margin'] = '0 0 0 10px';//added on 13feb2012
    //newTextBox.maxLength = '3';
    newTextBox.id = ctrlid;

    newTextBox.className = 'inputDate';

    //newTextBox.onchange = "javascript:return EnableButton();";

    //ControlValue = getControlValue(ctrlid);
    if (ControlValue != "")
        newTextBox.value = ControlValue;
    if (ControlValue == "Multiple")
        newTextBox.disabled = true;
      newTextBox.setAttribute("onkeypress", "javascript:SetMaxLength(event,this);");


    return newTextBox;
}


function SetMaxLength(e, txtbox)                                                           {

    var MaxLength = 7;
    if (_$(txtbox.id).value.length >= MaxLength) {
        e.preventDefault();

    }
}

Answer by Starx

It is possible using .preventDefault();

 $("body").find("input[type=text]").each(function(k,v) {
     $(this).on('keypress', function(event) {
        limit = 7; //for example
        val = $(this).val();
        len = val.length;
        if(len > limit-1) { event.preventDefault(); }
             });
    });

Demo

Read more

jQuery Tipsy won't work with jQuery.each() and live:true

Question by papaiatis

Note: This question was marked as solved once, but it figured out that upgrading to the latest jQuery was fixed only one issue. Please see the updated question below for the remaining issue.

Hi all,

I have just run into a weird issue with jQuery.Tipsy.

Here’s a simplified demo fiddle: http://jsfiddle.net/6nWtx/7/

As you can see, the lastly added a.tipsy2 element does not get tipsyfied. The .tipsy2 elements are being tipsyfied within a jQuery.each() function and at this point I have the problem. Without the each() it works. Unfortunately, I need .each() to iterate through the elements to do some other stuff before I call tipsy().

Any suggestion?

Here’s the source code of Tipsy: https://github.com/jaz303/tipsy/blob/master/src/javascripts/jquery.tipsy.js

IMHO the problem is using the combination of jQuery.each() and Tipsy option live:true

Update:

The other stuff I want to do before calling .tipsy() is checking for some optional configuration.

For example: <a href="#" title="This is a tooltip" class="tipsyfy delayed">Help</a>"

In this example I will add the following option to Tipsy: delayIn:1000 If there is no delayed class associated to the element this parameter will be delayIn:0.

Using the same logic, I want to specify the following classes as well: show-top, show-left, show-right, show-bottom for the Tipsy option called gravity.

Example: <a href="#" title="This is a tooltip" class="tipsyfy delayed show-left">Help</a>"

The full code:

$(".tipsyfy").each(function () {
    var a = "s",
        b = 0;
    if ($(this).hasClass("show-left")) a = "w";
    else if ($(this).hasClass("show-down")) a = "n";
    else if ($(this).hasClass("show-right")) a = "e";
    if ($(this).hasClass("delayed") && $(this).attr("data-delayIn") != null) b = $(this).attr("data-delayIn");
    $(this).tipsy({
        gravity: a,
        fade: true,
        live: true,
        delayIn: b
    })
})

And here is a full jsFiddle demo with all the stuffs I want to do: http://jsfiddle.net/xmLBG/1/

Answer by mgibsonbr

If you use jQuery 1.7.1 instead of 1.6.4 it will work. Maybe that live feature is relying on something buggy with the older versions, or some not-yet-implemented feature.

Update: from what I understood, you want the tipsy plugin to be called to every element with the .tipsyfy class, present now or added in the future. You don’t want to (or can’t) call it explicitly before insertion. You’re trying to accomplish that using the live option of the plugin. Is that right?

If that’s the case I can offer a workaround. I tried to use on (since jQuery’s live is deprecated) to bind some code to the load event, but it didn’t work, so I bound it to mouseenter and checked whether or not the plugin was already built for that element. If not, it builds it and re-triggers the event.

$(document).on("mouseenter", ".tipsyfy", function(e) {
    if ( !$(this).data("tipsy") ) {
        e.preventDefault();
        var a = "s",
            b = 0;
        if ($(this).hasClass("show-left")) a = "e";
        else if ($(this).hasClass("show-down")) a = "n";
        else if ($(this).hasClass("show-right")) a = "w";
        if ($(this).hasClass("delayed") && $(this).attr("data-delayIn") != null) b = $(this).attr("data-delayIn");
        $(this).tipsy({
            gravity: a,
            fade: true,
            live: true,
            delayIn: b
        }).trigger("mouseenter");
        return false;
    }
});            

Live example at jsFiddle.

For a small optimization, if the sole purpose of the .tispsyfy class is to instruct the plugin creation, and you don’t need it afterwards, you can remove it prior to re-triggering the mouseenter. This way the checking code won’t be called over and over again:

$(this).tipsy({...}).removeClass("tipsyfy").trigger("mouseenter");

Answer by Starx

Can’t you do this instead? It is what you are asking.

$(".tipsy1,.tipsy2").tipsy({live:true,fade:true});
$(".tipsy2").each(fucntion() {
    //do your stuff
});
Read more
...

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