How to apply diffForHumans() in laravel using ajax? - ajax

I'm working with laravel and native ajax. I am wondering where do I put diffForhHumans() when using ajax. In my Controller. I just return the object fetch.
Here's my Controller
public function getDownlines($id) {
$upline = Upline::find($id);
return $upline->downlines;
}
Model
public function downlines() {
return $this->hasMany('App\Downline');
}
HTML Code in View
<div id="downlines">
<div class="downlines-title-container">
<p class="title"></p>
</div>
<div id="downlines-holder">
<div class="p_parent_header">
<p>ID</p>
<p>Account Code</p>
<p>Created By</p>
<p>Created At</p>
</div>
</div>
</div>
Script in Ajax
var downlines = document.getElementById('downlines'),
downlines_holder = document.getElementById('downlines-holder');
function getPromise(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if(xhr.status == 200) {
resolve(xhr.response);
} else {
reject(Error(xhr.statusText))
}
}
xhr.onerror = function() {
reject(Error('Network Error'));
};
xhr.send();
})
}
function getDownlines(e, id) {
getPromise('upline/getdownlines/' + id).then(function(response) {
var resp = JSON.parse(response),
p_parent = document.getElementsByClassName('p_parent'),
p = p_parent.length;
while(p--) p_parent[p].remove();
if(resp.length > 0) {
downlines.style.display = 'initial'
downlines.children[0].children[0].innerHTML = e.innerHTML;
for(var i = 0; i < resp.length; i++) {
var p_parent = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p'),
p3 = document.createElement('p'),
p4 = document.createElement('p');
p_parent.classList.add('p_parent');
p1.innerHTML = resp[i].id;
p2.innerHTML = resp[i].account_code;
p3.innerHTML = resp[i].created_by;
p4.innerHTML = resp[i].updated_at;
p_parent.appendChild(p1);
p_parent.appendChild(p2);
p_parent.appendChild(p3);
p_parent.appendChild(p4);
downlines_holder.appendChild(p_parent);
}
} else {
downlines.style.display = 'none'
}
}, function(error) {
console.log(error);
})
}
I'm searching for the same problem and doesn't find one.
Any help would be appreciated. Thanks!!!

Please do this before returning the downlines
public function getDownlines($id)
{
$upline = Upline::find($id);
return $upline->downlines->map(function($downline) {
return [
'id' => $downline->id,
'account_code' => $downline->account_code,
'created_by' => $downline->created_by,
'created_at' => $downline->created_at->diffForHumans(),
'updated_at' => $downline->updated_at->diffForHumans(),
];
});
}
I am unsure if you want to use created_at or updated_at, because in the html you have written <p>Created At</p> but in the AJAX request, you have written p4.innerHTML = resp[i].updated_at;. So I added both in the return array :)

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 ?

On vue how to make a Edit function

Im doing my first CRUD with Vue - Laravel, i did a Add function that works fine but my Edit button is doing another Add function.
(I get the alert from updateDespesa alert("Usuário Alterado!");)
My Frontend:
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
des: this.despesa.des,
valr: this.despesa.valr,
vencc: this.despesa.vencc,
stt: this.despesa.stt,
emiss: this.despesa.emiss,
})
.then((response) => {
this.despesa.id = "";
this.despesa.valr = "";
this.despesa.stt = "";
this.despesa.vencc = "";
this.despesa.emiss = "";
this.getDespesa();
if(despesa){
alert("Usuário Alterado!");
}
})
.catch((err) => {
console.log(err);
});
},
My Backend:
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
In your backend, try update this and see
public function update(Request $request, $id) {
if ($id == 0) {
$despesa = new Despesa;
$despesa->create($request->all());
}
else {
$despesa = Despesa::findOrFail($id);
$despesa->fill($request->all())->save();
}
//$despesa->update($request->all());
return response()->json('Sucess');
}
and also please check the Despesa Model has declared the input fields in protected $fillable
async updateDespesa(despesa) {
const response = await axios
.put("api/despesas/" + despesa, {
...
})
.then((response) => {
// add this line, to check only alert when id is not null
// so that it only alert when update
if(despesa){
alert("Usuário Alterado!");
}
....
})
.catch((err) => {
console.log(err);
});
},

AJAX POST request not working with XMLHttpRequest in Laravel

I'm using XMLHttpRequest to avoid using JQuery and I wanna make an Ajax request to delete an object but I keep getting redirected back and getting FOUND (302) HTTP errors.
This is my code:
function deleteGuia(urlToSend) {
var borra = confirm('¿Está seguro de borrar la guía?');
if (!borra) {
return;
}
var req = new XMLHttpRequest();
var csrfToken = document.querySelector('meta[name="csrf-token"]').content;
req.open("POST", urlToSend, true);
req.setRequestHeader('X-CSRF-TOKEN', csrfToken);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
req.onreadystatechange = function () {
if (req.readyState === 4) {
if (this.readyState === this.DONE) {
console.log(this.responseURL);
}
if (req.status != 200) {
var msg = JSON.parse(req.response);
alert(msg.error);
} else {
alert('Exitoso');
}
}
}
var data = new FormData();
var guia = "{{$guia ?? ''}}";
var estado = "{{$tipo ?? ''}}";
data.append("guia", guia);
data.append("tipo", estado);
req.send(data);
}
</script>
This one's the controller function:
public function eliminarGuia(Request $request) {
$request->validate([
'guia' => 'required|numeric',
'tipo' => 'required'
]);
$guia = (int)$request->input('guia');
$tipo = $request->input('tipo');
\Log::info('Guia' . $guia . ' Tipo: '. $tipo);
if (strtoupper($tipo) === 'ENTREGA'){
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$borra_ciclos = Device::where('guia_recepcion', $guia)->delete();
if(!$borra_guia) {
return response(400)->json(['error', 'La guía no se encontró.']);
}
} else if (strtoupper($tipo) === 'REVERSA') {
$borra_guia = Guia::where('guia', $guia)->where('estado', $tipo)->delete();
$devices = Device::where('guia_reversa', $guia)->get();
if (!$borra_guia){
return response(400)->json(['error', 'La guía no se encontró.']);
}
foreach($devices as $device)
{
if (!$device->fecha_recepcion) {
$device->delete();
} else {
$device->guia_reversa = 0;
$device->fecha_reversa = null;
$device->save();
}
}
} else {
return response(400)->json(['error', 'La guía no se encontró.']);
}
return response(200);
}
web.php
Route::post('borrar_guia', 'VistasController#eliminarGuia')->name('borrar_guia');
There's no redirection at all. Why might that be happening? I don't know what else to add. The controller should return a 200 code when it delets an existing object in the database but it's getting a 200 from the redirection.

Ajax with laravel Post returning

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
Update your ajax header, according to this:
$.ajaxSetup({
headers: {
accepts: "application/json; charset=utf-8",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The possibilities of this issue is CSRF token and missing route.

How to change error 302 in laravel with ajax

I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});

Resources