Change status with ajax in laravel - javascript

I'm using Laravel in my project. I have a voucher that maintains a status.
I've used AJAX for changing the status and the AJAX code works successfully.
However the status did not change in my view until after I refresh the page. I'm looking for a way to solve this issue.
<button class="btn btn-link p-0 change" type="submit" data-id="{{ $voucher->id }}">
#if ($voucher->status == 1)
<i class="fa fa-toggle-on text-success"></i>
#else
<i class="fa fa-toggle-off text-muted"></i>
#endif
</button>
#if ($voucher->status == 1)
<span class="badge badge-soft-success">
enable
</span>
#else
<span class="badge badge-soft-pink">
disbale
</span>
#endif
$(".change").click(function() {
var id = $(this).data("id");
$.ajax({
url: "vouchers/change-status/" + id,
type: 'put',
dataType: "JSON",
data: {
"id": id,
"_method": 'put',
"_token": "{{ csrf_token() }}",
},
success: function() {
console.log("it Work");
// $("tr#"+id).remove();
}
});
console.log("It failed");
});

You can try this way:
Blade
Wrap your code in some holder with class status-enabled, when status is 1. Set special classes for elements which will be visible or not according status.
<div class="holder #if($voucher->status == 1) status-enabled #endif">
<button class="btn btn-link p-0 change" type="submit" data-id="{{ $voucher->id }}">
<i class="fa fa-toggle-on text-success enabled-visible"></i>
<i class="fa fa-toggle-off text-muted enabled-invisible"></i>
</button>
<span class="badge badge-soft-success enabled-visible">
enable
</span>
<span class="badge badge-soft-pink enabled-invisible">
disbale
</span>
</div>
CSS
Set rules:
.holder .enabled-visible {
display: none;
}
.holder .enabled-invisible {
display: inline-block;
}
.holder.status-enabled .enabled-visible {
display: inline-block;
}
.holder.status-enabled .enabled-invisible {
display: none;
}
JS
Toggle holder class when you have successfuly change status.
$(".change").click(function() {
var id = $(this).data("id");
$.ajax({
url: "vouchers/change-status/" + id,
type: 'put',
dataType: "JSON",
data: {
"id": id,
"_method": 'put',
"_token": "{{ csrf_token() }}",
},
success: function() {
$(this).closest('.holder').toggleClass('status-enabled');
}
});
console.log("It failed");
});

