...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
August 31, 2015

Checking if an instance's class implements an interface?

Wilco’s Question:

Given a class instance, is it possible to determine if it implements a particular interface? As far as I know, there isn’t a built-in function to do this directly. What options do I have (if any)?

interface IInterface
{
}

class TheClass implements IInterface
{
}

$cls = new TheClass();
if ($cls instanceof IInterface)
    echo "yes"

You can use the “instanceof” operator. To use it, the left operand is a class instance and the right operand is an interface. It returns true if the object implements a particular interface.

You can also do the following

public function yourMethod(YourInterface $objectSupposedToBeImplementing) {
   //.....
}

It will throw an recoverable error if the $objectSupposedToBeImplementing does not implement YourInterface Interface.

Read more
August 27, 2015

css selector for a node which doesn't contain a given selector with class attribute

Abc123’s Question:

How do I select the entire h4 node that doesn’t contain h3 with class=”avoid”? In this case I want to select the first and fourth h4 node.

<div>
<h4>
    <h1><h1>
    <h2><h2>
</h4>
<h4>
    <h1><h1>
    <h2><h2>
    <h3 class="avoid"><h3>
</h4>
    <h4>
    <h1><h1>
    <h2><h2>
    <h3 class="avoid"><h3>
</h4>
<h4>
    <h1><h1>
    <h2><h2>
</h4>
</div>

First of all. Having heading tags inside another is not valid. Saying that..

CSS is not capable of selecting a parent based on nested elements.

You need JS to do such selections. A good read is this.

Read more
August 6, 2015

Dispose submit button with ajax-jquery and php

Dan Costinel’s Question:

I have the following code, for learning porpose. In short, I want to grab some data from a database, with the help of a drop-down menu. My problem is that now I’m using a submit button to make the submit action. And the improvement that I want, is to get rid of the submit button, and grab the infos when the drop-down changes.

I’ve tried to make a function for the code between line 1 and 12, and call it with: <body onload="process()">, but it’s not working. Then I tried to put the onchange="this.form.submit()" attribute to the <select> element, but this doesn’t work also, because it sends the data to process.php like any normal submission when not using ajax.
Anyone know any fix? Thank you!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body onload="viewdata()">
    <form action="process.php" method="post" id="form">
        <select name="select" id="select">
            <option value="">Choose</option>
            <option value="1">supervizor</option>
            <option value="2">sef locatie</option>
            <option value="3">muncitor</option>
            <option value="0">toti</option>
        </select><br/>
        <input type="submit" value="Go"/>
    </form>
    <script type="text/javascript">
    var frm = $('#form'); // **LINE 1**
    frm.submit(function (ev) {
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (data) {
                $('#show').html(data);
            }
        });
        ev.preventDefault();
    });                    // **LINE 12**

    function viewdata(){
        $.ajax({
            type: "GET",
            url: "process.php"
        }).done(function( data ) {
            $('#show').html(data);
        });
    }
    </script>
    <br/><br/>
    <div id="show"></div>
</body>
</html>

You need to bind your processing on the change event of your drop down box.

$("#select").on("change", function(ev) {
    // Your ajax processing
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            $('#show').html(data);
        }
    });
    ev.preventDefault();
});
Read more
June 30, 2015

How Can i copy a mysql record and save with different id using PHP?

Sunny’s Question:

I am new in PHP. I have an idea. Can i copy a recoed of table and save it with different id in same table?

For example i have a web form with different fields. I use that form to store data in database. Now i have a page where i display that record and use CRUD operations. When user click on Edit Button it goes on Form where he see a Button of Create copy. When user click on Create Copy button it just begin to start making a copy of selected data and store same data with different id?

create copy

Here is a simple way. You can have multiple submit buttons. Like

<input type="submit" name="submit" value="Edit" />
<input type="submit" name="submit" value="Make a copy" />

When this forms get submitted, you can check which submit button was pressed by asserting with $_POST['submit'] or $_GET['submit'] if you method is GET.

For example:

if($_POST['submit'] == 'Make a copy') {
    $action = "copy";
} elseif($_POST['submit'] == 'Edit') {
    $action = "edit";
}

Using that you can know what the user wanted to do. Since you already have the data, just pass those to your function which creates a new record without the primary key.

Read more
May 29, 2015

convert string array to object array highchart and json

Code Demon’s Question:

I have this script

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

