...

Hi! I’m Starx

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

Checking password match returns "Passwords match" when both fields are empty

Question by Igal

I’m making a registration form and I want to check if the user has matching passwords while he’s typing and give him the appropriate message. So far everything works, except for these things:

  • When the user deletes everything from Confirm Password field it still
    gives him a message “Passwords do not match” while I want to give him
    no message or a message saying “Please confirm password”.
  • When the
    user deletes everything from both fields, it gives him a message
    “Passwords match”, while it should give him no message at all.

Here’s my code:

$(function () {
   $("#txtNewPassword").keyup(checkPasswordMatch);
   $("#txtConfirmPassword").keyup(checkPasswordMatch);
});


function checkPasswordMatch() {
    $("#divCheckPasswordMatch").html("");
    var password = $("#txtNewPassword").val();
    var confirmPassword = $("#txtConfirmPassword").val();

    if (password == "" && confirmPassword == ""){
        $("#divCheckPasswordMatch").html("");
        $("#divIsPasswordExist").html("");
    }
    else if (password != "" && confirmPassword == "") {
        $("#divCheckPasswordMatch").html("");
    }

    else if (password == "" && confirmPassword != "")
        $("#divIsPasswordExist").html("Password cannot be empty!");
    else
        $("#divIsPasswordExist").html("");


    if (password != confirmPassword)
    {
        $("#divCheckPasswordMatch").removeClass("registrationFormConfirm");
        $("#divCheckPasswordMatch").addClass("registrationFormAlert");
        $("#divCheckPasswordMatch").html("Passwords do not match!");
    }
    else
    {
        $("#divCheckPasswordMatch").removeClass("registrationFormAlert");
        $("#divCheckPasswordMatch").addClass("registrationFormConfirm");
        $("#divCheckPasswordMatch").html("Passwords match.");
    }
}

Any ideas, please?
Thank you!

Answer by Hardik Patel

......
        if (password == "" && confirmPassword == ""){
            $("#divCheckPasswordMatch").html("");
            $("#divIsPasswordExist").html("Password and Confirm Password dosen't exists");
            return;
        }
        else if (password != "" && confirmPassword == "") {
            $("#divCheckPasswordMatch").html("Confirm Password dosent't exists");
            return;
        }
        else if (password == "" && confirmPassword != ""){
            $("#divIsPasswordExist").html("Password cannot be empty!");
            return;
        }
        else{
            $("#divIsPasswordExist").html("");
        }
        if (password != confirmPassword)
        {
            $("#divCheckPasswordMatch").removeClass("registrationFormConfirm");
            $("#divCheckPasswordMatch").addClass("registrationFormAlert");
            $("#divCheckPasswordMatch").html("Passwords do not match!");
        }
        else
        {
            $("#divCheckPasswordMatch").removeClass("registrationFormAlert");
            $("#divCheckPasswordMatch").addClass("registrationFormConfirm");
            $("#divCheckPasswordMatch").html("Passwords match.");
        }
.........

Answer by Starx

There is a more elegant way to do this. Change your conditions to this

if(password.length > 0 && confirmPassword.length >0) {
    if(password == confirmPassword) {
        //confirmed
    } else {
       // not confirm
    }

} else {
   //not entered
}
Read more

Change the background image "on click" with jQuery

Question by wpdesign

I´m new to jQuery and I´m intressred in showing different background image
on click event. Is there any easy way?

Answer by Starx

Its as simple as this

$("#mylink").click(function() { 
           // ^ Attach a function on click event of an element with id="mylink"
  //Change the css of a element with id="myDiv"
  $("#myDiv").css("backgroundImage", "url(newimage.jpg)");
               // Note ^: In jQuery, the parameters with "-" as define that way
               // But of course .css() supports "-" also, but make a habit of doing in camel-case
});

Demo

Read more

PHP SQL – Advanced delete query

Question by Marc

I have a table with 3 columns: id, date and name. What I am looking for is to delete the records that have a duplicate name. The rule should be to keep the record that has the oldest date. For instance in the example below, there is 3 records with the name Paul. So I would like to keep the one that has the oldest date (id=1) and remove all the others (id = 4 and 6). I know how to make insert, update, etc queries, but here I do not see how to make the trick work. Thank you in advance for your replies. Cheers. Marc

id, date, name

1, 2012-03-10, Paul
2, 2012-03-10, James
4, 2012-03-12, Paul
5, 2012-03-11, Ricardo
6, 2012-03-13, Paul

