I am actually trying to obtain a dynamic dependent select option for city based on region and in my controller i am returning a string(using echo) but unfortunately the string is not rendering in the select option(of cities) on the browser. but i can see it by inspection or by printing on the console.
my jquery:
<script >
$(document).ready(function(){
$('.dynamic').change(function(){
if($(this).val() != '')
{
var select = $(this).attr("id");
var value = $(this).val();
var dependent = $(this).data('dependent');
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('dynamicdependent.fetch') }}",
method:"POST",
data:{select:select, value:value, _token:_token, dependent:dependent},
success:function(result)
{
$('#cityName').html(result);
console.log(result);
console.log(result);
}
})
}
});
$('#RegionName').change(function(){
$('#cityName').val('');
});
});
</script>
: my controller
class DynamicDependent extends Controller
{
public function fetch(Request $request)
{
$select = $request->get('select');
$value = $request->get('value');
$dependent = $request->get('dependent');
$data = city::where($select,$value)->get();
$output = '<option value="">Select '.ucfirst($dependent).'</option>';
foreach($data as $row)
{
$output .= '<option value="'.$row->$dependent.'">'.$row->$dependent.'</option>';
}
echo $output;
}
}
:no eroor message
Here is the picture of the actual outpout :
I suspect that the response might not be that well formed.
Try to return a proper response instead of echoing yourself.
// other code in the controller ...
return response()->json($output);
If it doesn't help, please include the actual response you get in the browser/console.
thanks. actually i was using bootstrap select library and there is a class called selectpicker when i removed this class from the select tag of city it worked fine
Related
I'm just getting started with codeigniter I want to insert some data into database via ajax but I have a problem with my ajax call;
I've been searching for two hours but I could not solve the problem.
My problem is when I click on submit button it says forbidden.
Also my csrf protection is set to TRUE! Please help, thanks
JS
$(document).ready(function() {
$(".addbtn").click(function (e) {
e.preventDefault();
if($("#mname").val()==='' ||
$('#sname').val() === '' ||
$('#genre').val()==='' ||
$('#album').val()==='' ||
$('#publishyear').val() ==='' ||
$('#artist').val()==='')
{
alert("Please fill all the fields!");
return false;
}
$("#FormSubmit").hide();
$("#LoadingImage").show();
var baseurl = "<?php echo base_url(); ?>";
var data = {
'mname': $("#mname").val(),
'sname': $('#sname').val(),
'genre': $('#genre').val(),
'album': $('#album').val(),
'publishyear': $('#publishyear').val(),
'artist': $('#artist').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>':
'<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: "POST",
url: baseurl+"index.php/admin_page/send_ajax",
data: data,
success:function(){
alert("success");
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show();
$("#LoadingImage").hide();
alert(thrownError);
}
});
});});
Config file
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
Controller
public function send_ajax(){
$data = array(
'name_of_music'=>$this->input->post("mname", TRUE),
'artist'=>$this->input->post("artist", TRUE),
'name_of_singer'=>$this->input->post("sname", TRUE),
'genre'=>$this->input->post("genre", TRUE),
'album'=>$this->input->post("album", TRUE),
'publishyear'=>$this->input->post("publishyear", TRUE)
);
$json_data['lyrics_info_data'] = json_decode($data);
$this->user_model->insert_json_in_db($json_data);
}
Model
public function insert_json_in_db($json_data){
$this->db->insert('lyrics', $json_data);
}
Can you confirm what is the use of this line $json_data['lyrics_info_data'] = json_decode($data); ? I think error is with this line.
You may use $json_data['lyrics_info_data'] = $data; instead of $json_data['lyrics_info_data'] = json_decode($data);
Also the model function need to update.
public function insert_json_in_db($json_data){
$this->db->insert('lyrics', $json_data['lyrics_info_data']);
}
Script update
Codeigniter will regenerate its crcf token on each request and this info will be stored in cookie. So token value you need to take from cookie and send along with ajax data you are passing. What I am doing with folliwing javascript is that, using a common function to attach crcf value along with all the ajax request.
In jquery there is an option to add custom data along with ajax request.
See jquery documentation http://api.jquery.com/jquery.ajaxprefilter/ for more details
<script>
$(document).ready(function(){
function getCookie(c_name) { // A javascript function to get the cookie value
if(document.cookie.length > 0) {
c_start = document.cookie.indexOf(c_name + "=");
if(c_start != -1) {
c_start = c_start + c_name.length + 1;
c_end = document.cookie.indexOf(";", c_start);
if(c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
$.ajaxPrefilter(function(options, originalOptions, jqXHR){ // This function will attach "csrf_test_name" with all the request you are sending.
if (options.type.toLowerCase() === "post") { // Required only if its a post method
var csrf_token = getCookie("csrf_test_name");
// initialize `data` to empty string if it does not exist
options.data = options.data || "";
// add leading ampersand if `data` is non-empty
options.data += options.data?"&":"";
// add _token entry
options.data += "csrf_test_name=" + csrf_token;
}
});
});
</script>
You can remove '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>' from var data.
Important note: if you change $config['csrf_token_name'] = 'csrf_test_name'; in config.php then you need to update this script as well.
Please try after updating your code and let me know if issues still exists.
Make Sure you are getting right base_url() and in javascript you should define the base_url() globally somewhere so that you can access it in any script as below
var baseurl = <?php echo base_url() ?>;
`
You are going way out of your way to make this difficult. csrf is not your problem. Try something like this
$(function () {
"use strict";
$("#form2").submit(function () {
var data = $("#form2").serialize();
//alert(data); return false;
$.ajax({
url: "/log/login",
data: data,
type: "POST",
success: function (msg) {
$("#display").text(msg);
},
error: function (msg) {
$("#display").text("its all bad");
}
});
return false;
});
});
(Of course you will need to put your own form id in etc)
Your controller should look something like this:
$data = array(
'borncity' => htmlspecialchars(trim($this->input->post('borncity'))),
'state' => htmlspecialchars(trim($this->input->post('state'))),
'country' => htmlspecialchars(trim($this->input->post('country'))),
'family' => htmlspecialchars(trim($this->input->post('family'))),
'year' => htmlspecialchars(trim($this->input->post('year'))),
'state1' => htmlspecialchars(trim($this->input->post('state1'))),
'deathcity' => htmlspecialchars(trim($this->input->post('deathcity')))
);
$this->form_validation->set_rules('borncity', 'city of birth', 'required|trim');
$this->form_validation->set_rules('state', 'state', 'required|trim');
$this->form_validation->set_rules('country', 'country', 'required|trim');
$this->form_validation->set_rules('family', 'family', 'required|trim');
$this->form_validation->set_rules('year', 'year', 'required|trim');
$this->form_validation->set_rules('state1', 'Born State', 'required|trim');
$this->form_validation->set_rules('deathcity', 'Death City', 'trim');
if( $this->form_validation->run() == FALSE) {
echo validation_errors();
}else
{
$this->db->insert('cities', $data);
echo "Success"; //this will show up in your ajax success line
}
}
Use Codeigniter's form validation in your controller. You do not need to use json decode. Please note these are examples
I want to show tick.png image on clicking save button when data inserted in database successfully. My view file name is insert_your_committee, model is users_model & controller user
Here is my code of all there files:
My Script of my insert_your_commitee file, All console.log show correct result but success function is not working. What is the problem?
<script>
function save_committee($c_id,$m_id,$start_date){
console.log($c_id);
console.log($m_id);
console.log($start_date);
var mid=$('#irnum'+$start_date).val();
console.log("df"+mid);
var url= "<?php echo site_url("user").'/ref_add';?>";
$.ajax({
url: url,
type: "POST",
dataType:'json',
data: {c_id:$c_id,m_id:$m_id,start_date:$start_date,irnum:mid},
success: function(data){
console.log(data);
$('#'+$start_date).show();
$('#btn'+$start_date).hide();
}
});
}
</script>
My Controller
public function ref_add()
{
$this->load->model('Users_model');
$parms=$this->input->post();
$c_id=$this->input->post('c_id');
$m_id=$this->input->post('m_id');
$s_dateparms=$this->input->post('start_date');
$irnum=$this->input->post('irnum');
$data_to_store = array(
'Cid' =>$c_id,
'Mid' =>$m_id,
'Month' => $s_dateparms,
'Year'=>$s_dateparms,
'Ref_Number' =>$irnum,
);
$params=array();
if ($this->users_model->add_ref($data_to_store)) {
$params['status'] = TRUE;
} else {
$params['status'] = false;
}
$return["json"] = json_encode($params);
echo json_encode($return);
}
And Here is my model
function add_ref($data)
{
$this->db->insert('reference', $data);
$report = array();
$report['error'] = $this->db->_error_number();
$report['message'] = $this->db->_error_message();
if($report !== 0){
return true;
}else{
return false;
}
}
I am not completely sure, but in order to get ajax to work, I had to add return false; after the ajax call in the function.
In my case, I was using ajax for login and backend was in codeigniter.
below code returns me blank in ajax response please help me
when i check my controller it also gives me blank.
Can you please check the code below to find out the reason of problem
here is my ajax code:
window.onload = function() {
$.ajax({
type:'json',
url:"http://localhost/myapne/admin/adminMenu/getMsg",
success:function(data){
alert(data);
// PrintSms(data);
},
error: function(error){
console.log(error);
}
});
}
here is my controller:
class AdminMenu extends CI_Controller{
function getMsg(){
$this->load->model('adminGetModel');
$data = $this->adminGetModel->getSms();
return array("status"=>"success","rows"=>$data);
}
}
here is my model:
class AdminGetModel extends CI_Model{
function getSms(){
// $a = $count*10;
// $b = $a + 10;
$this->load->database();
$query = $this->db->get('tblsms');
$rows = array(); //will hold all results
foreach($query->result_array() as $row)
{
$rows[] = $row; //add the fetched result to the result array;
}
return $rows;
}
}
Json_encode the data and use echo instead of return:
echo json_encode(array("status"=>"success","rows"=>$data));
This will return a string. If you want to turn it back into an object, you will then have to use JSON.parse() (or $.parseJSON if you're using jquery) in your ajax success handler.
http://rimi-classified.com/ad-list/west-bengal/kolkata/electronics-and-technology
The above link has a filter in the left. I am trying to use ajax to get city from state. but as the ajax is triggered the entire query is changing.
SELECT * FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'pages'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
It is taking the controller name in the query (controller name is pages).
The actual query is:
SELECT *
FROM (`ri_ad_post`)
WHERE `state_slug` = 'west-bengal'
AND `city_slug` = 'kolkata'
AND `cat_slug` = 'electronics-and-technology'
AND `expiry_date` > '2014-03-21'
ORDER BY `id` DESC
// Controller
public function ad_list($state,$city,$category,$sub_cat=FALSE)
{
if($state===NULL || $city===NULL || $category===NULL)
{
redirect(base_url());
}
$data['ad_list'] = $this->home_model->get_adlist($state,$city,$category,$sub_cat);
$this->load->view('templates/header1', $data);
$this->load->view('templates/search', $data);
$this->load->view('ad-list', $data);
$this->load->view('templates/footer', $data);
}
public function get_cities()
{
$state_id = $this->input->post('state');
echo $this->city_model->get_cities($state_id);
}
// Model
public function get_adlist($state,$city,$category,$sub_cat=FALSE)
{
if ($sub_cat === FALSE)
{
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
}
$this->db->where('state_slug', $state);
$this->db->where('city_slug', $city);
$this->db->where('cat_slug', $category);
$this->db->where('sub_cat_slug', $sub_cat);
$this->db->where('expiry_date >', date("Y-m-d"));
$this->db->order_by('id', 'DESC');
$query = $this->db->get('ad_post');
return $query->result_array();
//echo $this->db->last_query();
}
//ajax
<script type="text/javascript">
$(document).ready(function () {
$('#state_id').change(function () {
var selState = $(this).val();
alert(selState);
console.log(selState);
$.ajax({
url: "pages/get_cities",
async: false,
type: "POST",
data : "state="+selState,
dataType: "html",
success: function(data) {
$('#city').html(data);
$("#location_id").html("<option value=''>--Select location--</option>");
}
})
});
});
</script>
Please help me how to solve this issue. Please check the url I have provided and try to select a state from the filter section the problem will be more clear.
In .js what is the value of selState ?
In your model, you should if() else() instead of just a if, because your query will get override.
Where is the get_cities function ? Can we see it ?
On your url, the problem is that your ajax url doesn't return a real ajax call but an entire HTML page which is "harder" to work with. Try to change it into json (for dataType's ajax()) You should only do in your php something like this :
in your controller :
public function get_cities()
{
$state = $this->input->post('state');
//Do the same for $cat
if (!$state) {
echo json_encode(array('error' => 'no state selected'));
return 0;
}
$get_cities = $this->model_something->getCitiesByStateName($state);
echo json_encode($get_cities);
}
You should definitely send with ajax the $cat info
this is the method I want to send data to it
function get_lesson($reshte,$poodeman){
$this->load->model('dropdown_model');
header('Content-Type: application/x-json; charset=utf-8');
echo(json_encode($this->dropdown_model->get_lessons($reshte,$poodeman)));
}
and this is the get_lessens() function in the model file.
function get_lessons($reshte = null, $poodeman=NULL){
$this->db->select('rlessid, title');
if($reshte != NULL AND $poodeman!= NULL ){
$this->db->where('reshteid', $reshte);
$this->db->where('poodemanid', $poodeman);
}
$query = $this->db->get('tbllessons_root');
$lessons = array();
if($query->result()){
foreach ($query->result() as $lesson) {
$lessons[$lesson->rlessid] = $lesson->title;
}
return $lessons;
}else{
return FALSE;
}
}
and this is my ajax call at the view file
var reshteid = $('#reshte').val();
var poodemanid = $('#poodemanha').val();
$.ajax({
type:"POST",
url:"http://localhost/crud-grocery/index.php/examples/get_lesson/",//+reshte+"/"+poodeman,
data: "reshte="+reshteid+"&poodeman="+poodemanid,
success: function(lessons)
{
$.each(lessons,function(rlessid,title){
var opt = $('<option />');
opt.val(rlessid);
opt.text(title);
$('#lessons').append(opt);
});
}
});
as you see I am trying to chain options in the form
but The problem comes up when I try to post (send) two parameters to the controller method
any idea?
In your controller, you need to get POST values not as parameters:
//in controller
function get_lessons(){
...
//get POST values
$reshte = $this->input->post('reshte');
$poodeman = $this->input->post('poodeman');
You have to pass data as a javascript object literal:
...
data: {
reshte: reshteid,
poodeman: poodemanid
}
....