$.each(JSON.parse(response.portfolio), function(index, value){
    portfolio_in_arrears.push(value.in_arrears);
    portfolio_future.push(value.future_clients);
    portfolio_good_standing.push(value.good_standing);
    portfolio_ingrace_period.push(value.grace_period);
});

and this part of the highchart options

series: [{
    name: 'Future',
    data: portfolio_future //sample [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
    }, {
    name: 'In Grace Period',
    data: portfolio_ingrace_period //sample [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]
    }, {
    name: 'Arrears',
    data: portfolio_in_arrears //sample [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]
    }, {
    name: 'Good standing',
    data: portfolio_good_standing //sample [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
}]

I did successfully retrieved and parse the data from the json response and put on there corresponding array

var portfolio_in_arrears = [];
var portfolio_future = [];
var portfolio_good_standing = [];
var portfolio_ingrace_period = [];

but sadly when i tried to bind those array on the series option, it didnt work. When i check it on the console e.g. console.log(portfolio_future), I see the array like this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

which the proper array for the series option is

[3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]

so any ideas how to turn this

["146", "143", "123", "106", "106", "94", "76", "71", "69", "83", "66", "66", "98", "98", "96", "90", "85", "102", "102", "94", "135", "126", "111", "125", "116", "116", "108", "129", "113", "93", "102", "86", "86", "68", "81"]

to

[146, 143, 123, 106, 106, 94, 76, 71, 69, 83, 66, 66, 98, 98, 96, 90, 85, 102, 102, 94, 135, 126, 111, 125, 116, 116, 108, 129, 113, 93, 102, 86, 86, 68, 81]

as you can see, there’s no double qoutes stuff on each of the number.

You can solve this by specifying the value is strictly numeric. Use parseInt() function

Here is how you would use it.

portfolio_in_arrears.push(parseInt(value.in_arrears));

An example here.

Read more
April 21, 2015

Extract Top Level Domain from Domain name

Joao Alves’s Question:

I have an array of top level domains like:

['ag', 'asia', 'asia_sunrise', 'com', 'com.ag', 'org.hn']

Given a domain name, how can i extract the top level domain of the domain name based on the array above? Basically i dont care of how many levels the domain has, i only need to extract the top level domain.

For example:

test1.ag -> should return ag

test2.com.ag -> should return com.ag

test.test2.com.ag -> should return com.ag

test3.org -> should return false

Thanks

Updated to incorporate Traxo’s point about the . wildcard; I think my answer is a little fuller so I’ll leave it up but we’ve both essentially come to the same solution.

//set up test variables
$aTLDList = ['ag', 'asia', 'asia_sunrise', 'com', 'com.ag', 'org.hn'];
$sDomain = "badgers.co.uk"; // for example

//build the match
$reMatch = '/^.*?.(' . str_replace('.', '.', implode('|', $aTLDList)) . ')$/';
$sMatchedTLD = preg_match($reMatch, $sDomain) ? 
        preg_replace($reMatch, "$1", $sDomain) : 
        "";

Resorting to Regular Expressions may be overkill but it makes for a concise example. This will give you either the TLD matched or an empty string in the $sMatchedTLD variable.

The trick is to make the first .* match ungreedy (.*?) otherwise badgers.com.ag will match ag rather than com.ag.

parseurl() function gives you access to the host name of the url. You can use that to process the host name and find out the tld.

$url = 'http://your.url.com.np';
var_dump(parse_url($url, PHP_URL_HOST));

Next steps could be using explode() to split the host name and checking the last item in the exploded list. But I am going to leave that to you.

Read more
December 9, 2013

How to get available values for SET field?

Kirzilla’s Question:

Is there any way to get available values for SET field in table?

Thank you.

You can retrieve the possible values for a SET field using DESCRIBE myTableName mySetColumn or SHOW COLUMNS FROM myTableName LIKE mySetColumn:

  mysql> DESCRIBE myTableName mySetColumn;
  +-------+-------------------------------------------+------+-----+---------+-------+
  | Field | Type                                      | Null | Key | Default | Extra |
  +-------+-------------------------------------------+------+-----+---------+-------+
  | myset | set('Travel','Sports','Dancing','Dining') | YES  |     | NULL    |       |
  +-------+-------------------------------------------+------+-----+---------+-------+

Informative article here, manual here.

Here is how to get the possible values of SET using PDO extension.

