Codeigniter SQL table update with Ajax param not working - php

I hope someone can give me a hand because I've tried and tried to find the error with no luck, I'm trying to execute an update SQL statement which gets the values from a POST AJAX request and everything seems to work ok but the table's values doesn't get updated.
The App flow is like this (and it actually works, just without the data update):
In my view I have a button which detonates a modal window for the user to input values in 4 text fields, then the user can click on a button and it sends such values through a POST AjAX call, then the controller and the method takes care of the update, then the user is sent back to the same page where he/she originally clicked the button.
As additional information, paths are correct, the flow works correctly, the values are being sent correctly through the AJAX call to the controller but I'm lost from that point on... :S
Not sure what I'm doing wrong, any help is appreciated
// My View - HTML button //
<i class="fa fa-file fa-2x" aria-hidden="true" ></i>
// My View - HTML modal window code //
<div id="confirmation_box_service_report_additional_data" title="" style="display:none;">
<h1 align="center" style="color: #333333"><?php echo $this->lang->line('service_report_title') ?></h1><br />
<h2 align="center" style="color: #DF9E0A"><strong><?php echo $this->lang->line('project_service_comments') ?></strong></h2><br />
<form id="form_service_report_additional_data" name="form_service_report_additional_data" method="post" action="">
<table width="100%">
<tr>
<td width="45%" class="red_cell_background">
<div class="form-group">
<label for="client_images_comments"><?php echo $this->lang->line('client_images_comments') ?></label>
<textarea class="form-control" rows="5" id="client_images_comments"></textarea>
</div>
</td>
<td width="5%" class="purple_cell_background"> </td>
<td width="45%" class="purple_cell_background"><div class="form-group">
<label for="specialist_images_comments"><?php echo $this->lang->line('specialist_images_comments') ?></label>
<textarea name="specialist_images_comments" rows="5" class="form-control" id="specialist_images_comments"></textarea>
</div></td>
</tr>
<tr>
<td class="red_cell_background"><div class="form-group">
<label for="spare_parts_comments"><?php echo $this->lang->line('spare_parts_comments') ?></label>
<textarea name="spare_parts_comments" rows="5" class="form-control" id="spare_parts_comments"></textarea>
</div></td>
<td class="purple_cell_background"> </td>
<td class="purple_cell_background"><div class="form-group">
<label for="final_comments"><?php echo $this->lang->line('final_comments') ?></label>
<textarea name="final_comments" rows="5" class="form-control" id="final_comments"></textarea>
</div></td>
</tr>
</table>
</form>
</div>
// My Javascript modal window code //
function service_report_additional_data(jobId) {
$("#spare_parts_comments").val("<?php echo $jobDetails[0]['spare_parts_description']; ?>");
$("#confirmation_box_service_report_additional_data").dialog({
autoOpen: false,
resizable: false,
width: 900,
heightStyle: "content",
modal: true,
closeOnEscape: false,
open: function(event, ui) {
$(".ui-dialog-titlebar-close", ui.dialog | ui).hide();
},
buttons: [
{
text: "<?php echo $this->lang->line('save_and_close'); ?>",
class: "btn btn-warning",
click: function() {
var clientImagesComments = $('#client_images_comments').val();
var technicianImagesComments = $('#specialist_images_comments').val();
var sparePartsDescription = $('#spare_parts_comments').val();
var finalThoughts = $('#final_comments').val();
//alert(finalThoughts)
servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts);
},
},
{
text: "<?php echo $this->lang->line('Cancel'); ?>",
class: "btn btn-default",
click: function() {
$(this).dialog("close");
}
}
],
close: function() {
$(this).dialog("close");
}
});
$("#confirmation_box_service_report_additional_data").dialog('open');
}
//My AjAX call //
function servicereportadditionaldatasaving(jobId, clientImagesComments, technicianImagesComments, sparePartsDescription, finalThoughts) {
//alert(clientImagesComments)
$.ajax({
type: "POST",
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
data: {
'jobId': jobId,
'clientImagesComments': clientImagesComments,
'technicianImagesComments': technicianImagesComments,
'sparePartsDescription': sparePartsDescription,
'finalThoughts': finalThoughts
},
success: function (data){
//alert(data);
location.href = '<?php echo base_url() . DISPATCHERADMIN . '/myjob/details/' ?>' + jobId;
},
error: function (jqXHR, textStatus, errorThrown){
console.log('error:: ' + errorThrown);
}
});
}
// My Controller //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs extends CI_Controller {
public function __construct() {
// Construct the parent class
parent::__construct();
$this->lang->load('message', 'english'); // language file
$this->load->model('dispatcher/jobs_model');
}
public function servicereportadditionaldatasaving() {
$postData = $this->input->post();
$data = array(
'table_name' => 'jobs',
'job_id' => $postData['jobId'],
'client_images_comments' => $postData['clientImagesComments'],
'technician_images_comments' => $postData['technicianImagesComments'],
'spare_parts_description' => $postData['sparePartsDescription'],
'final_thoughts' => $postData['finalThoughts']
);
$this->jobs_model->update_job_service_report_additional_data($data);
}
}
?>
// My Model //
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Jobs_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function update_job_service_report_additional_data($data) {
extract($data);
$this->db->where("job_id", $job_id);
$success = $this->db->update($table_name, array('client_images_comments' => $client_images_comments,
'technician_images_comments' => $technician_images_comments,
'spare_parts_description' => $spare_parts_description,
'final_thoughts' => $final_thoughts
));
if($success) {
return $success;
} else {
return false;
}
}
}
?>

