Problem closing Sweet Alert Library which has a timer - ajax

Am working on an application build using Laravel. I have a payment page which is designed in a way when the user clicks on payment button, I trigger sweet alert Library with a message that the user should check his phone. The sweet alert popup also has a countdown timer for 60 seconds that works fine.
When the timer is counting, I am pushing the payload to the backend via AJAX whereby I consume the payment gateway API (which initiates STK push to the phone of the user with payment details).
When the payment is successful, I need to close the sweet alert popup box and redirect to another page which am unable to do. Kindly assist?
<script>
//When payment button is clicked
$("#payment").submit(function( event ) {
event.preventDefault();
//Initiate sweet alert library with a countdown timer of 60 seconds
var timer = 60,
isTimerStarted = false;
(function customSwal() {
swal({
title: "Message Sent",
text: "Please Check your Phone..." + timer,
timer: !isTimerStarted ? timer * 1000 : undefined,
showConfirmButton: false,
closeOnClickOutside: false,
showCancelButton: false,
});
isTimerStarted = true;
if(timer) {
timer--;
setTimeout(customSwal, 1000);
}
})();
//END sweet alert
//Fetch data from form
var token = $('#token').val();
var phone = $("#phone").val();
var email = $("#email").val();
var plan = $("#plan").val();
var amt = $("#amount").val();
var type ={
'token': token,
'phone' : phone,
'email' : email,
'plan' : plan,
'amt' : amt
};
// console.log(type);
$.ajax({
type: "POST",
url: "payment",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
//On success
if(response == 'suc'){
//Add code to remove the sweet alert popup
//Page to redirect to
window.location.href="success" ;
}
},
//Alert errors from backend
error: function(data) {
//console.log(data);
}
});
});
//END submission
</script>

Related

Controller method call using ajax