function get_set($table, $column)
{

    global $db; //PDO DB Handler

    $sql = "SHOW COLUMNS FROM $table LIKE :column";
    $stmt = $db -> prepare($sql);

    $stmt -> bindParam(":column", $column, PDO::PARAM_STR, 50);

    try {
        $result = $stmt -> execute();
        $row = $stmt -> fetch(PDO::FETCH_ASSOC);
        $set = $row['Type'];
        $set  = substr($set,5,strlen($set)-7);
        // Split into an array.
        return preg_split("/','/",$set);
    } catch (PDOException $e) {
        echo $e -> getMessage();
        return false;
    }

}

[Source]

Read more
November 6, 2013

Copy table row data to a form in html

Joel Paxton’s Question:

I have a page which has a form/table.

I want to be able to click on a button at the end of a row, or the row itself and copy this data into another form on a separate html page, which can then be edited.

I know it probably has something to do with JQuery, however I have little to no experience with that.

If you require more details, I will happily provide.

EDIT:

Here is what it looks like now (it’s a table which has retrieved data from an xml file using SimpleXML):

<form name ="editEvent" method="post" action="editEvent.php">
    <table border="1">
        <tr bgcolor="#FFA500">
            <th>ID #</th>
            <th>Name</th>
            <th>Start Time</th>
            <th>End Time</th>
            <th>Category</th>
            <th>Description</th>
            <th>Location</th>
            <th>Picture Path</th>
            <th>Edit/Delete</th>
        </tr>   <tr>
          <td>1
          <td>Climbing</td>
          <td>09:00</td>
          <td>09:30</td>
          <td>Physical</td>
          <td>Description of what is going on</td>
          <td>where it is</td>
          <td>a photo link</td>
          <td><input type="submit" name="edit" class ="box" value="Edit/Delete"/></td>
      </tr> 
    </table>

I want it to end up in a table like this:

<tr>
        <td><input type="text" name="name" placeholder="Enter new event name..."/></td>
        <td><input type="text" name="time" placeholder="Enter event start time..."/></td>
        <td><input type="text" name="endtime" placeholder="Enter event end time..."/></td>
        <td><input type="text" name="category"/></td>
        <td><input type="text" name="description" placeholder="Enter a description of the event..."/></td>
        <td><input type="text" name="loc"/></td>
        <td><input type="text" name="picturePath" placeholder="Enter link to picture..."/></td>
        <td><input type="submit" name="create" class="box" value="Create"/></td>
    </tr>

Honestly, any help or even pointers in the right direction would be appreciated. I really don’t know what to do here. I’ve tried searching these forums and Google, but all I found is stuff on SQL and databases. I just want to transfer some HTML table row data on one page to a HTML form on another to be edited.

You need some methods of identification on the columns like class name. For eg: <td class="name">Climbing</td> then you can attach an event handler on the td of the row and fetch all the data and populate the form.

$("td").on('click', function() {
   var tr = $(this).parent('tr');
   var name = tr.find(".name").text();
   // Grab other values like this

   // and later populate the form
});

However, Instead of copying the data, an efficient solution would be to hold the primary key of the row in one of the td or on one of the data attributes and use it to fetch the record from the database and then fill up the form.

Read more
October 8, 2013

Using .on() and targeting elements with a specific ID

Brandon Durham’s Question:

I understand you can use .on() to attach a single click event to an element and then specify which child elements receive the click. So, for example:

$(this.el).on("click", "span", function () {
    alert("Bloop!");
});

I need to be a bit more specific and target selectors with a particular attribute, like this:

$(this.el).on("click", "span[data-placeholder]", function () {
    alert("Bloop!");
});

That doesn’t seem to work, though. As soon as I add the attribute it stops working. No errors, just doesn’t seem to find the elements.

Is that the expected behavior? Is there a way around it?

CLARITY

$(this.el) is just a div that contains a number of elements, some of which are <span data-placeholder="First Name"></span> tags. There could be dozens of those <span> tags and I didn’t want that many event listeners, so I thought I’d use .on() to add the click to the parent container.

You can choose to filter your spans

$('span', this.el).filter(function() {
     return $(this).hasAttr('data-placeholder');
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

Or if the placeholder is set via data api:

$(this.el).filter(function() {
     return $(this).data('placeholder') != 'undefined';
}).on('click', function() {
   //This is for all the spans having data-placeholder
   //...
});

This functions above select those elements specifically, if event delegation on the OP is needed, then you can do the following:

$('span', this.el).on('click', 'span', function() {
     if($(this).data('placeholder') != 'undefined') {
         alert('bloop');
     }
});
Read more
...

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