Just in your success function:
success: function() {
console.log("it Work");
$("i.fa-toggle-on).hide();
$("i.fa-toggle-off).show();
}

Html Tag no need of if condition php blade.
<button class="btn btn-link p-0 change" type="submit" data-id="{{ $voucher->id }}">
#if ($voucher->status == 1)
<i class="fa fa-toggle-on text-success"></i>
#else
<i class="fa fa-toggle-off text-muted"></i>
#endif
</button>
<div id="alert-message"></div> // add this line
#endrole
change this code into your code.
script file
$(".change").click(function() {
var id = $(this).data("id");
var success = '<span class="badge badge-soft-success">' +
'enable' +
'</span>';
var failed = '<span class="badge badge-soft-pink">' +
'disbale' +
'</span>';
$.ajax({
url: "vouchers/change-status/" + id,
type: 'put',
dataType: "JSON",
data: {
"id": id,
"_method": 'put',
"_token": "{{ csrf_token() }}",
},
success: function() {
console.log("it Work");
$('#alert-message').html(success);
// $("tr#"+id).remove();
}
});
$('#alert-message').html(failed);
});

Related

Send input type file without using submit button

I have the form to attach the document and the js to send the data to php as follows:
function update_estado()
{
var dadosajax = {
'Fornecedor' : $("#Fornecedor3").val(),
'arquivo': $("#arquivo").val(),
}
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" class="limp9" id="forarq" method="post" enctype="multipart/form-data">
<div class="form-group col-md-3">
<select class="form-control1 spoiler4" name="Fornecedor" id="Fornecedor3" required>
<option value="xxxxxx#hotmail.com">xxxxxx#hotmail.com</option> </select>
<label class="label1" for="Fornecedor3">Email Fornecedor</label>
</div>
<div class="row clearfix" style="margin-top: -1%;">
<span class="btn fileinput-button" style="color: black;">
<i class="glyphicon glyphicon-plus" style="color: black;"></i>
<span style="color: black;">Add Arquivo...</span>
<input type="file" class="form-control" style="height: 62%;" id="arquivo" name="arquivo">
</span>
</div>
<div class="h4 mb-4" style="float:right; line-height: 2;">
<button type="button" class="btn btn-raised btn-default ripple-effect" onclick="update_estado()">Gravar <i class="fa fa-paper-plane"></i></button>
</div>
</form>
The variable with the email sends, but the input type file variable is empty.
I want to send both variables without submitting by clicking the save button.
you can do this
function update_estado()
{
// here is my code
var pedpront = [];
$.each($("input[name='updorc1[]']:checked"), function(){ pedpront.push($(this).val()); });
let formData = new FormData(document.querySelector("#forarq"))})
// get the values here and insert in key value pair down below
formData.append("pedprontData",pedpront)
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data:,formData
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
You can use this function and keep in mind that reader.result is file content string
base64encoded which means you need to decode it on server-side to get original content and save it.
function update_estado()
{
var file = $('#arquivo')[0].files[0];
var filename = file.name;
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload=function() {
var dadosajax = {
'Fornecedor' : $("#Fornecedor3").val(),
'arquivo': reader.result,
}
$.ajax({
url: 'pedencom.php',
type: 'POST',
cache: false,
data: dadosajax,
error: function(){
$(".error_message").removeClass('hide');
swal("Erro!", "Tente novamente. Caso persista o erro, contatar Administrador!", "error");
},
success: function(result2)
{
$('.limp9')[0].reset();
}
});
}
}

AJAX POST not actually sending POST data with Django

I want to submit a form to my Django back end using an AJAX post. I have multiple forms on the page but only want the one the user submits to be the one that sends.
The form is held in a modal:
<div class="modal-body">
<div class='content-section'>
<form method="POST" id="form{{ prod.id }}" class="showform" value="{{ prod.id }}" >
<input type="hidden" value="{{ prod.id }}" name="prodid">
{% csrf_token %}
<fieldset class='form-group'>
{{ form|crispy}}
</fieldset>
</form>
</div>
</div>
<div class="modal-footer">
<div class='form-group'>
<button class="btn btn-outline-info submit-form" value={{prod.id}} form="form{{ prod.id }}"
>Save
To Profile</button>
</div>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
When the submit button is pressed, it triggers the following AJAX :
$(document).on('click', '.submit-form', function () {
var thisButton = $(this)[0]
var prodID = $(this).val();
var form = $("form" + prodID);
$.ajax({
type: 'post',
headers:{
"X-CSRFToken": '{{ csrf_token }}'
},
url: '/ajax/validate_showadd/',
dataType: 'json',
contentType: 'json',
data: {
'form': form.serialize(),
"prodID":prodID,
},
success: function (data) {
console.log("sent")
},
error: function(data) {
console.log("error")
}
});
return false;
});
However, within Django whenever I try access any of these values it just returns 'None' and the QueryDict for the POST request is empty.
Thank you

Intermittent 405 Status response from ajax delete request

So I've got these cards, a user can click the delete button to remove a card. The card has an ID which deletes the card ID or community_id and user_id from the table. When the clicks the delete button, it sends an ajax delete request to the resource controller (delete method) which does delete the row from the database... sometimes.
It's very strange, sometimes it works, other times it returns a 405 (Method Not Allowed Exception).
Here's the code:
View:
#foreach($communities as $community)
<div class="col-md-3">
<div class="card communityCard">
<div class="loadingCard" loading>
<i class="loadingSpinner fas fa-circle-notch fa-spin"></i>
</div>
<div class="commandPanel">
<div class="commandPanelInterior">
#if($community->banned == 1)
#php($community->description = "This community has been removed for violating our terms of service.")
#else
<form class="form" action="/cad" method="GET">
#csrf
<input name="community_id" type="hidden" value="{{$community->id}}">
<button type="submit" class="sideMenuButton hvr-grow btn-primary"><i class="fas fa-door-open"></i></button>
</form>
#endif
#if($community->owner_id != Auth::user()->id)
<button id="deleteCommunity{{$community->id}}" value="{{$community->id}}" type="submit" class="deleteCommunityButton sideMenuButton hvr-grow btn-danger"><i class="fas fa-trash"></i></button>
#endif
</div>
</div>
<div class="card-header">
<img class="communityIcon" src="/images/communityIcons/{{$community->icon_path}}">
<span class="communityName">{{$community->name}}</span>
</div>
<div class="card-body">
<span class="communityDescription">{{$community->description}}</span>
</div>
#if($community->banned == 0)
<div class="card-footer">
<span class="badge badge-light"><i class="fas fa-users"></i> {{$community->user_count}}</span>
#php($communityBadges = $community->badge_types)
#foreach($communityBadges as $badgeType)
<span class="badge badge-primary" title="{{$badgeType->name}}">{!!$badgeType->badge_icon!!}</span>
#endforeach
</div>
#endif
</div>
</div>
#endforeach
Javascript:
// Remove User From Community Ajax
$('.deleteCommunityButton').click(function(event){
var clickedBtn = "#" + (event.target.id);
var community_id = $(event.target).val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
cache: false,
url: '/communitymembers/'+community_id,
data: {
"id": community_id,
"_method": 'DELETE'
},
success: function(response) {
$(clickedBtn).parent().parent().parent().parent().remove();
}
});
});
Controller:
public function destroy($id)
{
$memberList = CommunityMemberList::where('user_id', Auth::user()->id)->where('community_id', $id)->first();
$memberList->delete();
return redirect('/home')->with('message', 'The community has been successfully removed from your account');;
}
Web.php File:
Route::get('/home', 'HomeController#index')->name('home');
Error (From Console):
"message": "The DELETE method is not supported for this route. Supported methods: GET, HEAD, POST.",
Thanks :)

