Saving data in dynamically generated text fields into the database

In this tutorial, I’m going to show you how you can save the data inputted from a dynamically generated text field into the database.

I consider this one a quick tutorial, since most of it has already been tackled in the first part:

Generating form elements using jQuery

All we have to do now is to write the php code which will loop through the values of those text fields.

Requirements

You must already have the script which allows you to generate text fields and select fields using jquery. Though we won’t really use the select field in this tutorial.

image

If you have not written it yet, then I advice you to go check out the tutorial which I linked above. Or just check my mediafire folder. You can see the full post about the folder in the files category. I currently don’t have internet connection, and I’ll probably publish this one early tomorrow so bear with me if I don’t have links for you.

Assumptions

You should already know how to make use of arrays, read arrays, and create arrays in php. And that $_POST is also an array. A container for all the values of input fields in an html form.

Procedure

Okay, so I won’t spoil the excitement any further. Here’s the 3 liner code which gets the job done:

foreach($_POST['tx'] as $tx){
		$db->query("INSERT INTO tbl_names SET names='$tx'");
	}

Yup, its just a simple foreach loop. Nothing fancy about it. As long as you know how arrays are formed in php, you are good to go. Using print_r will give you an idea, on what is this code all about:

This was the output when I clicked on the submit button:

Array ( [tx] => Array ( [0] => data [1] => integrated [2] => entity [3] => blog ) )

As you can see, php automatically assigns a value to the brackets which we placed on the last tutorial:

<input name="tx[]"/>

That’s not the full code from the last tutorial, but at least you already get what I mean. Those values assigned by php, served a purpose of being the index for each of those generated text fields.

Yeah, I guess my explanation sucks. So just study the array returned by print_r and you will know what the heck am I talking about.

Using ajax, in saving those data might be a little bit complicated. But I’ll show it to you next time I got lazy of coding the system that we are creating.
And speaking about system. I guess I’ll take this opportunity to give you, the awesome reader of this sucker blog. An update of my life, to make this post a little bit unique, because the internet is so wide and what I’m talking about might already exist somewhere else.

Life Update and Conclusion

Were working on this system called the Business Permit and Licensing System. And I admit that this isn’t easy to make considering the sheer amount of data to be stored in the database, the number of tables which are connected together (oh heck!, lots of join queries!). And other factors which unfortunately haven’t entered my mind yet.

That’s it for this tutorial, thank you so much for reading. Please don’t hesitate to use the comments section below if you didn’t understand something, you want to suggest something, or anything else that you wish to say to this boring blogger.

How to use php and datalist for easier auto-suggest input field

In this tutorial, I’m going to show you how you can add an auto-suggest functionality to a text field. Which loads the data from a mysql database. For those of you who aren’t updated on the new form features in html5. Datalist are one of them. And at the time of writing of this tutorial only works on Firefox 4, 5 and Opera 10, 11.

Here’s a neat demo at wufoo.com:

http://wufoo.com/html5/attributes/05-list.html

Go ahead and try that on the browsers I mentioned a second ago. It won’t work in Safari, IE, and Chrome at this point in time.

Okay, so back in the main topic of this tutorial. Here are the requirements.

Requirements

  • Browser with support for datalist
  • Web server (Wampserver will do if you’re on Windows)

 

Assumptions

As usual, the assumptions depends on the requirements. You must at least know the basics of php, and mysql. The most important is that you already know how to perform mysql queries from a php script and output the data in the browser.

 

Procedure

First, you have to import your database configuration to the file that you are working on:

<?php require_once('db_config.php'); ?>

Note that I am using the ez sql library so the code might look a bit different for you. If you are using the common mysql_query() or mysql_num_rows() to communicate with the mysql database.

Next, perform a query which will check if there are actually records in the table. So that we won’t be wasting server resources fetching data which doesn’t even exist:

$res_num = $db->query('SELECT barangayID, barangay FROM tbl_barangay');

The variable $res_num will have a value greater than 0 if the query returned 1 or more results.

Next, perform the query which will get results from the table. The get_results() function in ez sql will just return an array of the records which was fetched by the query.

$sel_brgy = $db->get_results('SELECT barangayID, barangay FROM tbl_barangay'); 

Let’s pause with this queries for a while and create the form fields which will be used by the user. We added an autocomplete attribute and set it to off. This is to prevent the autocomplete built-in feature in the browser from messing with our beautiful auto-suggest feature.

<label for="brgy">Barangay:</label>
<input type="text" list="barangay" autocomplete="off" id="brgy">

If you are still wondering what the hell is the use of the label attribute. Then go ahead and click the label in the browser and see for yourself where the cursor goes.

So now, we create the datalist field. Note that the list attribute of the input field should be the same with the id attribute of the datalist field.

<datalist id="barangay">
   //loop goes here
</datalist>

Inside the datalist field, we loop through the array which was stored in the $sel_brgy variable.

<?php if($res_num > 0){ ?>
	<?php foreach($sel_brgy as $sb){ ?>
		<option value="<?php echo $sb->barangay; ?>"><?php echo $sb->barangay; ?></option>
	<?php } ?>
<?php } ?> 

