how to get last inserted id after inserting using codeigniter and jquery - php

Please help me on how to get the last inserted id from database using codeigniter and jquery. What I want is to get the the last inserted id after inserting. I am using jquery to insert the data. I don't have any idea on how to it. Thanks a lot in advance.
SCRIPT
$('#add-tag').click(function () {
var lang = $('#lang').val();
var tag = $('#tag').val();
var data = {
tag: tag,
lang: lang
}
if (tag === '') {
$('.error').html('<h4><i class="glyphicon glyphicon-info-sign">' +
'</i> Field cannot be empty!</h4>').addClass('bounceIn').show();
$('.error').delay(3000).fadeOut();
} else {
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
success: function (result) {
//display message if successful
$('.message').html('<h4><i class="glyphicon glyphicon-ok">' +
'</i> Tag has been added</h4>').addClass('bounceIn').show();
$('.message').delay(3000).fadeOut();
$('#tag').val('');
$('#tags').append('<a class="tags animated fadeInDown">' +
'<span class="remove-tag" id="remove-tag' + lid + '">' +
'</span></span> ' + tag + '</a>');
window.setTimeout(function () {
location.reload();
}, 2000);
}
});
}
});
VIEW
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div id="add-tag-form" class="display-none relative">
<div class="well well-sm">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<h5>Add Tag</h5>
<input type="text" id="tagLastID" class="form-control" placeholder="Tag Last ID" readonly>
<input type="hidden" id="lang" class="form-control" placeholder="Lang" required value="<?= $lang; ?>">
<input type="text" id="tag" class="form-control" placeholder="Tag" required>
<br />
<button id="add-tag" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
<div class="text-center"><a id="close-tag">cancel</a></div>
</div>
</div>
</div>
</div>
<button id="add-tag-btn" class="btn col-md-12 col-sm-12 col-xs-12">Add Tag</button>
</div>
</div>
CONTROLLER
public function add_tag() {
$this->Mblog->addTag();
}
MODEL
public function addTag() {
$lang = $this->input->post('lang');
$tag = $this->input->post('tag');
$data = array(
'tags' => $tag,
'lang' => $lang
);
$this->blog->insert('tags', $data);
return $this->blog->insert_id();
}

Add return to your controller function or echo the result like as follows:
public function add_tag() {
return $this->Mblog->addTag();
}
OR
public function add_tag() {
echo json_encode(['data' => $this->Mblog->addTag()]);
exit;
}
And then try to modify dump and see the ajax success response:
$.ajax({
url: "<?= site_url('blog/add_tag'); ?>",
type: 'POST',
data: data,
dataType: 'json', // this will convert your results to json by default
success: function (result) {
// You should get the json result
console.log(result.data);
// Your regular logic to handle result
},
fail: function(res) {
console.log(res); // will log fail results
}
});
Try these and let us know if this works for you or not.

If you are asking that how to return data from controller to jQuery then yes, this is the answer.
Replace your controller code with this
public function add_tag() {
$insert_id = $this->Mblog->addTag();
echo(json_encode(array("insert_id"=>$insert_id)));
}
The echo'ed result will be appear in your success of jQuery.ajax.

You're already returning the id from the Model, so in your controller the only thing you have to do is echo-ing the result.
public function add_tag() {
echo $this->Mblog->addTag();
}
Then in you jquery the result will be what you have echoed from the controller.

Related

Getting a null value in my input file type field

I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});

ajax submit form with file

I have form, with ajax, that contain textarea and upload file field
I can submit only one of them.
how can I fix that?
I want to send "info" + "filesData" to the server.
Please advise.
Thank you in advanced
AJAX :
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
alert(files_data);
var act = 'add';
var $form = $("#addCommentForm");
var info = $form.serialize();
info += '&act=' + act ;
alert(info);
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: files_data,
success: function(data)
{
// alert(data); // show response from the php script.
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false;
});
});
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-8 col-xs-12">
<textarea class="form-control" name="post[text]"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-xs-12">
<input type="file" class="form-control" name="file" id="files">
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<a class="btn btn-primary" id="submit">submit</a>
</div>
</div>
</form>
PHP
print_r ($_FILES);
print_r ($_POST);
In $.ajax call, subtitute the value of data parameter (filesData) by:
{ field1 : field1value, field2 : field2value, .... }
use as many field/value pairs as you need
you also can get the values directly like this:
{ field1 : $('#commentsBox').text(), field2 : $('#yourinput').val(), .... }

Codeigniter save ajax response

I want to save the ajax response I get into my database. The problem is that my ajax function doesn't allow my to put a insert query. When I Insert the insert query, my response doesn't work anymore and vice versa.
where ajax file is
public function submit() {
$data = array(
'user_id' => '1',
'swipedpicture' => $this->input->post()
);
$this->db->insert('tbl_results', $data);
print json_encode($data);
}
Ajax Jquery
var pic = $(this).find('input[name="inputcountry"]').attr('value');
jQuery.ajax({
type: "POST",
url: window.location.origin +"/swipr/index.php/preferences/submit",
dataType: 'json',
data: {swipedpic: pic},
success: function(res) {
if (res) {
console.log(res.swipedpicture);
}
}
});
Your javascript is setting a data element for posting that the submit function is not using.
The submit function should look like this.
$data = array(
'user_id' => '1',
'swipedpicture' => $this->security->xss_clean($this->input->post('swipedpicture'))
);
$this->db->insert('tbl_results', $data);
$response_array['status'] = 'success';
echo json_encode($response_array);
The javascript should look more like this. I used an form id of form1 and a form element of swipedpicture.
$('#form1').submit(function(e){
e.preventDefault();
$.ajax({
url: 'example_answer_submit',
type: 'POST',
data: $('#form1').serialize(),
success: function (msg) {
if (!msg) {
console.log('error');
} else {
console.log('success');
}
}
});
return false;
});
The form I used.
<h1 class="page-header text-center">Test Form</h1>
<form id="form1" class="form-horizontal" role="form" method="post" action="">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Swiped Picture</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="swipedpicture" name="swipedpicture" placeholder="Pic" value="">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<?php echo $result; ?>
</div>
</div>
</form>

