Typeahead Implementation in PHP/MySQL

First, you need to include all the necessary files for this to work. Place these three files in the head section of your page..

  • jquery-1.10.2.min.js 
  • bootstrap.min.js
  • bootstrap3-typeahead.min.js

Then, this script:

$(document).ready(function () {
    var objects = [];
    var map = {};
        source: function (query, process) {
                url: 'get_person.php',
                type: 'POST',
                dataType: 'JSON',
                async: true,
                success: function (data) {
                    objects = []; //resets the objects 
                    map = {}; //to avoid duplication
                    $.each(data, function (i, object) {
                        map[object.full_name] = object;
        }, //end source
        updater: function (item) {
            return item;
    }); //end of person typeahead
    $('#person').focus(function () {

This is my PHP code in which it passes a JSON object to my index.php file.

header('Content-Type: application/json');
 $query = mysqli_query($GLOBALS["___mysqli_ston"], "select userid,title,first_name, middle_name, last_name from tblperson;");
 $array = array();
 while($row = mysqli_fetch_array($query))
     $userid = $row['userid'];
  $title = $row['title'];
  $fname = $row['first_name'];
  $mname = substr($row['middle_name'],0,1);
  $lname = $row['last_name'];
  $data[$i]['userid'] = $userid;
  $data[$i]['fname'] = $fname;
  $data[$i]['mname'] = $mname;
  $data[$i]['lname'] = $lname;
  $data[$i]['full_name'] = $title.$fname." ".$mname."."." ".$lname;
 echo json_encode($data);

Just click the DEMO link above then copy the JavaScript source.


Everytime you tell girls you like them, they always asked "Why?". And I always go with the reason, "I just like you". And then, end of conversation.

Oh girl, I'm sorry. If you can only dissect my body and see what I felt about you. You'll be spending lots of hours reading all my reasons. Because sometimes with my limited source of words and vocabulary, I can't find the exact word. So, maybe you can?

"That feeling between like and love."
Hmmmn, getting there?
Nah, I'm not fond of words.

It's just sad that women love words. I know that you need to spit it out sometimes. Unfortunately, I'm not good in speaking. I haven't confess personally, like expressing my feeling like it's the end of the world. I haven't done that. And I don't have plan doing it except in my wedding vow.

When I tell you I like you , it's always true.
And it means I like every details about you. The soul within your body and all the words; the good and bad that may came out on your mouth.

You see me as a childish and immature person in my age. Oh girl, I've been through a lot. I've experienced the most painful thing already. So, I can always deal with opinions and criticisms. It wouldn't matter if you're not important to me but you are. So, I'll take it and make myself better. Well, of course not for you but for my self-growth.

I'm a happy person but love sad songs. You have to see people in their loneliest moment for you to deeply understand them. It's not enough to be good to them, you have to lift their spirit as much as possible. In this physical world that we live in, I don't strive for greatness. I work hard to be happy. But be happy with valid and righteous reasons. I define happiness as the absence of bitterness from the pain you have suffered. By thinking that you are more than enough and incomparable with others. By recognizing and accepting your imperfections because someday you will find someone that will fill those holes up and will embrace all your flaws. So, don't worry about love. Afterall, it's FREE.

Accept the things you can't change.
Have the courage to change the things you can.
And have the wisdom to know the difference.

It's a quote from Barry Allen's mom but I also heard it from social meetings of alcoholics, addicts, etc. Don't ever beg for love. Because, a love that is formed out of pity will break easily. So, don't ever do that. There is always someone out there who secretly loves you. (and then she smiles because she loves me. HAHAHAHA)

A perfect partner should always brings out the best in you. Who will help you grow in all aspect. Sometimes I wonder why those girls that I dearly liked doesn't like me? And I have this in my mind:

"Ok, it opens up an opportunity for other girls." HAHAHA

I just love girls who smile a lot. (and then she smiles again. HAHAHAHA)

Why are you really reading this? This is just a random thought because my mind loves to fly when I sleep early. So, instead of sending it in air, I decided to write it down. :)

And the song for this babble:

...now she's gone!

I just told her I like her, and now she's gone(not gone, gone). Am I that powerful? hahaha

Well, I am not that proud of myself but I'm always fine with it. Like really, as much as I want her. I just don't beg. It's not my style and I don't even know how to please/court a girl. Which makes me wonder, how did I get a girlfriend before? :)

Anyway, 2015 is coming! I have these list; a new year's resolution:

  • I'll try to go to church as often as possible.
  • Maybe be more mature in interacting with people esp. girls. HAHA
  • Mind OVER Emotion thing. I overthink a lot.
  • I'll work harder. I want to finish my Master's Degree as soon as possible to get married. HAHA
  • I'll sleep early like 10:00 PM.
  • Live healthy? Less caffeine and more water.
I guess that's it! I am happy with my life right now. What more can I ask for? Ahh there's one thing, I want to learn Nihongo. I got plans, you know? haha

My Sweet...Moon!

When this song hits me, I listen to it all over and over again. It's a bit sad but inspiring. I really love kids, like dreaming of having one right now. But I also have this in my mind that I'm not yet capable of giving her(I want a girl BTW) a very beautiful life.
I love the man you're making me
Yeah, every day I'm gonna prove there's nothing I won't do for you
Such a great love for his child.
OK, I should take up guitar lesson now 'cause I'm gonna write a song for my future Naleigh Moon.

Export Data from QuerySet as Excel File in Django

Let's say you have this function in your views.py:
def funtion_name(request):
    if request.method == "GET":
        get_id = request.user.id

        args = []
        kwargs = {
            'landproperty__sownerid__id': get_id,
            'geom__distance_lte': (pnt, D(km=kmdistance)),
            'narea__lte': getarea

        mm = YourModelHere.objects.filter(*args, **kwargs).values_list('fielname1', 'fielname2', 'fielname3','fielname4')
        request.session[0] = mm
        return HttpResponse(json.dumps(list(m)), content_type='application/json')

In order to get or pass the QuerySet from this function, you need to store it in a session as shown above.

Here's how to create an excel file:
def create_excel(request):
    book = xlwt.Workbook(encoding='utf8')
    sheet = book.add_sheet('untitled')

    default_style = xlwt.Style.default_style
    datetime_style = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')
    date_style = xlwt.easyxf(num_format_str='dd/mm/yyyy')

    headers = ['Table Header 1', 'Table Header 2', 'Table Header 3', 'Table Header 4']
    values_list = [headers] + list(request.session[0])

    for row, rowdata in enumerate(values_list):
        for col, val in enumerate(rowdata):
            if isinstance(val, datetime):
                style = datetime_style
            elif isinstance(val, date):
                style = date_style
                style = default_style
            sheet.write(row, col, val, style=style)

    response = HttpResponse(mimetype='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename=example.xls'
    return response

That's it! Just use the session variable from the previous function (funtion_name).

I like her a lot...

I like her a lot that I stop and just stare her smile like forever. What the F***! I always love cute people and those who smiles like an anti-inflammatory capsule. Women really are powerful  being! Like drugs, they can ease pain and worsen it. They're like a double-edge sword. :D

Too bad, I'm so pessimistic! But I think, just this time I'll be hopeful. hahaha
Like I always say, for a long time I don't like being close to a woman, like having a romantic closeness. Sounds gay! hahaha
It's a choice! I do date sometimes but I just thought that I don't need a girlfriend that time. Too many reasons, right? I guess all those reasons won't matter if your feeling towards that girl is greater than those reasons. It's all about their weight.

And the song for this babble,

#MusicPlaylist 1: Getting a Good Night's Sleep

I usually don't play music when I want to sleep 'cause sometimes I sing along with it.

I have to tell you this
Cause my heart goes wild
-Russian Red


When in comes to dancing, Lorde is the BEST! :D
I really love her, it makes my jaw drops and think of something weird. That's how good she is, actually she's just feelin' the song. 

Nah...just watch this video.

Changing password in Django

Add this to your urls.py:

url(r'^accounts/change-password/', 'django.contrib.auth.views.password_change',
    {'post_change_redirect' : '/accounts/password-changed/'}),
url(r'^accounts/password-changed/', 'django.contrib.auth.views.password_change_done'),

Just edit the links above. Then in you templates folder, create new folder and name it  registration . . Then create this html file below:

{% extends "edit_profile.html" %}
{% block head_title %}Change Password{% endblock %}
{% block content %}
<div class="jumbotron" style="width: 940px; margin: 80px auto; border-radius: 5px;">
    <form method="post" action=".">

         {% if next %}
                <input type="hidden" name="next" value="{{ next }}" />
            {% endif %}
        <input type="submit" value="Change" class="btn btn-primary btn-lg" />
        {% csrf_token %}
{% endblock %}

{% extends "edit_profile.html" %}
{% block head_title %}Password Change Successful{% endblock %}
{% block content %}
<div class="jumbotron" style="border-radius: 5px; margin: 80px auto; width: 940px;">
<div class="alert alert-success" style="padding: 5px;">
Your password has been changed successfully. Please <a href="https://www.blogger.com/accounts/logout/">re-login</a> with your new credentials
        or go back to the <a href="https://www.blogger.com/accounts/loggedin/">main page</a>.
{% endblock %}

That's it! It should work fine. Here's what it looks like using Bootstrap.

Serializing Objects and Passing Multiple JSON Data in Django

Below is just an example, just replace the necessary Models and Queries:

def pins_info(request):
 if request.method == "GET":
  getpin = request.GET.get('pin', None)
  keyvals = OrderedDict([
   ('taxdec', 'landproperty__ctaxdec'),
   ('brgy', 'ssectionid__sbrgyid__cbrgyname'),
   ('landarea', 'narea')
  keyvals1 = OrderedDict([
   ('mydescription', 'description')

  m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
  reference = ButuanMaps.objects.get(clandpin=getpin).geom
  within = SoilType.objects.filter(geom__contains=reference).values_list(*keyvals1.values())
  within1 = ErosionMap.objects.filter(geom__contains=reference).values_list(*keyvals1.values())
  result = dict(zip(keyvals, zip(*m)))
  result1 = dict(zip(keyvals1, zip(*within)))
  result2 = dict(zip(keyvals1, zip(*within1)))
  data = json.dumps([result, result1, result2], cls=DjangoJSONEncoder)
  return HttpResponse(data, content_type='application/json')
and in your template:
success: function(data) {
    taxdec = data[0]['taxdec'];
    brgy = data[0]['brgy'];
    landarea = data[0]['landarea'];
    soiltype = data[1]['mydescription'];
    erosion = data[2]['mydescription'];
    var inputform = $('#forminput').val();
        "<tr><td class=\"bold\">Tax Declaration </td><td>" + taxdec +
        "</td></tr>" + "<tr><td class=\"bold\">Barangay</td><td>" +
        brgy + "</td></tr>" +
        "<tr><td class=\"bold\">Area of Land</td><td>" + landarea +
        " m&sup2;</td></tr>" +
        "<tr><td class=\"bold\">Soil Type</td><td>" + soiltype +
        "</td></tr>" + "<tr><td class=\"bold\">Erosion Type</td><td>" +
        erosion + "</td></tr>");
In order to identify the index of the data, just look up the console:

PS: Add `from collections import OrderedDict`,and from django.core.serializers.json import DjangoJSONEncoder in your views.py