I am using codeigniter framework. I am trying to call controller method using AJAX function call on dropdown change event. My code is:
$(document).ready(function() {
$("body").on('change', '#assettype_id', function(e) {
var categoryval = $('#assettype_id :selected').val();
// assettype_id is dropdown id. On change event of
// dropdown, controller method will be called
myurl = 'http://mylocalsite/index.php/controllername/controllermethod/' + $.now();
alert("category id = " + categoryval); // for testing
$.ajax({
cache: false,
type: 'POST',
data: {
id: categoryval
},
url: myurl,
dataType: 'html',
success: function(data1) {
alert("inside ajax call"); // for testing
$('#result').html("");
// result is a div tag used to display result//
$("#result").html(data1);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error');
},
complete: function(xhr, status) {
alert("The request is complete!");
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This code is working perfectly for initial 2 or 3 change events of dropdown and getting new output but after 2 or 3 selection from dropdown, won't get new result like AJAX method is not working.
I have put 2 alerts for checking. alert with message 'category id =' is calling on every change event of dropdown but alert with message "inside ajax call" is not showing after 2 or 3 selections of dropdown even not going to error section of AJAX call.
I would like to know what is going wrong here? Thank you for you help.

How to get latest records without page refresh using Codeigniter and Websocket

Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});

How to open a modal in Drupal 8 without using a link?

The modal isn't triggered by a link on the page which the user has clicked. The modal is triggered when the user arrives on the url.
Think of something like a disclaimer that pops up as soon as the user arrives on the url.
You can use the Drupal.dialog function for this.
For example:
var $myDialog = $('<div>My dialog text</div>').appendTo('body');
Drupal.dialog($myDialog, {
title: 'A title',
buttons: [{
text: 'Close',
click: function() {
$(this).dialog('close');
}
}]
}).showModal();
See node.preview.js for another example.
Update: To use this with an AJAX request/response:
Drupal.ajax({
url: 'some/path',
success: function(response) {
var $myDialog = $('<div>' + response.data + '</div>').appendTo('body');
Drupal.dialog($myDialog, {title: 'Some title'}).showModal();
}
}).execute();

Google Analytics Send Event on Ajax Success Not Working

I have a Process Transaction Knockout method that returns a transaction status and depending on that status I want analytics.js event to be sent. I've used analytics-debug.js and in the console it says "Send finished" but the event never shows up in Google Analytics.
The send event works if it is before or after the ajax request but not if it is in the success or done callbacks.
$.ajax({
url: '/ProcessTransaction',
type: 'post',
data: 'data',
contentType: 'application/json',
success: function (result) {
if (result.StatusCode == 1 || result.StatusCode == 4) {
var subtotal = 7.95;
var enrollmentFee = 25;
var total = subtotal + enrollmentFee;
ga('ec:addProduct', {
'id': 'P12345',
'name': 'Test Product 1',
'category': 'Products',
'brand': 'Brand',
'price': subtotal,
'quantity': 1
});
ga('ec:setAction', 'purchase', {
'id': 'T12345',
'affiliation': 'TestSite',
'revenue': total,
'tax': enrollmentFee,
});
ga('send', 'event', 'Review', 'transaction', 'approved', total);
$('#submitpaymentbtn').data('loading-text', 'Approved!').button('loading');
window.location.href = '#Url.Action("Confirmation", new { ParticipantId = Participant.ParticipantId })';
}
else {
$('#modal-error').modal();
}
}
});
Send event does not allow decimal for event value. Math.round(total) fixes the issue. Even thought the analytics debug says event sent, it is never accepted or logged because the value must be an integer.
ga('send', 'event', 'Review', 'transaction', 'approved', Math.round(total));

Extjs- Paging Toolbar Next Page and Previous Page Disable

I have three parameters startdate, enddate and name which I have to send to the server to get back Json response. I am displaying the response in a GridPanel.
My Ajax Request looks like this:
FilterOperSet: function(button){
var win = button.up('window');
var form = win.down('form');
var start = form.getForm().findField('startDate').getSubmitValue();
var end = form.getForm().findField('endDate').getSubmitValue();
var act = form.getForm().findField('actor').getSubmitValue();
Ext.Ajax.request({
url: 'ListData',
params: { type: 'recordedRequest', startDate: start,
endDate: end, actor: act, start:0,limit:10 },
success: function(response) {
var json = Ext.decode(response.responseText);
var mystore = Ext.data.StoreManager.lookup('RecordedRequestStore');
mystore.loadData(json.recordedRequests);
},
scope: this});
}
I have a button, when user enters values for startdate, enddate and name and clicks on the button the above listener sends them as parameters along with start and limit for paging and response is captured and stored in gridpanel.
My issue with paging toolbar is: I could see the following as response
recordedRequests
// has some meta data here
success
true
total
1339
But my paging tool bar show only one page and at bottom says 0 of 0 and to the right nothing to display. Infact it should say 1 of 14 and should allow me to go through next pages.
2) Also when I click on refresh button it calls my store and calls server, but i want to make a ajax request with startdate, enddate and name as parameters(which would be exactly what my button above listerner does)
My Store looks like this:
autoLoad: false,
remoteFilter: true,
buffered: false,
pageSize: 10,
//leadingBufferZone: 1000,
fields:['start', 'end', 'actor','serviceOp'],
proxy: {
type: 'ajax',
url: 'ListData',
store: 'RecordedRequestStore',
startParam:'start',
limitParam:'limit',
pageParam:'page',
reader: {
type: 'json',
root: 'recordedRequests',
successProperty: 'success',
totalProperty: 'total'
},
extraParams: {
'type': 'recordedRequest',
},
//sends single sort as multi parameter
simpleSortMode: true,
// Parameter name to send filtering information in
filterParam: 'query',
// The PHP script just use query=<whatever>
encodeFilters: function(filters) {
return filters[0].value;
}
},
listeners: {
filterchange: function(store, filters, options){
console.log( filters )
},
totalcountchange: function() {
console.log('update count: ')
//this.down('#status').update({count: store.getTotalCount()});
}
}
Any sort of help will of great value for me. Thanks in Advance.
Instead of Ajax Request. I should use
store.load(params{your params})
For nextpage and previouspage I used beforeload listener for custom parameters.

Resources