Cancel submit jquery

This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/

Receiving and Processing a multi dimensional array

I have asked this question twice, with no satisfactory answer, that is, the problem I faced two questions ago still remains and none the wiser as how I am going to proceed with this.
This time I will provide all the code and what I receive, plus where the problem is occurring, I know what the issue is but since I'm relatively new to using AJAX it has me puzzled.
I have a form, which when you click the second to last field, duplicates itself, with the help of another user all the id's get changed to be unique.
<form role="form" class="batchinvoice form-horizontal" id="batchinvoice">
<div class="row">
<div class="form-group col-md-2">
<select class="form-control" name="sl_propid" >
<?php foreach($property as $row) :?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row[ 'property_name'] . " " . $row[ 'property_address1']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_date" placeholder="Date" class="sl_date form-control" id="datepicker">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_ref" placeholder="Invoice Reference" class="form-control" id="sl_ref">
</div>
<div class="form-group col-md-2">
<select class="form-control" name="sl_nom_id" id="sl_nom_id">
<?php foreach($subitem_nominals as $row) :?>
<option value="<?php echo $row['subnom_id']; ?>">
<?php echo $row[ 'nom_subitem_name']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_desc" id="sl_desc" placeholder="Invoice Description" class="form-control">
</div>
<div class="form-group col-md-2">
<input type="text" name="sl_vat" placeholder="VAT Amount" class="vat form-control" id="vat">
</div>
<div class="form-group col-md-1">
<input type="text" name="sl_net" placeholder="Net" class="form-control" id="sl_net">
</div>
</form>
The JS for the form clone
<script>
var clone_iterator = 0;
$(function () {
var i = 0;
$.datepicker.setDefaults($.datepicker.regional['']);
$.datepicker.formatDate("yy-mm-dd");
$('#datepicker').datepicker();
$('#batchinvoice .vat').click(function () {
// alert("ok");
var id = "batchinvoice" + clone_iterator;
$('#batchinvoice').clone(true).attr("name", id).attr('id', id).appendTo(".panel-body"); // here I added this .attr('id',id)
// here we'll change the id's of all the elements who actualy have an attribute
$('#' + id + ' *[id]').each(function () {
$(this).attr('id', $(this).attr('id') + clone_iterator); //we set the attribute id
});
clone_iterator++;
});
$('#submit').click(function () {
var res = {};
console.log(res);
$('.batchinvoice').each(function (i) { //the class is a good use to do things like that you can repeat it more than once !
res[i] = new Array();
console.log(res);
res[i].propid = $(this).find('*[name=sl_propid]').val();
res[i].date = $(this).find('.sl_date formcontrol').val();
res[i].ref = $(this).find('*[name=sl_ref]').val();
res[i].id = $(this).find('*[name=sl_nom_id]').val();
res[i].desc = $(this).find('*[name=sl_desc]').val();
res[i].vat = $(this).find('*[name=sl_vat]').val();
res[i].net = $(this).find('*[name=sl_net]').val();
console.log(res);
alert(res[i].propid);
// i++;
//$.each('',function( index, value ){}
//(int)i is already incremented if you use class and not IDS
});
console.log(res);
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: res,
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});
});
});
</script>
This is the particular controller function in CodeIgniter, Note I have tried multiple things.
function addInvoiceToLedger(){
// $this->load->model('SalesLedgerModel');
// $propid = $this->input->post('propid');
// print_r($this->input->post());
// $date = $this->input->post('date');
// $ref = $this->input->post('ref');
// $nomid = $this->input->post('id');
// $desc = $this->input->post('desc');
// $vat = $this->input->post('vat');
// $net = $this->input->post('net');
$res = $this->input->post(NULL, TRUE);
//problem is probably here, it's
//for($x = 0; $x < count($res); $x++){
foreach($res as $row){
$this->SalesLedgerModel->addInvoiceToLedger($row.propid, $row.date, $row.ref, $row.nomid, $row.desc, $row.vat, $row.net);
}
//}
//redirect('home/financial_input/');
}
the Model Function
function addInvoiceToLedger($propid, $date, $ref, $nomid, $desc, $vat, $net){
$data = array('sl_prop_id' => $propid, 'sl_date' => $date,
'sl_ref' => $ref, 'sl_nominal_sub' => $nomid, 'sl_invoice_desc' => $desc, 'sl_vat' => $vat, 'sl_amount' => $net);
$this->db->insert_batch('salesledger', $data);
}
Which all have the relevant field data for each form inside them.
My question is how do I receive and handle the array? Every loop I've tried doesn't work, I've tried getting variables singularly(as you can see above commented out) but that doesn't make sense (or work) because in the $.ajax data it is set to res, but $this->input->post('res') doesn't return anything nor does $this->input->post(NULL, TRUE)
Majorly stuck, I feel this should be a simple thing, but I clearly don't understand it.
Edit, still same problem can't find an answer anywhere D:, tried many things.
Still the same problem "res" is sent as post, but I can't retrieve it in the controller with $this->input->post()...anyone?
I only wanted to submit a comment but apparently I need 50 rep for that so I'll take my chances with an answer.
In your $.ajax block what if you change the data section to this:
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>FinancialInput/addInvoiceToLedger',
data: { res : res },
sucess: function (e) {
alert(e);
},
error: function (e) {
alert(e.toString());
}
});

Categories