Handling AJAX return values in SweetAlert2 - ajax

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.

Related

Detect successful response from ajax function

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',
})

Rails: Stripe accept payment workflow

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.

Django: Ajas and Reverse error: "str" object is not callable

I have some code that will return to an ajax call a reverse-url that is defined in my urls.py I have the user update a page and then they click submit. When they click submit they should return to the item list view instead of the item update view.
Views.py
This returns the same page successfully, but it isn't what I want.
return JsonResponse({"status": "success",
"message": message})
This produces an error message "next_url": reverse("item:list"), TypeError: 'str' object is not callable
return JsonResponse({"status": "success",
"next_url": reverse("item:list"),
"message": message})
HTML page
Here is the template's ajax used to route the user:
$.ajax({
url: '/item/ajax/approve/',
data: {
'reply': reply,
'item': item,
'user_type': userType,
},
type: "POST",
dataType: 'json',
success: function (data) {
var successMsg = data.message
if (data.status){
successMsg = successMsg + "<br/><br/><i class='fa fa-spin fa-spinner'></i> Redirecting..." //<i class> - 'font awesome'
}
if (data.next_url){
if ($.alert){ // if alert message is installed
$.alert(successMsg)
} else {
alert("")
}
redirectToNext(data.next_url, 1500)
} else {
location.reload();
}
}
});
You need to import reverse function in the beginning of your file.
from django.urls import reverse

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));

Displaying a message in a dialog box using AJAX, jQuery, and CakePHP

I have a form, and when users submit this form, it should pass the data along to a function using AJAX. Then, the result of that is displayed to the user in a dialog box. I'm using CakePHP (1.3) and jQuery to try and accomplish this but I feel like I'm running into the ground.
The form will eventually be used for uploading images with tags, but for now I just want to see a message pop up in the box..
The form:
<?php
echo $this->Form->create('Image', array('type' => 'file', 'controller' => 'images',
'action' => 'upload', 'method' => 'post'));
echo $this->Form->input('Wallpaper', array('type' => 'file'));
echo $this->Form->input('Tags');
echo $this->Form->end('Upload!');
?>
The AJAX:
$(document).ready(function() {
$("#ImageUploadForm").submit(function() {
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
$("#dialog-modal").dialog({
$("#dialog-modal").append("<p>"+html+"</p>");
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
})
}
});
return false;
});
});
NOTE: if I put $("#dialog-modal").dialog({ height: 140, modal: true }); OUTSIDE of the $.ajax but inside the $("#ImageUploadForm").submit(function() { and comment out the $.ajax stuff, I WILL see a dialog box pop up and then I have to click it for it to go away. After this, it will not forward to the location /images/upload/
The method that AJAX calls:
public function upload()
{
$this->autoRender = false;
if ($this->RequestHandler->isAjax())
{
echo 'Hi!';
exit();
}
}
$this->RequestHandler->isAjax() seems to do either absolutely nothing, or it is always returning false. I have never entered an if statement with that as the condition.
Thanks for all the help, if you need more information let me know.
Try this:
$(document).ready(function(){
$.ajax({
type: "POST", url: "/images/upload/",
data: $(this).serialize(),
async: false,
success: function(html){
//First you must append to div:
$("#dialog-modal").append("<p>"+html+"</p>");
$("#dialog-modal").dialog({
height: 140,
modal: true,
buttons: {
Ok: function() {
$(this).dialog('close');
}
}
}); //dialog
}//success
});//ajax
Note the first sentence:
$("#dialog-modal").append("<p>"+html+"</p>");
it can not be a propertie. You must pass an object as a parameter to dialog() function so properties or member of an object looks like:
{
height:140,
buttons:{},
anotherPropertie: 'value'
}
If you call to dialog() function after ajax(), the dialog will be empty because will execute before success() function declared inside ajax().

Resources