mysql_query(?);

Answer by Starx

The best suggestion I can give you is create a unique index on name and avoid all the trouble.

Follow the steps as Peter Kiss said from 2 to 3. Then do this

ALTER Table tablename ADD UNIQUE INDEX name (name)

Then Follow 4 Insert everything from the temporary table to the original.

All the new duplicate rows, will be omitted

Read more

Framework for database manipulation

Question by Priyank Bolia

Is there a PHP framework, that lets me write such code.

class Item
{
    private $_id; //primary key
    private $name;
    private $price;
    function __construct($name, $price) {
       $this->name = $name;
       $this->price = $price;
    }
}
...
$item = new Item(...);
db->Save($item);
...
db->Delete($item);
...
db->Update($item);
...
Item[] = db->Fetch($whereClause);

Yes Admins, I searched on Google, but I got lost in the vast sea (Doctrine, Propel, ActiveRecords,…), asked a different question on SO (which prohibited me from comparison), so I am asking differently now, which framework lets me write such simple code, without much additional coding, no XML, YAML.
Or additionally how to write such if not there. Any pointers will be helpful. Off course I have PHP 5.3 and can use PDO, but performance is a concern (magic functions…), not extensive features list (we support this thing also, that you will never use).

OOPS: forgot to add, don’t want a framework like CakePHP, etc. I am writing simple php without frameworks, want just some libraries that I can include into my project and call the above syntax. Its ok for me, if it requires a little SQL behind.

Answer by Starx

There are many frameworks. See this for an example.

Every frameworks have there own way of API, through which you can use many features, such as db, xml.

  1. For ORM only Doctrine is very Excellent
  2. For rapid development and scaffolding features Codeigniter is very good.
  3. For in-depth framework with many pre-built libraries Zend-Framework is one of the best. It has libraries for Doctrine too.
Read more

Check .length before applying substr()?

Question by Mike Hayes

In Javascript, is it better to do this:

var string = 'hello';
if(string.length > 10) {
    string = string.substr(0,10);
}

or simply:

var string = 'hello';
string = string.substr(0,10);

I know the performance difference between the two won’t be anything huge but I like my JS to run as lightly as possible!

Which is the best to use?

Thanks

Answer by Starx

Or, may be you can combine both

var str = 'hello'; 
str = str.length > 10 ? str.substr(0,10) : str;
Read more

Refer a friend functionallity for a website in OOP

Question by JamesG

I am trying to get to grips with OOP, and just want a little advice on how to approach a problem.

I am making a refer a freind system on my online shop, so when a user registers they will enter an email address of a friend that refered them. This already existing friend then gets a certain amount of points (currency) in their online account.

I have made most of my system just using functions and procedural programming in PHP, but was wondering if anyone could point me in the right direction to making the refer a friend system in OOP, or even if it is worth building in OOP?

I do understand the basic principles of OOP, but not quite sure how to fully build a program from start to finish using it.

Answer by Starx

Ok, this is what i would do

Class User {
    // ....

    public function newUser(array $params, $isRefer = false, $referal = null) {
             // $params Parameters for new user, like name, address etc
             // $isRefer boolean value to trigger referal
             // $referal Email of the referer
        $newUser = new user_model($params); 
             //Create a DBO of user, as per the new parameters
        if(isReferal) { $referer = $this -> getUserIdByEmail($referal); } 
            //If is referal, get his id, based on email
        $status = $this -> add($newUser); //Add the user
            //Add the user
        if($status) {
             //Once it is success
             $referer = new User($referer); //Create a object of referer
             $referer -> addPoints(50); // Give bonus point

        }
        return true; //Indicate the success
    }

    public fucntion __construct($id = null) {
        if($id) {
           //create the object
           $this -> id = $id;
        }
        // ....
    }

    protected function getUserIdByEmail($email) {
        //get the id
        return $id;
    }

    protected function addPoints($points) {
        //add the points on database table
        return true;
    }
}

The DBO class might be something similar to this

class UserDBO {
   protected $name;
   protected $address;

   public function __construct(array $params) {
      $this -> name = $params['name'];
      $this -> address = $params['address'];
   }

}

Usage:

