Post 500 (Internal Server error) ajax in codeigniter - ajax

I have a problem to sending data with ajax, when i click button save to sending data to database. but when i push F12 the error show
POST http://[::1]/sys-web/admlogin/manufacture/addmanufacture 500 (Internal Server Error)
send # http://[::1]/sys-web/assets/js/jquery-2.1.4.min.js:4
ajax # http://[::1]/sys-web/assets/js/jquery-2.1.4.min.js:4
save # http://[::1]/sys-web/admlogin/manufacture:374
onclick # http://[::1]/sys-web/admlogin/manufacture:507
CI Controller
public function AddManufacture()
{
$data = array(
'manufacturing_name' => $this->input->post('manufacturing_name'),
'address' => $this->input->post('address'),
'email' => $this->input->post('email'),
'telephone' => $this->input->post('telephone'),
'join_date' => $this->input->post('join_date')
);
$insert = $this->m_manufacture->save($data);
echo json_encode(array("status" => TRUE));
}
CI Model :
function save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
CI View :
function save()
save_method = 'add';
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('admlogin/manufacture/addmanufacture')?>";
} else {
url = "<?php echo site_url('admlogin/manufacture/editmanufacture')?>";
}
// ajax adding data to database
var formData = new FormData($('#form')[0]);
$.ajax({
url : url,
type: "POST",
data: formData,
contentType: false,
processData: false,
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
}
});
}

Related

Q: how to make form validation codeigniter with ajax?

