JQuery Ajax POST 500 Interval error - ajax

I have an error 500 (Internal Server Error), I dont know what is the problem
m.ajaxTransport.a.send # jquery.min.js:4
(anonymous function) # add:198
fichier javascript:
$("#addItem").on('click',function(e){
e.preventDefault();
var id_produit = parseInt($("#produit_id option:selected").val());
var prix = parseFloat($('#prix_produit').val());
var remise = parseFloat($('#remise_produit').val());
var qte = parseInt($('#count_produit').val());
var id_facture = <?php echo($count_id); ?>;
var data = [];
data = {
FacturesProduit: {
facture_id : id_facture,
produit_id : id_produit,
prix : prix,
remise : remise,
quatite : qte
}
};
console.log(data);
var url = <?php echo $this->Html->url(array('controller' => 'facturesproduits' , 'action' => 'ajout_produit')); ?>;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
console.log(result);
}
});
});
Action :
public function ajout_produit() {
$message = 'error';
if ($this->request->is('ajax')) {
$data = $this->request->data;
if ($this->FacturesProduit->save($data)) {
$message = 'success';
}
}
echo json_encode($message);
die();
}
thanks

Related

Laravel 5.8 after first ajax request success run another one in same button

i want to store invoice head row in one table and after that store its items rows in another table so i want to run two ajax requests first one for invoice head and the second is for invoice items
here is my ajax code :
function functionOne() {
var allVals = [];
$.each($(".record__select:checked"), function () {
allVals.push($(this).val());
});
var amount = $('#amount').val();
var client = $('#client').val();
var mobile = $('#mobile').val();
var pnr = $('#pnr').val();
var branch = $('#branch').val();
var join_selected_values = allVals.join(",");
alert(allVals.length);
if(amount!="" && client!="" && mobile!="" && pnr!="" && branch!="" && allVals.length >=1) {
$.ajax({
url: "/deposits_service",
type: "POST",
data: {
_token: $("#csrf").val(),
amount: amount,
client: client,
mobile: mobile,
pnr: pnr,
branch: branch
},
cache: false,
success: function (data) {
if(data['success']){
$.ajax({
url: "/deposits_service/",
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success']) {
$(".record__select:checked").each(function() {
$(this).parents("tr").remove();
});
// alert(data['success']);
} else if (data['error']) {
alert(data['error']);
} else {
// alert('Whoops Something went wrong!!');
// alert(data.responseText);
alert(data['error']);
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value ) {
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
}
else
{
alert("Please select row and make sure that you fill all the field !");
}
}
and here is Controller code :
public function store(Request $request)
{
if(Input::get('payment_type') == 'cash'){
$this->validate($request,[
'amount'=>'required|integer|min:0',
'client'=>'required',
'mobile'=>'required',
'pnr'=>'required',
'branch'=>'required',
]);
$deposit = new Deposit();
$deposit->paymentType = $request->get('payment_type');
$deposit->amount = $request->get('amount');
$deposit->total_fare = $request->get('fare');
$deposit->total_tax = $request->get('tax');
$deposit->total_vat = $request->get('vat');
$deposit->amountRemain = $request->get('amount');
$deposit->amount_arabic = $request->input('amount_arabic');
$deposit->amount_english = $request->input('amount_english');
$deposit->client = $request->get('client');
$deposit->mobile = $request->get('mobile');
$deposit->direction = $request->get('directing');
$deposit->pnr = $request->get('pnr');
$deposit->paymentStatus = "0";
$deposit->rowStatus = "0";
$deposit->used = "0";
$deposit->transferred = "0";
$deposit->userSign = Auth::user()->shortsign;
$deposit->branch = $request->get('branch');
$deposit->cashierSign = null;
$deposit->date = Carbon::now();
$deposit->save();
session()->flash('success',__('site.added_successfully'));
return redirect()->route('deposits.index');
}
else {
$this->validate($request,[
'amount'=>'required',
'client'=>'required',
'mobile'=>'required',
'pnr'=>'required',
'branch'=>'required',
]);
$deposit = new Deposit();
$deposit->paymentType = $request->get('payment_type');
$deposit->amount = $request->get('amount');
$deposit->amountRemain = $request->get('amount');
$deposit->amount_arabic = $request->input('amount_arabic');
$deposit->amount_english = $request->input('amount_english');
$deposit->client = $request->get('client');
$deposit->mobile = $request->get('mobile');
$deposit->direction = $request->get('directing');
$deposit->pnr = $request->get('pnr');
$deposit->paymentStatus = "0";
$deposit->rowStatus = "0";
$deposit->used = "0";
$deposit->transferred = "0";
$deposit->userSign = Auth::user()->shortsign;
$deposit->branch = $request->get('branch');
$deposit->cashierSign = null;
$deposit->date = Carbon::now();
$deposit->save();
session()->flash('success',__('site.added_successfully'));
return redirect()->route('deposits.index');
}
}
public function updateAll(Request $request)
{
$depositId = Deposit::latest()->first()?: app(Deposit::class);
$newID = (int)$depositId->id ;
$ids = $request->ids;
DB::table("presales")->whereIn('id', explode(",",$ids))->update(['deposit_refund_no'=>$newID+1,'status'=>'Closed']);
return response()->json(['success'=>"Products Updated successfully."]);
}
here is routes :
Route::post('/deposits_service', [Deposit::class, 'store']);
Route::delete('/deposits_service', [Deposit::class, 'updateAll']);
the problem now is that the first request run ok but the second not running
would you please help me with this ?

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

populating dropdown based in first selection

My COntroller
public function gettestRecieve() {
$test = array('recieve' => $this->input->post('recieve'));
$data = $this->test->getrecieve($test);
echo json_encode($data);
}
My Model
function getAcademic($test) {
$this->db->select('a_y');
$this->db->where($test);
$this->db->distinct();
$result = $this->db->get('table');
$return = array();
if($result->num_rows() > 0){
$return[''] = 'select';
foreach($result->result_array() as $row){
$return[$row['a_y']] = $row['a_y'];
}
}
return $return;
}
My view
$(document).ready(function () {
$('#test').change(function () {
var add = $(this).val();
//console.log(add);
$.ajax({
url: "<?php echo base_url();?>getAcademic",
method: "POST",
data: {testing: add},
success: function(add) {
var data = JSON.parse(add);//parse response to convert into onject
console.log(data);//see your result in console
//alert(data[0].Ayear);
$('#good').html('<option value="'+ Ayear +'" >'+ Ayear +'</option>');
}
})
});
});
this gives me an error object HTMLSelectElement what does it mean, when i tried to look at my console it gives me a right value {"": "A & Y", 2014-2015: "2014-2015"} but in frontend gives an error, how could i fix this! can someone know this error, thanks and advanced

Symfony2 handle jQuery serialized Form and extra data sent with ajax post

I'm trying to handle the form and some extra data sent with ajax.
Here is my ajax post code :
$(document).on('submit', '#edit-entreprise', function (e) {
e.preventDefault();
var $entreprise = $("#liste-entreprises").val();
var $url = Routing.generate('load_edit_entreprise_form');
var $formSerialize = $('#edit-entreprise').serialize() + "&entreprise=" + $entreprise;
$(".panel-entreprise").empty().append('<div class="progress"> <div class="indeterminate"></div> </div>');
$.ajax({
url: $url,
type: 'POST',
data: $formSerialize,
success: function(html) {
console.log(html);
}
});
});
And here, my controler :
public function editAction(Request $request)
{
$entreprise = $request->request->get('entreprise');
$entreprise = $this->getDoctrine()
->getRepository('AvisClientsBundle:Entreprise')
->find($entreprise);
$editForm = $this->createForm('AvisClientsBundle\Form\EntrepriseType', $entreprise);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entreprise);
$em->flush();
return new Response(json_encode(array('status' => 'success')));
}
return new Response(json_encode($this->render('AvisClientsBundle:Admin/Entreprise:edit.html.twig', array(
'entreprise' => $entreprise,
'edit_form' => $editForm->createView(),
))->getContent()));
}
I don't know how to receive the form and the extra data :(
Can you explain me how to do this ?
Thanks !
I do it like this :
Ajax (I use FormData ):
$('#formId').submit(function (event) {
// Eviter le comportement par défaut (soumettre le formulaire)
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: $this.attr('method'),
data: new FormData($this[0]),
processData: false,
contentType: false,
error: function (request, status, error) {
callback(request.responseText);
},
complete: function () {
//
},
statusCode: {
//traitement en cas de succès
200: function (response) {
var message = response.message;
callback(response, event);
},
412: function (response, event) {
callback(response);
}
}
});
});
In sf2 here is the handler:
public function updateAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('testBundle:testEntity')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find entity.');
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
//envoi des données JSON en front
$response = new JsonResponse();
$response->setStatusCode(200);
//ajout de données éventuelles
$response->setData(array(
'message' => "Ligne buffer updated",
'form' => json_encode($this->getHtmlForm($entity))));
return $response;
} else {
//form non valide
//envoi des données d'erreurs JSON en front
$response = new JsonResponse();
$response->setStatusCode(412);
$response->setData(array(
'form' => json_encode($this->getHtmlForm($entity)),
'message' => $editForm->getErrorsAsString(),
));
return $response;
}
}

Resources