I found the answer myself, after many attempts of looking into the code here and there I found that the problem was at the Ajax call at the following line:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>",
it was expecting an ID to be passed as part of the original URL as follows:
url: "<?php echo base_url() . DISPATCHERADMIN . '/jobs/servicereportadditionaldatasaving/' ?>" + jobId,
To be honest I need to review my code more in detail but that was the issue, everything is working as expected.

Related

403 forbidden in Codeigniter Ajax request even with cookie transfer

I am submiting a form with Ajax, I am also sending the cookie, however I still get the 403 forbidden. These are the 2 ways I tried sending the cookie.
Directly setting csrf cookie name and value in Ajax.
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
Getting the CSRF cookie from the form field
<form id="reviewForm" method="POST">
<div class="control-group">
<div class="controls">
<input type="text" class="form-control"
placeholder="Title" id="title" required
data-validation-required-message="Please enter the review title"/>
<p class="help-block"></p>
</div>
</div>
<div class="control-group">
<div class="controls">
<textarea rows="10" cols="100" class="form-control"
placeholder="Message" id="message" required
data-validation-required-message="Please enter your message" minlength="5"
data-validation-minlength-message="Min 5 characters"
maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div> <!-- For success/fail messages -->
<br>
<div class="g-signin2 btn btn-default pull-right" data-onsuccess="onSignIn"></div>
<br/>
</form>
function onSignIn(googleUser) {
console.log('onto the function');
var profile = googleUser.getBasicProfile();
var google_name = profile.getName();
var google_image = profile.getImageUrl();
var google_email = profile.getEmail();
console.log('got the details');
console.log('submitting');
var title = $('#title').val();
var message = $('#message').val();
console.log(google_name);
var csrf_test_name = $("input[name=csrf_test_name]").val();
console.log(csrf_test_name);
console.log(title);
console.log(message);
$.ajax({
type: "POST",
url: 'http://localhost/hbp/review/submit',
data: {
title,
message,
'csrf_test_name ' : 'csrf_test_name ',
'google_name': google_name,
'google_email': google_email,
'google_image': google_image,
},
success: function () {
alert('fuck');
}
});
None of them seem to work, here's the controller if it helps.
public function review($google_name, $google_email, $google_image, $message, $title)
{
$this->load->library('session');
$csrf_token = $this->security->get_csrf_hash();
$data = array(
'csrf_token' => $csrf_token
);
if (!$google_name and $google_email and $google_image and $message and $title) {
$this->load->library('session');
redirect('/', $this->session->set_flashdata('review_form_error', 'Error! All yields are required!')
);
} else {
echo $google_name, $google_email, $google_image, $message, $title;
$this->review_model->set_review($google_name, $google_email, $google_image, $message, $title);
redirect(base_url(), $this->session->set_flashdata('review_success', 'Thank you for providing us with your helpful feedback'));
}
}
try ajax setup
$.ajaxSetup({
data: {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
});
How to troubleshoot CSRF token issues?
open developer console in browser
go to network tab
click on the request being made
go to Cookies tab - compare request and response cookies
You can also var_dump($_POST) on the server side.
Question-specific remarks:
'csrf_test_name ' : 'csrf_test_name ',
should this not be
'csrf_test_name ' : csrf_test_name,
Try with double quotes:
'<?php echo $this->security->get_csrf_token_name(); ?>' : "<?php echo $this->security->get_csrf_hash(); ?>",
EXTRA: how to pass CI variables to JavaScript in a clean way, avoiding PHP/JS clutter?
Create a view file and include it in the bottom of your template:
file name = views/public/ci_config.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
?>
<script type="text/javascript">
var CONFIG = {
'base_url': '<?php echo base_url(); ?>',
'csrf_expire': '<?php echo $this->config->item('csrf_expire'); ?>',
'csrf_token_name': "<?php echo $this->security->get_csrf_token_name(); ?>", // needs double quotes!
'csrf_hash': "<?php echo $this->security->get_csrf_hash(); ?>" // needs double quotes!
};
</script>
Load it in a parent template, for example the footer partial, with:
<?php $this->load->view('public/ci_config'); ?>
Easily access this data anywhere in JS files:
var csrf_token_name = CONFIG.csrf_token_name;
var csrf_hash = CONFIG.csrf_hash ;
Or like Aria said:
$.ajaxSetup({
data: {
CONFIG.csrf_token_name : CONFIG.csrf_hash
}
});
Now you don't have to put all your JS code in a PHP file.

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

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.

Error Uploading File with AJAX in codeigniter

I am making an admin panel in codeigniter. I have a table games. It has an image inside it. I want to upload that image using ajax. But for some reason, the image is not being uploaded and error occurs no file selected.
Controller
public function ajax_add() {
$this->_validate();
$config = [
'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
];
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$file = $this->upload->data();
$file_name = $file['file_name'];
if ($file_name == '') {
$data['error_string'][] = 'Please upload an image.';
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
} else {
$data['inputerror'][] = 'image';
$data['error_string'][] = $this->upload->display_errors();
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id'),
'image' => $file_name
);
$insert = $this->game->save($data);
echo json_encode(array("status" => TRUE));
}
public function ajax_update() {
$this->_validate();
$data = array(
'title' => $this->input->post('title'),
'iframe' => $this->input->post('iframe'),
'status' => $this->input->post('status'),
'category_id' => $this->input->post('category_id')
);
$this->game->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
HTML
<div class="container">
<h1 style="font-size:20pt">Games</h1>
<h3>Game Data</h3>
<br />
<button class="btn btn-success" onclick="add_game()"><i class="glyphicon glyphicon-plus"></i> Add Game</button>
<button class="btn btn-default" onclick="reload_table()"><i class="glyphicon glyphicon-refresh"></i> Reload</button>
<br />
<br />
<table id="table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th style="width:125px;">Action</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Title</th>
<th>Category</th>
<th>Status</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</div>
Javascript
<script type="text/javascript">
var save_method; //for save method string
var table;
$(document).ready(function () {
//datatables
table = $('#table').DataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('game/ajax_list') ?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [-1, -3], //last column
"orderable": false, //set not orderable
},
],
});
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function () {
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
});
function add_game()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#modal_form').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Game'); // Set Title to Bootstrap modal title
}
function edit_game(id)
{
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url: "<?php echo site_url('game/ajax_edit/') ?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data)
{
$('[name="id"]').val(data.id);
$('[name="title"]').val(data.title);
$('[name="iframe"]').val(data.iframe);
$('[name="status"]').val(data.status);
$('[name="category_id"]').val(data.category_id);
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Game'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
function reload_table()
{
table.ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled', true); //set button disable
var url;
if (save_method == 'add') {
url = "<?php echo site_url('game/ajax_add') ?>";
} else {
url = "<?php echo site_url('game/ajax_update') ?>";
}
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function (data)
{
if (data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
} else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="' + data.inputerror[i] + '"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="' + data.inputerror[i] + '"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled', false); //set button enable
}
});
}
function delete_game(id)
{
if (confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url: "<?php echo site_url('game/ajax_delete') ?>/" + id,
type: "POST",
dataType: "JSON",
success: function (data)
{
//if success reload ajax table
$('#modal_form').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
</script>
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Game Form</h3>
</div>
<div class="modal-body form">
<?php
$attributes = array(
'id' => 'form',
'class' => 'form-horizontal'
);
echo form_open_multipart('#', $attributes);
?>
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Title" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Iframe</label>
<div class="col-md-9">
<textarea name="iframe" placeholder="Iframe" class="form-control" type="text"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-9">
<select name="category_id" class="form-control">
<option value="">--Select Category--</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['id'] ?>"><?php echo $category['name'] ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<?php echo form_upload(['name' => 'image']); ?>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Status</label>
<div class="col-md-9">
<select name="status" class="form-control">
<option value="">--Select Status--</option>
<option value="0">Inactive</option>
<option value="1">Active</option>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal -->
Noticed several required condition you missed in code
First in your ajax_add method
if ($this->upload->do_upload()) this should contain image field name like
if ($this->upload->do_upload('image')){// as your file upload field name is "image"
}
Then for ajax upload your client side code some params are missing
contentType: false,
processData: false,
so your ajax method should (in save method) looks like
$.ajax({
url: url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
contentType: false,
processData: false
.....
processData this is important when file upload via ajax
In addition to the suggestions from Rejoanul, you may want to check that you are not uploading a file that is too large.
Apparently if the file you are attempting to upload is larger than the maxsize, the FILES variable will be empty.
https://stackoverflow.com/a/21633123/2153218
Try to change This line in your controller
$img = "img"; // input name="img"
$this->upload->do_upload($img);
Try this
$config = array( 'upload_path' => './assets/game_images/',
'allowed_types' => 'gif|png|jpg|jpeg'
'overwrite' => TRUE, );
get_instance()->load->library('upload', $this->config);
if($this->upload->do_upload('image')) {
echo "file upload success";
} else {
echo $this->upload->display_errors();
}

how to get value by jQuery+Codeigniter and show in input field?

I got some problem about receive value from server , and show the value in input .
Sometimes, if I want to show the value in page, I will use the POST method, then set the input'ID in controller and model, and use foreach() in page you want to show , therefore the work is done.
But, if I want to show the value in input'field, how I need to do for it ?
I write some code for this and try to use AJAX receive and show in input, it's not working,can everybody help me to solve this problem , please....... Σ(  ̄□ ̄;)
I try to create a new model and a new page for it, there is a very simple form, the code is below:
view:kungfu.php
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
NUM:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="float:left;">
<span id="loading" style="display:none">Loading!!</span><br>
<span id="complete" style="display:none">Complete!!</span>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="query" name="query" class="btn" type="button" value="QUERY">
</div>
</form>
</div>
model:pr_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_query()
{
$query=$this->db->get("kungfu_table");
return $query->result();
}
}
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_query()
{
$this->load->model("pr_model");
$data = array(
"kungfu" =>$this->pr_model->pr_query()
);
echo json_encode($data);
}
}
if I want to show the value in normal page , I will use foreach() but I don't know how to show in input, I try to use getjson() , but no working . can somebody teach me ?
// 2013/11/30 re-edit
dear Suleman:
I try to write some code about .ajax() , but I still got problem , the other section was the same , but the controller had be change :
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
$max=json_encode($data);
echo $max;
}
}
model:pr_model.php
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery->result();
}
and I try to edit a js file for .ajax(),but the Chrome console tell me "Uncaught ReferenceError: maxnum is not defined " , can you tell me how to edit it ?
$("#newone").click(function(){
$("#num").val(function(){
max_response = $.ajax({
type:"POST",
url:"<?php echo base_url()?>/static_data/kungfu_maxquery",
cache:false,
data: "num:"+maxnum
});
max_response.done(function(){
return maxnum;
});
});
});
Make sure your model data is available in view, If available then need to alter your inpup fields:
NUM:<input id="num" value="<?php echo $data_for_first_input_filed; ?>" name="num" type="text" class="field_set"><br>
NAME:<input id="name" value="<?php echo $data_for_second_input_filed; ?>" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" value="<?php echo $data_for_third_input_filed; ?>" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" value="<?php echo $data_for_forth_input_filed; ?>" name="kungfu" type="text" class="field_set"><br>
If you want to append data through AJAX, then here is sample code:
$("#newone").click(function(){
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
data: {
'num':maxnum
},
cache: false,
success: function(data) {
console.log(data);
$("#num").val(data['filed_name_returned']);
$("#name").val(data['filed_name_returned']);
$("#local").val(data['filed_name_returned']);
$("#kungfu").val(data['filed_name_returned']);
}
});
});
AJAX request is not a cheap call, we can get all the data in one request and can set that available data in success function. I do't know your table structure that' why I have appended one line extra console.log(data); that will show your returned data in console.