Hello guys i try to make form validation codeigniter with ajax server side but it still not working, i want to make error message 'required' display under form input. what is it wrong in my code.
this is my controller
function ajax_submit_kategori() {
$this->load->library('form_validation');
$data['nama'] = $this->input->post('kategori');
$data['id_legislator'] = $this->input->post('legislator');
$this->db->insert('galangsuara_has_categories',$data);
$return['status'] = '0';
echo json_encode($return);
}
this is my ajax
<script type="text/javascript">
$('#input').submit(function(event){
event.preventDefault();
Pace.track(function(){
var cate = $('#tim').val();
var dapi = $('#dapil').val();
var legi = $('#legislatif').val();
$.ajax({
url: "<?= site_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
$("#modal_tambah").modal('hide');
document.getElementById("input").reset();
var table = $('#table').DataTable();
table.ajax.reload();
window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});
});
return false;
});
anyone can help me? :(
Try This
Controller code:
function ajax_submit_kategori() {
$status = 1;
$error = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('kategori', 'Kategori', 'required');
$this->form_validation->set_rules('dapil', 'Dapil', 'required');
$this->form_validation->set_rules('id_legislator', 'Id_legislator', 'required');
if ($this->form_validation->run() == FALSE) {
$status = 0;
$error = validation_errors();
} else {
$data['kategori'] = $this->input->post('kategori');
$data['dapil'] = $this->input->post('dapil');
$data['id_legislator'] = $this->input->post('id_legislator');
$this->db->insert('galangsuara_has_categories', $data);
}
$return['status'] = $status;
$return['$error'] = jsone_encode($error);
echo json_encode($return);
exit();
}
ajax code :
$.ajax({
url: "<?= base_url().'timgalang/ajax_submit_kategori'?>",
type : 'post',
data : {kategori: cate, dapil: dapi, legislator: legi},
dataType: "json",
success : function(data){
console.log(data);
//here, first you need to check your data is perfect for error then do according to your wish
//$("#modal_tambah").modal('hide');
//document.getElementById("input").reset();
//var table = $('#table').DataTable();
//table.ajax.reload();
//window.location = 'kategori';
},
error: function(data){
alert('ERROR');
}
});

Download maatwebsite excel using ajax in laravel

I'm trying to download an excel file using ajax method in laravel.
Controller function:
$myFile = Excel::create($name, function ($excel) use ($export) {
$excel->sheet('Data', function ($sheet) use ($export) {
$sheet->fromArray($export);
$sheet->cells('A1:N1', function ($cells) {
$cells->setBackground('#dbdbdb');
$cells->setFontColor('#000000');
$cells->setFontWeight('bold');
$cells->setFont(array(
'family' => 'Calibri',
'size' => '9',
));
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 9,
),
));
});
});
$myFile = $myFile->string('xlsx');
$response = array(
'name' => $name,
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile),
);
return response()->json($response);
Ajax function:
$(document).on('click', '.ExportJobs', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var ids = [];
$(".InvoiceCheckBox:checked").each(function(e) {
ids.push(this.value);
});
data = {
"ids": ids,
};
$.ajax({
method: "POST",
url: "/exportNew",
data: data,
success: function(response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
}
});
});
But using above controller method is not returning excel formatted file if I change string value from xlsx to csv then csv formatted file is getting downloaded.
How do we make the excel formatted file downloaded? Any suggestions, Please!
I know this is quite late, but posting for others who struggle with same issue like me
I also needed to download excel from using Maatwebsite excel library by using ajax post call.
added a button to fire the ajax call to download excel file
<button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
Download
</button>
Used following js code to post ajax request
function downloadExcel() {
var salaryMonth = $("#dp-salary-month").datepicker("getDate");
var department = $("#cbox-department");
var month = new Date(salaryMonth).getMonth() + 1;
var year = new Date(salaryMonth).getFullYear();
$.ajax({
xhrFields: {
responseType: 'blob',
},
type: 'POST',
url: '/downloadPayroll',
data: {
salaryMonth: month,
salaryYear: year,
is_employee_salary: 1,
department: department.val()
},
success: function(result, status, xhr) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
// The actual download
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
in routes/web.php file set the reoute for my controller
Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController#downloadPayroll');
Here I used maatwebsite/excel library to generate excel file with FromQuery approach but due to library update Excel::create has been replaced by Excel::download in "maatwebsite/excel": "^3.1" I used download method in my case here is my HelperClass to generate records according to my requirement
PayrollHelper.php
namespace App\Http\Helpers;
use App\PayrollEmployee;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class PayrollHelper implements FromQuery
{
use Exportable;
public function forDepartment(int $department)
{
$this->department = $department;
return $this;
}
public function forMonth(string $month)
{
$this->month = $month;
return $this;
}
public function query()
{
// get the salary information for the given month and given department
return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]);
}
}
finally in my controller
class PayrollController extends Controller
{
public function downloadPayroll(Request $request)
{
$file_name = '';
try {
$requestData = $request->all();
$salary_month = $requestData['salaryMonth'];
$salary_year = $requestData['salaryYear'];
$department = $requestData['department'];
$is_employee_salary = boolval($requestData['is_employee_salary']);
$month = Carbon::createFromDate($salary_year, $salary_month);
$month_start = Carbon::parse($month)->startOfMonth();
$formated_month = Carbon::parse($month)->format('F Y');
$file_name = 'Employee_salary_' . $formated_month . '.xlsx';
// to download directly need to return file
return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
} catch (exception $e) {
}
}
}
After creating excel file return file to get as ajax response as blob
That's all
Just see the xhrFields to set responseType as blob and then see the ajax success part. Hope you everyone find the solution:
<script>
$(document).ready(function(){
$("#ExportData").click(function()
{
dataCaptureExport();
});
});
function dataCaptureExport(){
var FromDate = $('#dateFrom').val();
var ToDate = $('#dateTo').val();
var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
$.ajax
({
type: "POST",
url: '{{ route('invoice_details_export') }}',
data: dataString,
cache: false,
xhrFields:{
responseType: 'blob'
},
success: function(data)
{
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = `Invoice_details_report.xlsx`;
link.click();
},
fail: function(data) {
alert('Not downloaded');
//console.log('fail', data);
}
});
}
It's late but help for others
You can do this way
In Ajax
$(document).on('click', '#downloadExcel', function () {
$("#downloadExcel").hide();
$("#ExcelDownloadLoader").show();
$.ajax({
url: '{{ route("admin.export_pending_submitted_tasks") }}',
method: "GET",
cache: false,
data: {
search_partner,
search_state,
search_city,
_token,
},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
},
error: function (ajaxContext) {
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
alert('Export error: '+ajaxContext.responseText);
}
});
});
In Controller
// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
$input = $request->input();
$pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';
$pendingTaskList = $pending_submitted_tasks->where('status', 'pending')->get();
if($pendingTaskList->count() > 0):
$myFile = Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
$response = array(
'name' => "Pending-Task-List.xlsx",
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
);
return response()->json($response);
else:
return back()->with('message', 'No Pending tasks available to download!!');
endif;
}
If you are using jquery:
// In controller:
return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);
// Ajax:
$.ajax({
type: 'GET',
url: '{{ route("some.route") }}',
data: {
"_token": "{{ csrf_token() }}"
},
xhrFields:{
responseType: 'blob'
},
beforeSend: function() {
//
},
success: function(data) {
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(data);
window.open(objectUrl);
},
error: function(data) {
//
}
});

How to send an ajax contact form with to a recipient email address