That’s pretty much all of the code required in providing auto-suggest functionality to a text field. It was made easier because of the new form features in html5.

Here’s an output, rendered in Firefox 5:

image

 

Conclusion

Really simple interface, that’s why I prefer to using this instead of those stylish jquery auto-suggest plugins. And speaking of jquery, we didn’t even use the ajax() function in jquery to have this nice little functionality. It’s just plain html and php. That’s it for this tutorial, see you again next time. Thanks for reading!

Generating form elements using jquery

Last time I showed you how you can generate form fields using javascript and a little bit of jquery:

How to generate form fields using javascript

This time, I’ll show you how you can do it in jquery with a little bit of javascript.

Requirements

  • Jquery core

Assumptions

Yep! It’s the first time that I’m going to do this section. A proper introduction is needed. Assumptions section is where I speak of  all the things which you need to know first before trying to read a tutorial. So in this tutorial, I assume that you already know the basics of jquery and javascript. That’s all there is to it, if you already know javascript and jquery, and you have all the requirements. Then you’re ready to start.

Procedure

First, do the housekeeping. I won’t tell you how to do it…
Just kidding! When I say housekeeping, it means including all the files which are needed on your page. And the bit of code which will let you perform actions using jquery.

$(function(){
       //form generation code goes here
});

Second, create the form which will be used by the user to generate another form element.

<form name="x" action="jquery_generatefields.php" method="post">
<input type="button" id="jq_gen_txt" value="generate text field"/><br/>
<input type="button" id="jq_gen_sel" value="generate select field"/>

<div id="gen_txt_fields"></div>
<div id="gen_sel_fields"></div>
<input type="submit"/>

If you have red my last tutorial on creating form elements using javascript. You might already know that the 2 buttons in the form will be the event launcher. And the 2 divs is where the generated field goes to.

You might also notice that I have action and method attributes for the form. That’s because I’m going to make a 2nd part for this tutorial in which we will actually save the inputted data in those dynamically generated fields into the database. Stay tuned for that.

Going back to javascript. Inside the document.ready() function. Create 2 new variables. This will serve as the index for the elements that the user is going to create later on. If you didn’t catch what I mean by that. I said that were going to use it for the id attribute for each dynamically generated form elements.

var num_txt = 0;
var num_sel = 0;

By the names of those variables, you might already predicted that what were going to generate are:

  • Text field
  • Select field

Next, create the function that will execute if the button for generating text fields has been clicked:

$('#jq_gen_txt').click(function(){
  //code for text field generation goes here
}

Inside the function. We create the element input. Then add attributes id, name, and placeholder to it. Id is optional, if you want to have a unique identifier for the form elements that are created then put the id attribute. Name attribute is mandatory for this tutorial. Since were going to use it later to access the value of that specific field for our database. Finally we append it to the div with the id attribute of gen_txt_fields.

var txt = $("<input>").attr({'id': 'tx' + num_txt,
 'name': 'tx[]',
 'placeholder':  num_txt}).appendTo('#gen_txt_fields');

Next we also create a button which can be used by the user to remove the text field that has been created.

var rem_btn = $("<input>").attr({'type' : 'button',
 'id' :  num_txt,
'value' : 'remove'}).appendTo('#gen_txt_fields');

The code is the same, the only difference are the attributes which are being applied. Type attribute is used to determine what type of input field will be generated, this is a mandatory attribute. Since without it, you can’t possibly know what type of input field will be generated because there are lots of input fields. Some of those are:

  • radio buttons
  • checkboxes
  • text fields
  • password fields

And with the advent of html5. Another set of fields has been added to the list:

  • email fields
  • telephone number fields
  • number fields

I think there are still more, but I can’t recall them. And I can’t even Google them since my internet connection has already been turned off at this moment.

Oops, don’t forget to include the code which will increment the variable num_txt everytime the user clicks on the button:

num_txt++;

Next create the function for creating select fields:

$('#jq_gen_sel').click(function(){
   //code for select field generation goes here
}

First, you have to create the select field.

var sel = $("<select>").attr({'id' : 'gender' + num_sel,
'name' : 'gender[]'}).appendTo('#gen_sel_fields');

Next, will be its options:

var male = $("<option>").attr({'id' : 'male' + num_sel ,
 'value' : 'Male'}).text('Male').appendTo(sel);

var female = $("<option>").attr({'id' : 'female' + num_sel,
 'value' : 'female'}).text('Female').appendTo(sel);

We both append those to the select field which is currently assigned to the variable sel. So its safe to make use of the variable name. But you can also make use of the id of the select field, that will also work.
Remember that the value is different from text:

  • value – actual value of the option
  • text – the value which is being shown in the option. (innerHTML as you might call it)

Then finally the incrementing code:

num_sel++;

Next, we write the code for the button which removes/deletes the generated text field (I’ll leave the removal of select field to you).

$('input[id^=rem_btn]').live('click', function(){
   //code for input field removal
}

The code is a bit different from usual. Since we didn’t use the click() event directly. We used the live() event instead. Its always been my practice to use this in cases wherein I need to access a dynamically generated form.

var clicked = $(this).attr('id');
var tx_id = 'tx' + clicked;
$("#" + tx_id).remove();
$(this).remove();

In the code above, we accessed the Id attribute of the button, and stored it in the tx_ad variable together with the prefix that we used in the text fields id which is the word ‘tx’. We then performed a simple remove() function to remove the text field with the same index as that of the button.

Conclusion

That’s it for this tutorial. You’ve learned how to generate form elements using jquery. Next time I’m going to show you how you can save the data inputted in those dynamically generated text fields into the database.

Hide or show multiple form elements using jquery and fieldsets

In this tutorial I’m going to show you how you can hide or show multiple form elements in one go. That is by grouping those form elements in an html fieldset.

 

Requirements

  • jquery core

 

Procedure

First, do the housekeeping.

<style>
#full{
    width:500px;
}
</style>
<script src="jq.js">
</script>

I’m really lazy today, so I didn’t include the style and the script type. This works, but its not really a good practice.

Next, create the form elements.

<input type="button" id="hide" value="hide/show"/>

<fieldset id="full">
<legend id="full_legend">Fieldset_hideshow</legend>
<p><input type="text" name="a" placeholder="a"/></p>
<p><input type="text" name="b" placeholder="b"/></p>
<p><input type="radio" name="c"/>
<input type="radio" name="c"/>
<input type="radio" name="c"/></p>
</fieldset>

We grouped the 2 text fields and the 2 radio buttons inside the fieldset. So that we won’t be accessing those elements one by one if we want to hide/show them.

Finally, we create the script which will hide/show the fieldset and all of the elements inside of it.

<script>
$(function(){

$('#hide').click(function(){
    $('#full').toggle('fast');
    });
});
</script>

In case you don’t know toggle is just a shortcut for .show() and .hide() functions. And here’s what it does: first it checks if the element is hidden or not. Might be something like this, if you hand code it:

if($(element).is(":visible")){
    //hide it
}else{
    //stay put
} 


Conclusion

I can’t really think of a good conclusion, because it seems like I’m only repeating what I’m saying every time I make a conclusion. And what’s worst is that what I’m saying doesn’t really fit the description of a conclusion. Don’t you agree? Anyway, again thanks for reading!

Tutorial files update

If you have been checking out the tutorial files in the link below. Then you would like this update. I made an account at wupload and mediafire where I will upload all of the files that I have used for my tutorials.

Files

Here are the public folder links:

I have already uploaded 5 zip files at the time of writing of this post. Which includes:

image

I’m too lazy to type so please bear with my screenshot.
In case you didn’t catch what I said a second ago. I won’t be updating the last post about the tutorial files anymore. Just go visit those 2 public folders for the updates, thanks!

Awesome sites for the tech savvy

In this article I’m going to share to you some of the sites where I get most of the information on anything that is under the  technology category. I’m an IT student at the time of writing so expect that most of the sources I’ll share to you are in one way or another connected to my field.

 

slideshare.net

Most of the people in the web design and development industry, programming industry and the tech industry in general. Upload some of their presentations in this site. Its really a good resource.

image

 

makeuseof.com

The logo speaks up for itself. In this site you will find computer tips, software reviews, cool tools and websites, and other awesome stuff.

image

 

lifehacker.com

This is where the tech news, computer tips, software reviews, cool applications are being integrated into one site.

image

 

howtogeek.com

One of the most awesome sites when it comes to tips on how to perform some geeky stuff on the computer and other gadgets.

image

 

neowin.net

One of the most reliable source of tech news from hacking (Lulzsec and Anonymous are really hot in the time of writing of this entry) to everything tech related.

image

 

youtube.com

Why did youtube made it to this list? That’s because of the awesome people who use it. In fact I have already made 2 articles to prove how awesome youtube is:

image

 

gizmodo.com

They mostly feature consumer electronics in this site. Gadgets and gizmos for short. Pretty much awesome if you are a techy spending a lot of time fiddling with your gadgets.

image

 

stumbleupon.com

If you are not in the mood to do anything productive but still want to learn something, then stumbleupon is for you. As it says in the the logo below, discover your web with Stumbleupon. It’s the ultimate tool for discovering awesome content scattered throughout the internet.

image

 

google reader

A service from Google wherein you get to read the content from a site without actually visiting the site. That is through RSS. Just visit google.com/reader so that you’ll know what the heck I am talking about.

image

 

twitter.com

This is my current addiction in the time of writing of this article. Twitter is simply awesome for those who wants to follow and get the latest news from a person, a website, a magazine, or anything, anyone under the sun who has a twitter account. But for me, I mainly use it for following tech/software companies like Microsoft, Google, Adobe. And some web design and development blogs like sixrevisions, smashingmagazine, line25, speckyboy and others which are also really awesome.

image

 

howstuffworks.com

Yet another awesome site. Just use the link above to go there so you’ll know what I mean. But here’s a quick link if you’re here for the tech.

image

 

Conclusion

That’s pretty much all I can share to you. If you are reading this and you know of other sites that might be considered as a part of this list, then you might as well share it in the comments below. I’d really appreciate it. Thanks for reading!