Ajax bind click to another element

I have a button (is anchor tag with class vote) which should be clicked to vote for an article via ajax request. After that I want to update the votes count in my blade view (its a laravel application). The div with the class points should be updated but I dont know how to bind points on click to the ajax call?
I want to bind the .point to ajax call like I did it with $button to then update the div with the class points.
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}"></a>
Main code:
<div data-id="{{ $article->id }}" class="points">{{ $article->votes->count() }}</div>
$(document).on('click','.vote',function(){
var $counter = $(this).next();
var $button = $(this);
var id = $button.data('id');
var token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type:'POST',
url:"{!! URL::to('article/vote/') !!}/" + id,
dataType: 'JSON',
data: {
"_method": 'POST',
"_token": token,
"id": id,
},
success:function(data){
$counter.html(data.count);
var color = data.voted ? '#bbb' : '#38c172';
$button.css('background-color', color);
console.log('success');
console.log(data);
},
error:function(xhr){
if (xhr.status == 401) {
window.location.href = "{!! URL::to('login') !!}";
} else if (xhr.status == 403) {
window.location.href = "{!! URL::to('email/verify') !!}";
}
},
});
});
So you want your .points to be updated and not the a button you clicked.
First, make sure your a and .points are children of the same div element and there like:
<div>
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}">
button
</a>
<div data-id="{{ $article->id }}" class="points">
{{ $article->votes->count() }}
</div>
</div>
...
<div>
<a data-id="{{ $article->id }}" class="btn vote {{ Auth::check() && Auth::user()->votedFor($article) ? 'btn-success' : '' }}">
button
</a>
<div data-id="{{ $article->id }}" class="points">
{{ $article->votes->count() }}
</div>
</div>
Then in your JavaScript define the counter element like
var $counter = $(this).parent().find('points');
and update your success: method to apply CSS class and put data count:
$counter.html(data.count);
var color = data.voted ? '#bbb' : '#38c172';
$counter.css('background-color', color);
Let me know if it makes sense and you can finish the implementation.

Confirm delete box for dynamic jQuery delete row

I have this jQuery function for delete row data from MySQL using Ajax. This worked with jQuery confirm, BUT I need to add Bootstrap 3 modal box confirm(YES/NO) before delete row.
function deleteBox(id){
if (confirm("Are you sure you want to delete this record?"))
{
var dataString = 'id='+ id;
$("#flash_"+id).show();
$("#flash_"+id).fadeIn(1000).html('<img src="../img/select2-spinner.gif"/>');
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(result){
if(result){
$("#flash_"+id).hide();
// if data delete successfully
if(result=='success'){
//Check random no, for animated type of effect
// Delete with slide up effect
$("#list_"+id).slideUp(600);
}else{
var errorMessage=result.substring(position+2);
alert(errorMessage);
}
}
}
});
}
}
HTML :
<div class="box-body">
<ul class="todo-list ui-sortable">
<li class="list" id="list_3"> <span class="handle"><i class="fa icon-ellipsis-vertical icon-large"></i> <i class="fa icon-ellipsis-vertical icon-large"></i></span>
<span class="tools"><i alt="Delete" title="Delete" class="icon-remove-sign icon-large" onclick=deleteBox("3")></i>delete</span>
title/sedcription <span class="flash" id="flash_3"></span>
<small class="label label-success pull-right"><i class="icon-time"></i>date</small>
</li>
<li class="list" id="list_5"> <span class="handle"><i class="fa icon-ellipsis-vertical icon-large"></i> <i class="fa icon-ellipsis-vertical icon-large"></i></span>
<span class="tools"><i alt="Delete" title="Delete" class="icon-remove-sign icon-large" onclick=deleteBox("5")></i>delete</span>
title/sedcription <span class="flash" id="flash_5"></span>
<small class="label label-success pull-right"><i class="icon-time"></i>date</small>
</li>
</ul>
</div>
How do I add bootstrap 3 confirm modal box for this function?!
Demo fiddle

Categories