I've currently got this:
$.ajax({
url: '/some/url',
dataType: 'json',
type: 'POST',
data: formData,
success: function(data) {
if (window.confirm('Thank you for your message. Can I erase the form?')) {
document.querySelector('.form-input').val('');
}
},
error: function(xhr, status, err) {
console.error(status, err.toString());
alert('There was some problem with sending your message.');
}
});
Instead of it going to a URL, how can I change it to send directly to a specific email address? I am using this contact form with a React app I've created.
So react component, class based.
class Foo extends Component {
popupQuestion() {
// implement method
}
sendEmail() = () => {
axios.post('/some/url', {
subject: 'mail',
to: 'someone#example.com',
body: 'something',
name: 'name'
})
.then(function (response) {
popupQuestion();
})
.catch(function (error) {
console.log(error);
return 'Error occurred. Please refresh page and try again.';
});
}
render() {
return(
<form onSubmit={this.sendEmail}>
// ...
</form>
);
}
}
And php method that will be executed on some/url
public function sendEmailAction(): bool
{
$request = // get request;
$subject = $request->get('subject');
$to = $request->get('to');
$body = $request->get('body');
$name = $request->get('name');
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom(['mymail#exmaple.com' => 'me'])
->setTo([$to => $name])
->setBody($body);
$sent = $mailer->send($message);
return $sent ? true : false;
}

checking if the success data is empty in ajax method of jquery

I have two select boxes in my form.when a user select an option of first select box the options of second select box will be shown by jquery ajax.My problem is that some options of first select box has no record in database and when they selected the second select box should not be shown.I need to check if the data is empty .I treid this code but nothing happens
view:
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('section').change(){
var sec_id=$(this).val();
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
if(!resp)
$('#subsec').hide();
else
$('#subsec').show();
$('$subsec').html(resp)
})
}
});
</script>
you can try this
$.ajax({
url:url,
type:'post',
success:function(resp){
if(resp == "" || resp == null){
$('#subsec').hide();
}
else {
$('#subsec').show();
$('#subsec').html(resp);
}
})
}
});
I have added inline comments to help you out
class Article_Controller extends CI_Controller
{
public function get_options()
{
$option = $this->input->post('option'); // validate this
//Get a list of Sub options from your model
$model = ''; //your own implementation here
//If no model data returned, send a 404 status header
//and bail
if(!$model){
return $this->output->set_status_header(404);
}
$responce = array(
'suboptions' => $model // array of suboptions the model returned
);
// Ideally Abstract all the Ajax stuff to
// its own controller to keep things Dry
return $this->output
->set_status_header(200)
->set_content_type('application/json')
->set_output(json_encode($responce));
}
}
-
//Global URL variable or put it in <base href>
var URL = "<?php echo site_url();?>";
(function($){
var myForm = {
init : function(){
//initialize myForm object properties here
this.Form = $("form#myFormID");
this.selectChange = this.Form.find("select#mySelectBoxI");
this.newSelect = this.Form.find("select#secondaryselectboxId");
//hide second select with CSS by default
//Bind the Change event to our object(myForm) method
this.selectChange.on('change', $.proxy(this.ChangedEvent, this));
},
ChangedEvent : function(event){ // gets the change event
//Grab the currentTarget(option[i]) value from the event received
//You may also need to pass the CSRF Token
this.buildAjaxRequest({'option' : event.currentTarget.value});
},
buildAjaxRequest : function( data ){
var config = {
cache : false,
url : URL + 'article_controller/get_options',
method : 'POST',
data : data, //'option' : event.currentTarget.value
dataType : 'json'
};
this.makeAjaxRequest(config).then(
$.proxy(this.ResponceHandler, this),
$.proxy(this.ErrorHandler, this)
);
},
makeAjaxRequest : function( config ){
return $.ajax( config ).promise();
},
ResponceHandler : function( data ){
$.each(data.suboptions, function(i, v){
this.newSelect.append('<option value="'.data[i].'">'.data[v].'</option>');');
});
this.newSelect.show();
},
ErrorHandler : function(xhr, statusText, exception){
switch(xhr.status)
{
case 404: //remember the 404 from the controller
alert(xhr.statusText); //handle your own way here
break;
}
},
}
myForm.init();
}(jQuery));
Hi pls try this,
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('#firstSelectBoxId').change("selectboxMethod");
});
function selectboxMethod(){
var sec_id=$("#firstSelectBoxId").val();
alert("Selected from first select"+sec_id);
if(sec_id != null){
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
$('#subsec').show();
$('#subsec').html(resp);
}
});
}else{
$("#subsec").hide();
}
}
</script>

Laravel 4 render view AJAX html is empty

public function index($id)
{
$project = Project::findOrFail($id);
if(Request::ajax())
{
$html = View::make('Milestones.indexpartial', $project)->render();
return Response::json(array('html' => $html));
}
return View::make('milestones.index')->with('project', $project)
->with('title','Milestones');
}
$(".ajaxul a").click(function()
{
var url = $(this).attr('href');
$.ajax(
{
url: url,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajaxloading').show();
}
})
.done(function(data)
{
$('#ajaxloading').hide();
$(".refresh").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
Please help me make this work.
I'm new to AJAX and laravel.
my problem was this line here:
$html = View::make('Milestones.indexpartial', $project)->render();
it gives an error. then i changed it to
$html = View::make('Milestones.indexpartial',array('project' => $project))->render();
the request is a success but the html is empty.
Please help me. Thank you.

Resources