Update db using codeigniter/modal window

Hello, can someone help me to be able to update a row in the db using codeigniter/jquery. I have been able to add and view my data but not sure how to proceed with the update/edit part. I have the following on my td tag and am able to pass this value to the controller but not sure how to proceed after this to pull the up the record as a popup window and edit it;

<td><a href="companyEdit/<?php echo $post->vendor_id; ?>" ><span class="glyphicon glyphicon-pencil"></span></a></td>

Thanks for the help.

A
aej1973Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Marco GasiFreelancerCommented:
Without seeing any code is a bit difficult guess what you have to do, but the general pattern is the following:
I argue that companyEdit is a method of your controller and <?php echo $post->vendor_id; ?> is the parameter, in this method you have to get the parameter and pasing it toa model method which has to use it to update the database returning ideally true or false. The returning value will be used to present a view with success or error.

public function($vendor_id)
{
    $data['result'] = $this->modelname->updateVendor($vendor_id);
    $this->load->view('header');
    $this->load->view('db_result', $data);
    $this->load->view('footer');
}

Open in new window


In your model you have to put a method to update the database using ActiveRecord or plain mysql ActiveRecord.

Hope this is clear enough. If you need help with the model method, I'll help you later, because now I have to run away :-)
0
aej1973Author Commented:
Hello Marco, thank you for getting back to me. Can you please let me know how I can set up the modal window.
Thank you very much.

A
0
Marco GasiFreelancerCommented:
Ok. Can you explain me the application flow? When the modal window has to appear? What is the modal window content? What happens when the user click Ok or Cancel button? And, last but not least, have you some code to start with? :-)
Cheers
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

aej1973Author Commented:
Hello Marco, my workflow is as follows:

1. I have a db that I update via  form with the following values;
vendor name/address/contact/status.

2. I am able to display the data from this db on my web page.

3.Ihave a link on every row that had a edit button enabled and it has the row Id passed to this link (<td><a href="companyEdit/<?php echo $post->vendor_id; ?>" ><span class="glyphicon glyphicon-pencil"></span></a></td>).

4.When I click on this link I need to have a popup/modal window that displays the records for that row which I need to be able to edit and update the db. I am not sure how to do this.

Thank you for your help and please let me know if there is any other information you need.

A
0
aej1973Author Commented:
Sorry, I did not let you know. I am using active records.  Attached is my controller file and my modal.

Thanks,
A
insertdata.php
modelviewdata.php
0
Marco GasiFreelancerCommented:
Well, is a bit tricky, so be patient :-) I can't give you a ready-to-use code, because I don't know the exact structure of your code and of your controllers, models and views, but I think you'll be able to change my sample code to make it work in the real world.
To make something like you want to do I used a jQuery plugin, fancybox.
This is the logic. When your user clicks on the link to edit the record a javascript code is executed which open the fancybox modal window. The call to fancybox is built calling a specific view which will give to the fancybox window its contents. Finally, when the user clicks the Ok button to post updates a seconf javascript function is called which does an ajax call to a controller method which calls a model method to update the database. Ready?

This is what you must add in the footer of your page (notice the last three lines: they makes base_url value available for all javascript functions so you can use Ajax within CI):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="<?php echo js_url('jquery.fancybox.js') ?>"></script> 
<script type="text/javascript">
	var baseurl = "<?php print base_url(); ?>";
</script>

Open in new window


This in your header:
<link href="<?php echo css_url( 'jquery.fancybox.css' ) ?>" rel="stylesheet">

Open in new window


js_url and css_url are shortcut to the assets subfolders: you can create an assets_helper.php file when you put something like this:
/**
 * Helper css_url()
 *
 * @access public
 * @param string
 * @return string
 */
if ( ! function_exists('css_url'))
{
 function css_url($uri)
 {
  $_ci = get_instance();
  return $_ci->config->base_url('assets/css/'.$uri);
 }
}  

// ------------------------------------------------------------------------

/**
 * Helper js_url()
 *
 * @access public
 * @param string
 * @return string
 */
if ( ! function_exists('js_url'))
{
 function js_url($uri)
 {
  $_ci = get_instance();
  return $_ci->config->base_url('assets/js/'.$uri);
 }
}  

Open in new window

and then load the helper within your controller construct method in the usual way.

Your link to edit db (notice the added class 'updateDB'):
 <td><a class="updateDB <?php echo $post->vendor_id; ?>" href="#" ><span class="glyphicon glyphicon-pencil"></span></a></td>

Open in new window


All javascript function can reside in just one file (the mine is called app.js):
 $( document ).ready( function ()
{
    //your functions here
});

Open in new window


The first javascript function to open the modal window:
	$( document ).on( 'click', '.updateDB', function ( e ) {
		e.preventDefault();
                var classes = $(this).attr('class');
                var classes_array = classes.split(' ');
                var vendorId = classes_array[classes_array.length -1]; //here is the vendor_id
		$.fancybox( {
			type: "ajax",
			scrolling: "no",
			href: baseurl + "update_db_form/" + vendorId,
			fitToView: false,
			autoSize: true,
			closeClick: false
		} );
	} );

