I am trying to load a view through ajax passing in a post variable through controller following is my ajax call:
$('#image_id').on('click',function(){
var image_id = $('#image_id').val();
alert(image_id);
if(image_id != '')
{
alert('called');
$.ajax({
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
});
}
else
{
alert('Error');
}
});
I am using the add_id to retrieve data from the database in my controller below:
public function load_add()
{
$this->load->model('Product_model');
$data['advert_data']=$this->Product_model->get_specific_add($this->input->post('add_id'));
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add',$data);
$this->load->view('include/footer');
}
I am getting an error at the point of data retrieval from DB, as the model does not have the add_id. Following is my model code
public function get_specific_add($image_id)
{
$this->db->select('adverts.title,adverts.item_condition,adverts.add_type,adverts.address,adverts.price,adverts.negotiable,adverts.product_description,adverts.create_time, users.first_name,users.last_name,users.mobile,users.email,users.image_name');
$this->db->from('adverts,countries,states,cities,users');
$this->db->where('adverts.id= $image_id_new');
$this->db->where('adverts.country_id=countries.id');
$this->db->where('adverts.city_id=states.id');
$this->db->where('adverts.area=cities.id');
$this->db->where('adverts.user_id=users.id ');
$this->db->where('adverts.id= $image_id');
$query = $this->db->get();
return $query->result();
}
Appreciate if someone can help me on this. The page i am trying to load is Site/site_load_add. Thanks
You've call same url with both GET|POST, First call POST is ok, but in GET that's your error.
$.ajax({
// first call is OK!
url:"<?php echo site_url('Site/load_add')?>",
method:"POST",
dataType: "html",
data:{add_id:image_id},
success:function(data)
{
// BUG HERE, This's a GET call and with No query string
// Will `$this->input->post('add_id')` found nothing.
window.location.href = "<?php echo site_url('Site/load_add')?>";
}
Thank you all for the support, I got this sorted by passing the ID of the advert a below:
public function load_add($id)
{
$this->load->model('Product_model');
$data['advert_data'] = $this->Product_model->get_specific_add($id);
$data['adverts'] = $this->Product_model->get_adverts();//get database query output to the array
$array_info2 = array(
"title" => "View Add"
);
$this->load->view('include/header', $array_info2);
$this->load->view('include/navbar_logged_in');
$this->load->view('Site/site_load_add', $data);
$this->load->view('include/footer');
}
Thanks
Related
I am using echo json_encode($data); to send an array back to jquery ajax. I want to get data from json and retrieve it on input text and I got this error like: The URI you submitted has disallowed characters.
I don't know on how to pass data in model. Btw, I'm using codeigniter.
Once I click the edit button, a modal will appear. Please, help me guys!!
Button
<a onclick="edit_content_by_id('.$row->post_id.')" title="Edit"><span class="ti-pencil"></span>
Model
public function GetContentById($id) {
$query = $this->db->select('*')->from('cms_posts_tbl cpt')->
join('cms_contents_tbl cct', 'cct.post_id = cpt.post_id')->
join('cms_category_tbl ccat', 'ccat.post_category_id = cpt.post_category')->
where('post_id', $id)->get();
foreach($query as $row) {
$data = $row;
}
echo json_encode($data);
}
jQuery Ajax
function edit_content_by_id(id) {
var data = { content_id : id };
$.ajax({
type: 'POST', url: 'http://localhost:81/ci_sample/model/GetContentById('+ id +')',
data: data, dataType: 'json',
cache: false,
success:function(data) {
$('#modal_content').modal('show');
$('#modal_content').find($('post_title')).val(data.post_title);
}
});
}
header('Access-Control-Allow-Origin:*');
Go to config.php and configure this variable.
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-#\=';
I have this simple AJAX code to get the User Timezone whenever he is successfully login to the dashboard.
JS
<script type="text/javascript">
$(document).ready(function(){
'use strict';
/**
* Getting user current timezone offset
*/
var timezone_offset = new Date().getTimezoneOffset();
timezone_offset = timezone_offset == 0 ? 0 : -timezone_offset;
$.ajax({
type: "POST",
url: "<?php echo base_url('dashboard'); ?>",
data: {"timezone": timezone_offset},
cache: false,
success: function(data){
alert(data);
},
error: function(){
console.log('error');
}
});
});
</script>
Controller
public function index()
{
$data = $this->global_data->logged_user();
$data['page_title'] = 'Dashboard';
$data['page_directory'] = 'pages/dashboard';
$data['greeting'] = $this->global_helpers->greeting() . ' !';
$chart_data = array();
$order_history = $this->trade_history->chart_data();
foreach($order_history AS $d)
{
$chart_data[] = array(
'y' => $this->global_helpers->month_name($d->month) ."' ". $d->year,
'a' => $d->profit,
'b' => $d->loss
);
}
echo $_POST['timezone'];
$data['chart_data'] = json_encode($chart_data);
$this->load->view('template', $data);
}
But the problem is, when it's success why it's return the HTML header? not the data I wish to get?
What do I do wrong here? And I put this AJAX code in footer.php file. Sorry for this silly question but I just got stuck here.
I appreciated any kind of helps, Thanks!
Edited
Sorry for this silly post, I can't use that way, i just need to create another controller for handling any kind of AJAX value, so the problem will be fixed.
Well, you can't render HTML inside an alert anyway.
I see that you ended up solving this issue, but, FYI, if you ever need a controller to return HTML as data, use the third parameter on view method:
echo $this->load->view('template', $data, TRUE);
See more at Codeigniter docs :)
I'm struggeling to use codeigniter the way it was created. I'm opening an edit page (order). I want to change data on the page which will be dynamically saved after leaving a field. But when I'm not succeeding in the way codeigniter works or with other words on a "nice way". I don't want to be depending on the uri structure and get the data with uri segment, like the code is now. I want to improve the code beneath but i'm not succeeding...
This is the code to open my view
public function edit($id = NULL) {
// Fetch a page or set a new one
$this->load->model('shop_m');
$this->load->model('details_m');
$this->data['subtitle'] = 'incoming';
if ($id) {
if($this->transfer_m->get_permission($id) > 0){
$this->data['transfer'] = $this->transfer_m->get_rec($id);
// $this->data['transfer'] = $this->transfer_m->get($id,true);
count($this->data['transfer']) || $this->data['errors'][] = 'page could not be found';
$this->data['details'] = $this->details_m->get_by(array('doc_no' => $id),FALSE);
}
else{
redirect('admin/Dashboard', 'refresh');
}
} else {
$this->data['transfer'] = $this->transfer_m->get_new();
}
$this->data['shop_from'] = $this->shop_m->get($this->data['transfer']->from_customer,TRUE);
$this->data['shop_to'] = $this->shop_m->get($this->data['transfer']->to_customer,TRUE);
// Load the view
$this->data['subview'] = 'pages/details/transfer_edit';
$this->load->view('pages/main', $this->data);
}
My ajax call
function add_shop(shop){
var id = $('#doc_no').text();
$.ajax({
url: base_url+"/admin/transfer/add_shop/"+id+"/"+shop,
async: false,
type: "POST",
data: "",
dataType: "html",
success: function(data) {
$('#ajax-content-container').hide();
}
})
}
my controller function to add a shop
public function add_shop($id){
$data = array('to_customer' => $this->uri->segment(5));
$this->transfer_m->save($data,$id);
}
Any help will be appreciated!!
You can use post. Modify your ajax call and pass the data like below. See the document here https://api.jquery.com/jquery.post/
data: { id: id, shop: shop }
This data can be accessed $this->input->post('id'); $this->input->post('shop');
Hey I'm new to CI and have scoured the internet for a tutorial that will work but for some reason it won't work. Can someone help me with the code please:
What's the right edit to the code to submit an entry to the database via ajax without reloading the page?
Controller:
public function index(){
$this->load->helper('url');
$this->load->view('template');
}
function create()
{
$this->load->library('form_validation');
$this->load->helper('form');
$this->load->model('dbmodel');
$response = array();
$this->load->model('dbmodel');
$result = $this->dbmodel->addnew_row();
}
Model:
public function addnew_row() {
$data = array(
'title' => $this->input->post('title'),
'description' => $this->input->post('description'),
);
$result = $this->db->insert('books', $data);
return $result;
}
View Form:
<h2>Create</h2>
<?php echo form_open('welcome/create', array('id'=>'form'));?>
<p>Title: <?php echo form_input('title') ?></p>
<p>Description: <?php echo form_input('description') ?></p>
<?php echo form_submit('btn_submit','Save'); ?>
<?php echo form_close();?>
View AJAX:
// $.POST Example Request
$('#form').submit(function(eve){
eve.preventDefault();
var title = $('#title').val();
var description = $('#description').val();
url = '<?php echo site_url('welcome/create');?>'
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
}
$(#dynamic_container).html(response.output);
});
});
Ok,At first you need to briefly go through the syntax of jQuery.ajax() before using it.
Now going though the AJAX code you mentioned in the question , this block of code is not suppose to be there
$(#dynamic_container).html(response.output);
AJAX provides Callback Function Queues to manipulate response before/after an AJAX call has been successfully completed , and in your case using success will resolve the issue :
$.ajax({
url: url,
type: 'POST',
data:{title:title, description:description
},
success : function(response){
$(#dynamic_container).html(response.output);
}
});
And you might be interested in using jQuery.post().
I am new to jquery and am having trouble with the autocomplete function. edit:I should mention I am using MVC with Codeigniter. My AJAX response is returning like this [{"customer_name":"Adecco Management & Consulting S.A."}]. It is also not all in a row it is each character in the dropdown like this
[
{
"
c
u
s
t
and so on. Here is my autocomplete script.
$('#cust_name').autocomplete({
source: function(request,response){
var request = {
toSearch: $('#cust_name').val()
};
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
response(data);
}
});
}
});
and my controller:
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
echo json_encode($data['id']);
}
model:
public function autoComplete(){
$toSearch = $_POST['toSearch'];
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
input in view:
<input data-input-type="cust_name" id="cust_name" class="ids form-control search-query " type="text" name="customer_name">
I am not sure I set up the jquery function correctly but the response includes the desired results, in the wrong format, when I type in the input. Thanks for any help you can give!
I received the answer outside of SO and want to post the solution here for others.
controller: I needed to put the results into an array and pass that to the ajax response as one object.
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
$results = array();
foreach($data['id'] as $row){
$results[]=$row->customer_name;
}
echo json_encode($results);
}
jquery: As far as I understand this section, I wasn't making use of the built in functions and therefore overwriting the request variable that autocomplete sets up.
$('#cust_name').autocomplete({
source: function(request,response){
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
var items = JSON.parse(data);
response(items);
}
});
}
});
model: didn't change much. I added distinct to limit dup values.
public function autoComplete(){
$toSearch = $_POST['term'];
$this->db->distinct();
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
Thanks to all those who helped me with this!