Delete dialog box with ajax - Symfony 3 - ajax

I have a basket where I can have items that I can delete
When I click on the bin icon, it delete it straight from the page with this script
$('.delete').on('click', function (e) {
e.preventDefault();
var value = $(this).attr('data-value');
$.ajax({
url: '{{ path('ajax_app_basket_bill_delete_item') }}',
type: 'POST',
dataType: 'json',
data: {
'itemId': value
},
success: function (data) {
$('#item' + value).remove();
if (data['success'] == 1) {
$.ajax({
url: '{{ path('ajax_app_basket_bill_refresh_price') }}',
type: 'POST',
dataType: 'json',
data: {
'credit_box' : creditBox,
'code' : code
},
success: function (data) {
$('#t1').text(data['totalWithoutTax']);
$('#t2').text(data['tax']);
$('#t3').text(data['total']);
}
});
}
}
});
});
(here is the html in case you need to see this)
<a class="delete" data-value="{{ item.id }}" href="#"><i class="mdi mdi-delete"></i></a>
And my question is, how can I actually create a very simple dialog box to confirm deletion when I click on the bin icon without to remove it instantly.
thank you

The simpliest way would be with the javascript function confirm:
$('.delete').on('click', function (e) {
e.preventDefault();
if (confirm('Really delete this item?')){
var value = $(this).attr('data-value');
$.ajax({
url: '{{ path('ajax_app_basket_bill_delete_item') }}',
type: 'POST',
dataType: 'json',
data: {
'itemId': value
},
success: function (data) {
$('#item' + value).remove();
if (data['success'] == 1) {
$.ajax({
url: '{{ path('ajax_app_basket_bill_refresh_price') }}',
type: 'POST',
dataType: 'json',
data: {
'credit_box' : creditBox,
'code' : code
},
success: function (data) {
$('#t1').text(data['totalWithoutTax']);
$('#t2').text(data['tax']);
$('#t3').text(data['total']);
}
});
}
}
});
}
});
You can get more fancy with jQueryUI's .dialog() or other additional dialog box scripts easily foundable via Google or else.

Related

Ajax success function not receiving data ASP.NET MVC

I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :
View:
<div id="dvform">
<!-- some data-->
<input type="submit" value="submit" id="btnsubmit" />
</div>
<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
addAppointment();
});
});
function addAppointment (){
$.ajax({
type: 'POST',
url: '/FuelerAppointments/Create',
contentType: 'application/json; charset=utf-8',
dataType: "html",
data: $("dvform").val(),
success: function (data) {
swal("Done!", "The appointment was saved successfully!", "success");
},
error: function (data) {
swal("Error deleting!", "Please try again", "error");
},
});
}
Controller :
[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}
First you should change dataType: "html", to dataType: "json",
and create FuelerAppointment object before the $.ajax():
var fuelerAppointment = {};
fuelerAppointment.Name = $("#Name").val();
and then the data in ajax method
data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',
For more information check this link Using AJAX In ASP.NET MVC
change dataType: "html" to dataType: "json"
and in data properties should you write like this
var model = {
prop1: prop1Value,
prop2: prop2Value,
...
};
data: {fuelerAppointment: model}
Or
data: JSON.stringify({
fuelerAppointment: {
prop1: prop1Value,
prop2: prop2Value,
...
}
})
Notes: the fuelerAppointment object should behave a sem proprieties in C# class

How to reload the part of table?

I have this table:
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data("id");
$.ajax(
{
url: "client/"+id,
type: 'delete',
dataType: "JSON",
data: {
"id": id
},
success: function (response)
{
$("#reload_table").load(window.location + " #reload_table");
}
});
});
Simply after delete first one test2 everything is good and reload the part of table, but when I go to delete test1 it does not delete it, I have to reload the whole page then delete it!
I'm use this for reload the table but it reload for just one time!:
$("#reload_table").load(window.location + " #reload_table");
How can I make it reload table ?
I'm not using any library like datatable etc, it just simple bootstrap table.
Alternative : Remove tr after ajax success
#forelse($users as $user)
//...
<tr id="{{ $user->id }}">...</tr>
//...
#empty
<p>No data Available</p>
#endforelse
//js
$(".deleteProduct").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var id = $(this).data("id");
$.ajax(
{
url: "client/"+id,
type: 'delete',
dataType: "JSON",
data: {
"id": id
},
success: function (response)
{
$('#'+id).remove();
}
});
});
Since you are binding the event to an element inside the table row, you should be able to simply delete the table row by finding the closest tr to that element:
$(this).closest('tr').remove();