Open in new window


update_db_form is just a methid within your controller and this method i quite simple:
public function update_db_form(vendor_id)
{
    $data['vendor_id'] = vendor_id;
    $this->load->view( 'update_db_form_view', $data );   
}

Open in new window


This method create the modal window content.
update_db_form_view:
<form>
	<div>
		<label for="vendor_id">Vendor id</label>
			<input id="vendor_id" type="text" value=$vendor_id />
		<button id="post_vendor_id" > Ok </button>
		<button class="btn closeFancybox"> Cancel </button>
	</div>
</form>

Open in new window


And now the second call to a javascript function:
	$( document ).on( 'click', '#post_vendor_id', function ( e ) {
		e.preventDefault();
		var vendorId = $( '#vendor_id' ).val();
		if ( vendorId === '' )
		{
			jQuery.fancybox.close();
			return;
		}
		else
		{
			jQuery.fancybox.close();
			var url = baseurl + 'post_vendor_id/' + vendorId;
			$.ajax( {
				type: 'post',
				cache: false,
				url: url,
				success: function (  )
				{
					//here you could display a short message or just do nothing ;-)
				},
				error: function ( jqXHR, textStatus, errorThrown )
				{
					console.log( jqXHR + " textStatus: " + textStatus + ", errorThrown: " + errorThrown );
				}
			} );
		}
	} );

Open in new window


the controller method post_vendor_id() which accept as parameter the value to update the database will call a model method which will actually perform the update.

Is this clear enough? Does this make sense for you? I hope, I really hope... ;-)
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
aej1973Author Commented:
Marco, thank you very much for your time. I will go through this and will get back to. Really appreciate your help.

A
0
aej1973Author Commented:
Hello Marco, I have made a quite a bit of progress but need some help with the last part.

1. I was able to capture the db values with reference to the id
2. In the pop up when I click the update button the alert message captures the correct controller path but my db is not getting updated. Can you let me know why? I have attached the model and the controller for your reference.

Also, can you let me know how I can build in some validation into my pop up form. Thanks again for all your help.


A
url-image.png
update-db-form.php
modelviewdata.php
form-edit.php
0
Marco GasiFreelancerCommented:
Hi A.
The javascript is missing. You have to follow my example and use javascript to post data to the controller method which actually post the data. Perhaps your code doesn't update the db because something went wrong with the javascript.
About the validation, you have to do iot too within the javascript function which post the data, before posting them.
And then put some validation code in the server side also, within the controller method which receive the data from javascript.
0
aej1973Author Commented:
Hi Marco, I do have the jquery in place, attached is the script.

//########update script for the controller##############
    //@ updatedb class is on the edit link on the from
    //@ the updatedb class also has the vendorid that we are caputuring using the split command.
	$( document ).on( 'click', '.updateDB', function ( e ) {
		e.preventDefault();
		        var baseurl = 'http://localhost:8888/forms/index.php/update_db_form/';
                var classes = $(this).attr('class');
                var classes_array = classes.split(' ');
                var vendorId = classes_array[classes_array.length -1]; //here is the vendor_id
		$.fancybox( {
			type: "ajax",
			scrolling: "no",			
			href: baseurl + "editInfo/" + vendorId, 
			fitToView: false,
			autoSize: true,
			closeClick: false
		} );
	} );
	//###### End Script....
    
    //#########update script for the pop up ##################
    $( document ).on( 'click', '#post_vendor_id', function ( e ) {
		e.preventDefault();
		var baseurl = 'http://localhost:8888/forms/index.php/update_db_form/';
		var vendorId = $( '#vendor_id' ).val();
		if ( vendorId === '' )
		{
			jQuery.fancybox.close();
			return;
		}
		else
		{
			jQuery.fancybox.close();
			var url = baseurl + 'updateCompanyInfo/' + vendorId;
			$.ajax( {
				type: 'post',
				cache: false,
				url: url,
				success: function (  )
				{
					alert(url);
					//here you could display a short message or just do nothing ;-)
				},
				error: function ( jqXHR, textStatus, errorThrown )
				{
					console.log( jqXHR + " textStatus: " + textStatus + ", errorThrown: " + errorThrown );
				}
			} );
		}
	} );
                                      
    //########End Script........

Open in new window

0
Marco GasiFreelancerCommented:
The problem is that in my script I just grabbed 'vendorId' value as example. But you have a lot of field to update so we can do two things: grab all them in our javascript, build an array and pass the array to the controller method; or try to keep things simple using normal submit tecnique. I'd prefer this second option, so you can build your form traditionally givint it method='post' and action='<?php echo base_url('updateCompanyInfo') ?>'.

Delete the parameter 'vendor_id' from the updateCompanyInfo() method and get id and other values from the $_POST array and go on with your model. This should work and avoids to create a too complex javascript function.
0
aej1973Author Commented:
Marco, thank you so very much, you have been such a great help.

Thanks,
A
0
aej1973Author Commented:
Thank you.
0
Marco GasiFreelancerCommented:
Glad to help you and good luck with your project.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
AJAX

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.