$userObj = new User();
$userObj -> newUser(array("name", address"), true, "referal@email.com");
Read more

MYSQL filter table by related options table with grouped records

Question by Konstantin

I have three tables:

items:

id   name
4   Item Blue, L
2   Item Blue, S
6   Item Green
8   Item L
9   Item Red, Blue, Green, S, M, L
5   Item Red, L
3   Item Red, M
1   Item Red, S
7   Item S

options:

id   group   name
1   1   red
2   1   blue
3   1   green
4   2   s
5   2   m
6   2   l

items_has_options:

item_id   options_id
1   1
1   4
2   2
2   4
3   1
3   5
4   2
4   6
5   1
5   6
6   3
7   4
8   6
9   1
9   2
9   3
9   4
9   5
9   6

How can i select items which have options: (red or blue or green) and (s)? I need to choose items which have some options from different groups. Options may have many groups, not only two. Result must be:

2   Item Blue, S
9   Item Red, Blue, Green, S, M, L
1   Item Red, S

Answer by barsju

Not sure this will work but it might get you started..

SELECT DISTINCT i.id, i.name FROM items i
INNER JOIN items_has_options ihs1 ON
    i.id = ihs1.item_id
INNER JOIN items_has_options ihs2 ON
    i.id = ihs2.item_id
INNER JOIN options o1 ON
    ihs1.options = o1.id AND (o1.name = "red" OR o1.name = "blue" OR o1.name="green")
INNER JOIN options o2 ON
    ihs2.options = o2.id AND o2.name = "s"

The idea is that you join with the options table twice, once for color and once for size.
You need the distinct since you will get duplicate rows from o1…

Answer by Starx

I haven’t tested this but, should work

SELECT count(iid), i.name FROM items i
INNER JOIN items_has_options ihs ON
    i.id = ihs.item_id
INNER JOIN options oON
    ihs.options = o.id
WHERE i.name ='Item Blue, S'
Read more

Get & format HTML tags from a simple string

Question by MicroEyes

I have a String variable say

strHTML = "<div class='abc'> This is a test <span class='xyz'> String </span> </div> "

that i m receiving from server. When I use

$('#container').append(strHTML);

it is displaying the whole string including HTML tag in “container”.

What i want is to take each HTML tag as HTML element in “Container” & apply class whever i defined in it..

Answer by MicroEyes

I did this working…
Actually, what i did is..

var strHTML = "<div class='abc'> This is a test <span class='xyz'> String </span> </div> ";
$("#container").html(strHTML);

Thankx to all for helping me..

Answer by Starx

Split your string and change them into DOM Object. Then you can manipulate them as you want.

Example:

var abcDiv = $("<div></div>");
abcDiv.attr('class', 'abc'); // add class
var xyzSpan= $("<span></span>");
xyzSpan.attr('class', 'xyz'); //add class

abcDiv.append("This is a test"); //Add the text
abcDiv.append(xyzSpan); //Add the span

$('#container').append(abcDiv); //insert the div
Read more

Not able to get the json response

Question by Nirav Gandhi

    var myurl="https://raw.github.com/currencybot/open-exchange-rates/master/latest.json";

    $.ajax(
    {
     url:myurl,
     type:"POST",
     dataType:"JSONP",
     success:function(myObj)
       {
        console.log(myObj);  
       }
   });

I tried using the shorthand getJSON, but console throws me an error “use POST request”.
And using the code above, console states that “Invalid Label”.

Answer by Starx

Use $.getJSON(), it is shorthand function and very efficient too.

var myurl="https://raw.github.com/currencybot/open-exchange-rates/master/latest.json";

$.getJSON(
  myurl,
  function(data) {
      //manipulate your json
});

But for the JSONP request, you should have callback parameter in the URL

As quoted on the documentation[here]

If the URL includes the string “callback=?” (or similar, as defined by the server-side API), the request is treated as JSONP instead.

Read more

How to get folder root from url?

Question by Earvin Bryan S. Co

How do you get the root folder from a php file?

For example

URL: http://localhost/project_name/

Result: return “project_name”

Answer by Starx

Use the parse_url() function for this

$url = $_SERVER['REQUEST_URI']);
$urlParse = parse_url($url);

echo $urlParse['hostname'];

However, this will only work, if you are using a webserver, for these type of url

http://www.mydomain.com

If you want this to work on a localhost, add some few lines

$url = $_SERVER['REQUEST_URI']);
$urlParse = parse_url($url);

$path = explode('/',$urlParse ['path']);
echo $path[1]; //gives project_name in your case
Read more
...

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