Codeigniter - Call another controller from a view using ajax

Initially I am trying to load two views from one controller.
On submission I am passing one view to one controller and another view to another controller using ajax dynamically. Here is the skeleton of the controller
function edit(){
if (!$this->login_model->is_logged_in())
{
redirect('auth/login', 'refresh');
}
$this->load->library('form_validation');
$this->data['custom_error'] = '';
//------------- Getting Student data----------------
if ($this->form_validation->run('students') == false)
{
$this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);
} else
{
$data = array(
'username' => $this->input->post('username'),
'city' => $this->input->post('city')
);
if ($this->student_model->edit('students',$data,'id',$this->input->post('id')) == TRUE)
{
redirect(base_url().'index.php/students/manage/');
}
else
{
$this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';
}
}
$this->data['result'] = $this->codegen_model->get('students','id,username,city,created_on,date_created','id = '.$this->uri->segment(3),NULL,NULL,true);
$this->data['message'] = $this->db->get('messages')->result();
//---------------------- Posting student data for Edit--------------
$this->load->view('pheader');
$this->load->view('/students/students_edit', $this->data);
//-------- loading comment controller for comment box --------------
$msg_data['result'] = $this->db->get('messages')->result();
$this->load->view('commentView', $msg_data);
}
So the problem is when I m submitting the messages_view both the controllers are loaded , but I need to load only one controller
Here is my student_edit view where I edit my details
<?php
echo form_open(current_url()); ?>
<?php echo $custom_error; ?>
<?php echo form_hidden('id',$result->id) ?>
<p><label for="username">Username<span class="required">*</span></label>
<input id="username" type="text" name="username" value="<?php echo $result->username ?>" />
<?php echo form_error('username','<div>','</div>'); ?>
</p>
<p><label for="city">City<span class="required">*</span></label>
<input id="city" type="text" name="city" value="<?php echo $result->city ?>" />
<?php echo form_error('city','<div>','</div>'); ?>
</p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
Here is the commentView that I am loading separately from the controller
<div id="content-table-inner">
<table border="0" width="100%" cellpadding="0" cellspacing="0">
<?php foreach ($result as $comment): ?>
<tr valign="top">
<p>Posted By : <?=$comment->created_by?></p>
<p>Posted On : <?=$comment->created->on?></p>
<p>Message : <?=$comment->message?></p>
</tr>
<br/>
<?php endforeach; ?>
</table>
<div class="submitComment" id="insertbeforMe">
<h3>Add a message</h3>
<form id="form" method="POST" action="">
<p>
<textarea name="message"></textarea>
</p>
<input type="hidden" value="<?=base_url()?>" id="baseurl"/>
<button name="submit comment">Submit Comment</button>
</form>
</div>
<script type="text/javascript">
function comment(){
var baseurl = $('#baseurl').val();
$('.submitComment').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
success : function(comment){
$(comment).hide().insertBefore('#insertbeforMe').slideDown('slow');
}
})
return false;
})
}
</script>
</div>
Can anyone tell me whats the problem ?
If I understand correctly...
The event you should be capturing is the form's "submit", not the submit-button's "click". You're essentially running the AJAX request and submitting the form.
Try something like this instead:
$('form').on('submit', function(e) {
e.preventDefault(); // this prevents the form from submitting
// do AJAX stuff
});
Unless I am mistaken you are attaching the event to a click event on the '.submitComment' div.
Should you not give the button an id and attach the .click event to it ?
Then you need to define the view you want to call via ajax to return some json which your function can use:
The Javascript:
$('#button').click(function(){
$.ajax({
url : baseurl + 'index.php/comment/insert',
data : $('form').serialize(),
type: "POST",
dataType: "json",
success : function(comment){
$('table').append('<tr><p>'+comment.createdby+'</p><p>'+comment.createdon+'</p><p>'+comment.message+'</p></tr>');
}
})
return false;
})
The Controller method (comment/insert):
function insert() {
$comment = $this->input->post('message');
$result = $this->commentModel->insert($comment);
if($result["OK"]) {
$data['json'] = json_encode(array('createdon' => $result["createdon"], 'createdby' => $result["createdby"], 'message' => $result["message"]));
$this->load->view('json_comment_view', $data);
}
//ELSE deal with errors (flashdata etc...)
}
The View (loaded via ajax):
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo $json;
?>
I haven't tested this code - or used codeigniter extensively in about a year, but the concepts covered should put you on the right track for what you want to achieve. Let me know!

Categories