Search

Jquery Append/Prepend Elements to DOM

Done with the php framework code igniter

 

Jquery Prepend Elements to DOM

I decided to write this article because a few months back I didn’t know how to do this and I finally have some free time so I’m going to quickly explain it in a video tutorial and for those who don’t have speakers or don’t understand English i’m posting it below in text.

Video Tutorial (more of an explanation)

Jquery Ajax Append Data Explained from joel beasley on Vimeo.

Video Example of Result


Jquery Append/Prepend Elements to DOM from joel beasley on Vimeo.


Step 1- First we need to make sure we load the latest form of JQuery.

Step 2 – We need to make our form. I’m going to shorten the paste to save room by only adding 4 fields.

<div id="newClient">
	<form id="clientsAdd" method="post" action="">
		<div class="formRow">
			<label>Company</label>
			<input type="text" name="company" class="company" value="" size="50" />
		</div>
		<div class="formRow">
			<label>First Name</label>
			<input type="text" name="firstname" class="firstname" value="" size="50" />
		</div>
		<div class="formRow">
			<label>Last Name</label>
			<input type="text" name="lastname" class="lastname" value="" size="50" />
		</div>
		<div class="formRow">
			<label>Email</label>
			<input type="text" name="email" class="email" value="" size="50" />
		</div>
			<input id="submit" type="submit" value="Add Client" />
		<div class="clearall"></div>

	</form>
</div>
<?=anchor('','New Client',array('class' => 'newClient'))?>

Now that we have a form in our view and our name fields match our db fields we can move on to our controller.

Note: It’s important that our field names match our database fieldnames since we are going to send all the post data directly to the database.

Step 3 – Open your controller file and create a function called addClient.

	function addclient()
	{
		if(empty($_POST)) { return false; }
		if($this->db->insert('clients', $_POST)) {
			echo mysql_insert_id();
		} else {
			return false;
		}
	}

I’ll go over this line by line

if(empty($_POST)) { return false; }

This will detect if there is any post data coming to the controller and if there is no post data the controller will not return anything.

if($this->db->insert('clients', $_POST)) {

This if there is post data then the controller will execute this code and insert or form into the database table clients. Code Igniter will automatically match the fields of the table clients with the field names from the from “name” field.

	echo mysql_insert_id();

This will echo back the mysql insert id of the row of data that was inserted. We need this information to pass back through the javascript we will write so we can use it in the view when the data is appended or prepended to the DOM.

Step 4 – Now that we have our view/form and we can process the data that will come through the controller we need to pass the data from the form to the controller with javascript. So, open up your javascript init file and we will add the following.

$(document).ready(function() {
	$('form#clientsAdd input#submit').click(function() {

// Send the form to the controller
		$.ajax({
                       url: 'clients/addclient',
                       type: 'post',
	        	data: $('form#clientsAdd').serialize(),
                        dataType: 'html',
			success: function(id) {
				$('ul#aclient').prepend('<li id="' + id + '"><ul class="clients"><li class="cCol cCompany">' + company + '</li><li class="cCol cFirstname">' + firstname + '</li><li class="cCol cLastname">' + lastname + '</li><li class="cCol cEmail"> ' + email + '</li>');
				$('li#'+id).hide();
				$('li#'+id).slideDown('slow');
				$('li#'+id).animate({
						backgroundColor: "joelgreen"
				      }, 1000 );
					$('li#'+id).animate({
							backgroundColor: "white"
					      }, 1000 );

		// Clear the form fields
                                $('input.company').val('');
				$('input.firstname').val('');
                                $('input.lastname').val('');
                                $('input.email').val('');
			}
		});
		return false;
	});
});

Step 5 – Create the view for seeing the data, i have it in the same view as the form so it’s all on the same page.

<h3 class="clients">Existing Clients</h3>
<ul class="clientsHeading">
	<li class="cCol cCompany">Company</li>
	<li class="cCol cFirstname">First Name</li>
	<li class="cCol cLastname">Last Name</li>
	<li class="cCol cPhone">Phone</li>
	<li class="cCol cFax">Fax</li>
	<li class="cCol cEmail">Email</li>
	<div class="clearall"></div>
</ul>
<ul id="aclient">
<?php foreach($query_clients->result() as $row) :? >
<li id="<?=$row->id?>">
<ul class="clients">
	<li class="cCol cCompany"><?=$row->company?></li>
	<li class="cCol cFirstname"><?=$row->firstname?></li>
	<li class="cCol cLastname"><?=$row->lastname?></li>
	<li class="cCol cPhone"><?=$row->phone?></li>
	<li class="cCol cFax"><?=$row->fax?></li>
	<li class="cCol cEmail"></li>
	<div class="clearall"></div>
</ul>
</li>
<?php endforeach; ?>
</ul></code>

Step 6 - Create the controller to retireve the current client info

<code>	function index($name=NULL)
	{	

		$userid = userid();
		$this->db->select('*');
		$this->db->from('clients');
		$this->db->where('user', $userid);
		$data['query_clients'] = $this->db->get();

		// Initialize
		$this->layout->set('nav', 'clients');
		$this->layout->load('layout','clients/clients_view',$data);
	}

Database Dump

CREATE TABLE `clients` (
  `id` int(11) NOT NULL auto_increment,
  `company` varchar(128) NOT NULL,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(64) NOT NULL,
  `email` varchar(128) NOT NULL,
  `phone` varchar(16) NOT NULL,
  `fax` varchar(16) NOT NULL,
  `address` varchar(128) default NULL,
  `city` varchar(128) default NULL,
  `st` varchar(2) default NULL,
  `zip` varchar(5) default NULL,
  `user` int(11) NOT NULL,
  `date` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ;

--
-- Dumping data for table `clients`
--

INSERT INTO `clients` VALUES(24, 'o5Media', 'Joel', 'Beasley', '', '', '', '', '', '', '', 7, '2009-08-31 18:32:21');

I’m sure i did a number of things wrong so please feel free to comment and correct me.

Leave a Reply

Testimonials

o5Media did an outstanding job identifying our needs and exceeding them. They do it all with utmost professionalism.