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));
Related
I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})
I am trying to integrate Stripe using the elements workflow.
Below are the steps that a user does
Select the plan
Enter card details and click 'Subscribe'
When the user clicks "Subscribe", in the backend I
create a subscription and return the clientSecret
call confirmCardPayment by using the clientSecret in step 1
on success of step 2, pass the paymentIntentId to backend to fetch the card details and save it in the user record.
Below is part of the code
$(document).on('click', '#payment-btn', (e) => {
event.preventDefault();
let name = document.querySelector('#name_on_card').value;
$.ajax({
url: '/subscriptions',
method: 'POST',
beforeSend: function(request){
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
data: {
plan_id: plan_id
}
}).then((res) => {
stripe.confirmCardPayment(res.clientSecret, {
payment_method: {
card: card,
billing_details: {
name: name
}
}
}).then((result) => {
if(result.error) {
alert(result.error.message);
} else {
$.ajax({
url: '/user',
method: 'PATCH',
dataType: "json",
beforeSend: function(request){
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
},
data: {
stripe_customer_payment_method_id: result.paymentIntent.payment_method
}
}).then((result) => {
Turbolinks.visit('/videos?message=success');
})
}
});
});
});
Would this be a good way to execute the payments workflow or is there a more efficient way, may be i am missing something.
Thanks.
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>
I use a SweetAlert2 Popup with an AJAX request. Once the user clicks on submit I execute the request.
In the PHP file I then make some validation on the submitted data and depending on the result I want to give a feedback in SweetAlert2 for the user as information.
Here is my SweetAlert2 Code:
$('#sweet-ajax').click(function () {
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning",
showCancelButton: true,
closeOnConfirm: false,
confirmButtonText: "Yes, submit!",
cancelButtonText: "Cancel",
showLoaderOnConfirm: true,
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger m-l-10',
preConfirm: function(givenData){
return new Promise(function(resolve, reject) {
setTimeout(function(){
//if statment only for test purposes filled with 2==1
if(2 == 1){
swal("Oops", "Sorry something strange happend!", "error")
}else{
resolve()
}
}, 2000)
})
},
allowOutsideClick: false
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
})
swal({
//only if the response from the AJAX is correct - but how?
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' //need to get the return value of the AJAX request and append it here
})
}, function(dismiss) {
if (dismiss === 'cancel') {
swal(
'Cancelled',
'The action have been cancelled by the user :-)',
'error'
)
}
})
});
And the checkTool.php file:
<?php
$registration = $_POST['registration'];
$ammountInput= $_POST['ammount'];
$email= $_POST['email'];
//only some demo things here. Implement it after the SweetAlert2 stuff works properly
if ($registration == "success"){
return response(json_encode(array("abc"=>'Success')));
}else{
return response(json_encode(array("abc"=>'Error')));
}
?>
How can I now determinate what is the response from the AJAX request in the Javascript Code of SweetAlert2?
Is it possible to handle the AJAX response in SweetAlert2?
Wrap your sweet alert inside the ajax .done(function(response){}) function
}).then(function(givenData){
$.ajax({
type: "post",
url: "/assets/php/checkTool.php",
data: {registration: "success", amount: ammountInput, email: "test#example.com"},
}).done(function(response) {
if(response['abc'] === 'Success') {
swal({
type: 'success',
title: 'Correct!',
html: 'All safe! Here is the answer from the tool: ' + response['answer']
})
}
});
})
}, function(dismiss) {
In my experience what made it work, keeping in mind the use of showLoaderOnConfirm: true is doing the ajax call inside the preconfirm, and getting from the json response the elements I need as follows:
swal({
title: "Sure?",
text: "Clicking on validated sends the data to our tool.",
type: "warning"
showLoaderOnConfirm: true,
preConfirm: function () {
return new Promise(function (resolve) {
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(objectToPost),
url: "/assets/php/checkTool.php",
dataType: 'json', // in ,my case the absence of this was the cause of failure
})
// in case of successfully understood ajax response
.done(function (myAjaxJsonResponse) {
console.log(myAjaxJsonResponse);
swal(
"My title!",
"My response element is: " + myAjaxJsonResponse.selectedElement,
"success"
);
})
.fail(function (erordata) {
console.log(erordata);
swal('cancelled!', 'The action have been cancelled by the user :-)', 'error');
})
})
},
})
.catch(swal.noop)
The swal being invoked when clicking a button, on my scenario.I hope this helps someone, as it took me quite some time to make it work.
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.