Second ajax call return 404

My second ajax call starts only when the first succeeded. The problem, the second ajax call return 404 error code. Find below the code.
Can anyone help troubleshooting ? Thanks a lot
$.ajax({
contentType: 'application/json',
type: 'GET',
url: '${pageContext.request.contextPath}/transaction/status/'+$("#telephone").val()+'/'+$("#transref").val(),
dataType : 'json',
cache: false,
error: function(xhr,error,textStatus){
console.log(error);
},
success: function(data) {
console.log(data)
if(data.transfertResponseCode == '01'){
$('#statut').empty();$('#statut').append('<div class="row"><div class="col-md-2 col-sm-2"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span></div><div class="col-md-10 col-sm-10">Transaction en cours de traitement.... Veuillez patienter quelques instants</div></div>');
}else if(data.transfertResponseCode == '00'){
var data = {"msisdn":$("#telephone").val(), "amount":$("#montant").val(), "transref":$("#transref").val(), "clientid":$("#clientID").val()};
$.ajax({
contentType: 'application/json',
url: 'http://74.208.84.251:8221/QosicBridge/user/deposit',
type: 'POST',
data : JSON.stringify(data),
dataType : 'json',
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('USR28' + ":" + 'YG739G5XFVPYYV4ADJVW'));
},
error: function(xhr,error,textStatus){
console.log(error);
},
complete: function(data) {},
success: function (data) {
console.log(data);
}
});
}
}
});

Opencart cart.add() with option

I'm looking for solution in opencart.
Need to rebuild cart.add function for adding product with option value.
By default:
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('#cart > button').button('reset');
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
checkout/cart/add php side for option:
if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
} else {
$option = array();
}
Any solutions?
You can do this in the following way. Create a simple Javascript object.
var productData = {'product_id' : PRODUCT_IDS.CARD, 'quantity': 1,'option':{'229':"Some option value"}};
And send the request as follows. Converting the object to post params using the param function.
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $.param(productData),
dataType: 'json',
beforeSend: function () {
},
complete: function () {
},
success: function (json) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Also there are some other ways to do this, you can see possible payload formats in the /controller/checkout/cart.php file.

jquery ajax web method call

I am trying to call ajax web method when button is clicked. This is the following code I have written.
$(function() {
$("<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: '{rating: \'' + textrating.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {
},
error: function throwError(data) {
},
});
});
This is asp button I am using
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClick="btnBack_Click" />
The code behind is
[WebMethod]
[ScriptMethod]
public static void SubmitRatings(string rating)
{
if (HttpContext.Current.Request.QueryString["ID"] != null)
{
if (HttpContext.Current.Session["LoginId"] != null)
{
string str = HttpContext.Current.Request.Form["lblRate"];
RatingsBAL bal = new RatingsBAL();
bal.StoreRatings(HttpContext.Current.Session["LoginId"].ToString(), HttpContext.Current.Request.QueryString["ID"], Convert.ToInt32(rating));
}
}
}
But for some reason the web method is not being fired. Can anyone help me please? Thanks in advance.
Change $("<%=btnRatingSubmit.ClientID%>").click to
$('#'+"<%=btnRatingSubmit.ClientID%>").click
You were missing a #, which is used to select elements by their ids in jquery.
Full Code:
$(function () {
$('#' + "<%=btnRatingSubmit.ClientID%>").click(function (e) {
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
});
function Functioncall(){
var textrating = $('#<%= btnRatingSubmit.ClientID %>');
$.ajax({
type: 'POST',
url: 'NewRatings.aspx/SubmitRatings',
data: {
rating: textrating.val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function doNothing(data) {},
error: function throwError(data) {},
});
}
<asp:Button ID="btnBack" runat="server" Text="Back To Results" OnClientClick="Functioncall()" />

Resources