Codeigniter Ajax - Help Needed with Error - php

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().

Related

use ajax call to load a view codeigniter

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

codeigniter not returning json/ajax response

I have read a lot on codeIgniter ajax response. I have and modified my ajax script multiple times yet codeIgniter does not return the json response although I see the response when debugging with firefox developer browser under the network tab of web console. here's what i have written
AJAX script
$("#class_id").change(function(){
var class_id = $("#class_id").val();
alert(class_id);
alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
dataType: 'json',
data: {class_id: class_id},
success: function(response) {
$("#res").html(reponse.class_id);
}
});
return false;
});
controller
function set_class_id()
{
if ($this->session->userdata('teacher_login') != 1)
redirect(base_url(), 'refresh');
//echo "dsdsd".$this->input->POST('class_id');
if (!empty($this->input->POST('class_id')))
{
$page_data = array('class_id' => $this->input->POST('class_id'));
//$response["JSON"] = json_encode($page_data);
$response = array('class_id' => $this->input->POST('class_id'));
echo json_encode($page_data);
$this->load->view('backend/index', $page_data);
}
}
Have you tried using
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
Also, check th output class for more info Codeigniter Output Class
So I figured a way out. using just php, I sent the class_id to the controller using a submit button then checked for the response on the page to enable the subject dropdown. Although i haven't figured why the ajax isn't working yet. thanks guys for your inputs

AJAX on success return HTML files instead the data value?

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 :)

How to ajax request to custom page in prestashop 1.7

Am apology for my bad english. Am new to prestashop. Please anybody help. How to send AJAX request to custom php file in prestashop
//My js file
$.ajax({
url : baseUrl + "modules/<myModule>/ajaxfunc.php",
type: "POST",
cache: false,
data : {form_data: 1 , action:'imageuploadAction'},
beforeSend: function() {
$('body').append('<div class="loading_popup">Loading...</div>');},
success: function(data){
console.log(data);
}
});
// php file
// modules/<myModule>/ajaxfanc.php
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
class ajaxfuncAjaxModuleFrontController extends ModuleFrontController
{
public function imageuploadAction() {
die('here');
}
}
?>
I didn't know its be correct or not. please guide me.
You can use an ajax front controller in your module and generate the URL you need for the Ajax request in the module itself with a hook.
See Make an ajax request from a Prestashop module
I have found the solution to get the proper Ajax request in prestashop 1.7
//In tpl file
<script>
var url= {url entity='module' name='<myModuleName>' controller='<MyControllerName>' params = ['var1' => 1,'var2' => 2,action => 'MyControllerAction']}
</script>
//In Js file
$.ajax({
url : url,
type: "POST",
data : 'var3='3,
success : function(response){
console.log(response);
}
});
//In Controller Php file
<?php
require_once(dirname(__FILE__).'../../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../../init.php');
class <MyModule><MyController>ModuleFrontController extends ModuleFrontController
{
public function initContent()
{
$this->ajax = true;
parent::initContent();
}
// displayAjax for FrontEnd Invoke the ajax action
// ajaxProcess for BackEnd Invoke the ajax action
public function displayAjaxMyControllerAction()
{
$var1 = Tools::getValue('var1');
$var2 = Tools::getValue('var2');
$var3 = Tools::getValue('var3');
header('Content-Type: application/json');
die(Tools::jsonEncode(['var1'=> $var3]);
}
}

Ajax Auto-complete search with Code-igniter

Ajax Auto-complete search with Code-igniter from my database. I am trying to search my database and Ajax completes the search from items saved on my database. I believe I am missing a simple trick. Maybe I am writing my controller or maybe everything all wrong... Code below
// View Page
Location path: application/views/template/header
<form class="navbar-form" >
<input type="text" id="mysearch" placeholder="search" onkeyup="doSearch();">
<br />
<script>
// This is the jQuery Ajax call
function doSearch()
{
$.ajax({
type: "GET",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
//class example
</script>
Note: My form or search box is inside my header... So my view page is located in template/header
// Controller Page
Location path: codeigniter/application/controller/ajax.php
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('ajax_model');
//$this->load->helper('url_helper');
}
public function form ()
{
$data['title'] = 'Ajax search';
$this->load->view('template/header');
}
// function ends
public function getdata($param = '')
{
// Get data from db
$data['ajaxdata'] = $this->ajax_model->search($param);
// Pass data to view
$this->load->view('template/header', $data);
}
}
?>
// My Model
Location path: application/model/Ajax_model.php
<?php if (! defined('BASEPATH')) exit('No direct script access');
class Ajax_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function search ($title){
$this->db->select('title');
$this->db->select('text');
$this->db->like('title', $title, 'both');
return $this->db->get('news');
}
}
?>
Please be aware I am new to CodeIgniter. It explains my rather obvious ignorance
$data['ajaxdata'] = $this->ajax_model->search($param);
$data['ajaxdata'] = json_encode($data['ajaxdata']);
echo $data['ajaxdata'];
Ajax method expects data in form of (JSON) string. So you don't need to load header again. Instead, just pass needed data from DB and jQuery will put it in designated place. In this case into element with id of searchresults.
Try changing this
$this->load->view('template/header', $data);
to
$content = $this->load->view('template/header', $data,TRUE);
// load view to a variable.
echo $content;
if i am clear what you need try:
first define ajax request type:
function doSearch()
{
$.ajax({
type: "GET",
dataType:"html",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
Then in controller :
just echo your view:
$auto_complete_html = $this->load->view('template/header', $data,TRUE);
echo $auto_complete_html;
//good practice always die(); after ajax called
die();
Try using POST in AJAX instead of GET:
<script>
// This is the jQuery Ajax call
function doSearch()
{
var search = $("#mysearch").val()
$.ajax({
type: "POST",
url:"localhost/codeigniter/ajax/getdata/",
data:'search=' + search,
success:function(data){
$("#searchresults").html(data);
}});
}
//class example
</script>
Then in your controller Get THE POSTED data from AJAX
public function getdata()
{
$param= $this->input->post('search');
// Get data from db
$result = $this->ajax_model->search($param);
// Pass data to view
echo $result;
}

Categories