Ajax response Not working in Codeigniter - ajax

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.

Related

How to return resonse from ajax and display it in Blade file in laravel 8

I am trying to integrate sorting system in laravel application, I am able to do ajax call and got the response but how to display that data in blade file.
I have the data already displayed on search page now if user try to sort the and old data will replaced by the new data.
How can I do that.
Controller Code :
public function sort_data(Request $request){
$results='';
if(request()->sub_sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_sub_category);
})->paginate(24);
} elseif (request()->sub_category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->sub_category);
})->paginate(24);
} elseif (request()->category){
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->whereHas('categories', function ($query){
$query->where('slug', request()->category);
})->paginate(24);
} else{
$results = Product::orderBy($request->sorting_selection,'asc')->with('categories')->paginate(24);
}
// $returnHTML = view('pages.user.shop.products.products')->with(["products"=>$results])->render();
// return response()->json(array('success' => true, 'html'=>$returnHTML));
// return response()->json(['products' => $results, 'status' => 200]);
return view('pages.user.shop.products.products')->with(["products"=>$results]);
}
I have already tried the commented code. But not success
$(document).ready(function(){
$('#soting-select').on('change', function(){
var value = document.getElementById('soting-select').value;
var ajaxurl = '/sort-product';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data: {
'sorting_selection' : value
},
success: function(response){
console.log(response);
}
});
});
});
Old Response :
New Response :
You can call render() on the view.
And also you may need to change the $results variable to $products as you have shared the data with $products variable in your blade file.
$returnHTML = view('pages.user.shop.products.products', compact('products'))->render();
See the View source code for more information.

AJAX POST to laravel returning 404 not found

I am trying to process POST data from ajax to laravel controllers but I can't access it. Here is what I am doing in AJAX.
$.ajax({
type:'POST',
url:'/complete_ca_fin',
data: {fin_id: id},
success:function(data){
console.log(data);
$('#modal_complete').modal('hide');
$('html, body').animate({
scrollTop: 0 }, "slow");
$('#message_form').empty().css('display','block').removeClass('alert-danger').addClass('alert-success').text('Finished Good CA has been successfully completed.');
$('#message_form').fadeOut(4000);
setTimeout(function(){
window.location = '/quality_control';
}, 3000);
refresh_check = true;
window.onbeforeunload = null;
},
error: function (data) {
console.log('Error: ' + data);
} // end of error
}); // ajax
id should be accessed in the controller. Here is my route
Route::post('/complete_ca_fin', 'DatasheetController#complete_ca_fin');
And here is my controller
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
When I try to return $id just to test I noticed that it is empty ( I don't if it has anything to do with it ) but I know that var id in the ajax has a value because I tested it in the console.
Here is a sample of the console log. 37 is the value of the id so there should be a value in the controller
You are using findOrfail which means it will throw a 404 if there is no email, you want to be validating if it exists, not 404'ing of not
public function complete_ca_fin(Request $request) {
$id = $request->id;
$complete_ca = FinishedCA::find($id);
if ($complete_ca->exists()){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}
Use Input::get('id'); instead of request , So your method will like this
public function complete_ca_fin(Request $request) {
$id = Input::get('id');
$complete_ca = FinishedCA::findOrFail($id);
if ($complete_ca){
$complete_ca->status = '5';
$complete_ca->save();
return 'success';
}
//return 'success';
}

forbidden in ajax call error function in codeigniter csrf

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

How to post multiple data through $.ajax to Codeigniter controller method

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
}
....

Ajax Form submit

I am new to Ajax. i wanna submit a form through Ajax and save the data sent to the database.
Something like the Facebook Status update - where text area is disabled and then submited. once its saved in the database it comes back and updates the status message on the top. and again the text area is enabled.
this is my form
<?php echo $form->create('StatusMessage', array('type' => 'post', 'url' => '/account/updateStatus', 'id' => 'updateStatus')); ?>
<?php echo $this->Form->input('id', array('value' => $user['User']['id'],'type' => 'hidden')); ?>
<?php echo $this->Form->textarea('message', array('value' => 'What have you been eating ?')); ?>
Edited: Modified as suggested by 0 RioTera
Cakephp Action
function updateStatus() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax'; //THIS LINE NEWLY ADDED
$this->data['StatusMessage']['pid'] = 0;
$this->data['StatusMessage']['commenters_item_id'] = $this->data['StatusMessage']['item_id'] = $this->User->Item->itemId('1', $this->data['StatusMessage']['id']);
unset($this->data['StatusMessage']['id']);
//debug($this->data);
if($this->User->Item->StatusMessage->save($this->data)) {
return true;
} else {
echo 'not saved';
}
} else {
echo 'no';
}
}
Javascript code
$(document).ready(function () {
var options = {
target: '#output2',
// target element(s) to be updated with server response
beforeSubmit: showRequest,
// pre-submit callback
success: showResponse, // post-submit callback
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
$('#updateStatus').submit(function () {
// make your ajax call
$(this).ajaxSubmit(options);
return false; // prevent a new request
});
function showRequest(formData, jqForm, options) {
$('#StatusMessageMessage').attr('disabled', true);
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
alert('shdsd');
}
});
Using jquery and http://jquery.malsup.com/form/ plugin:
$(document).ready(function() {
var options = {
target: '#message', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$('#updateStatus').ajaxForm(options);
});
function showRequest(formData, jqForm, options) {
$('#StatusMessageMessage').attr('disabled', true);
}
function showResponse(responseText, statusText, xhr, $form) {
$('#StatusMessageMessage').attr('disabled', false);
}
I didn't try it but I hope it helps you
i hope that this tutorial will help
http://mohammed-magdy.blogspot.com/2010/10/ajaxformsubmitter.html
This is a function I use to submit forms in cakephp 3.x it uses sweet alerts but that can be changed to a normal alert. It's very variable simply put an action in your controller to catch the form submission. Also the location reload will reload the data to give the user immediate feedback. That can be taken out.
$('#myForm').submit(function(e) {
// Catch form submit
e.preventDefault();
$form = $(this);
// console.log($form);
// Get form data
$form_data = $form.serialize();
$form_action = $form.attr('action') + '.json';
// Do ajax post to cake add function instead
$.ajax({
type : "PUT",
url : $form_action,
data : $form_data,
success: function(data) {
swal({
title: "Updated!",
text: "Your entity was updated successfully",
type: "success"
},
function(){
location.reload(true);
});
}
});
});
This is what a simple action would look like in the controller;
public function updateEntity($id = null){
$entity = $this->EntityName->get($id);
$entity = json_encode($this->request->data);
$this->EntityName->save($entity);
}

Resources