I have created a SweetAlert using the code below. After I used this, the result was shown BUT I am not pressing OK yet, already jumped to URL that I set.
This is a SweetAlert script I created (I save in my script when I want to use then I take it from because I'm using Laravel framework).
<script type="text/javascript">
function showSuccessSwal(message) {
Swal.fire(
'Success',
message,
"success"
);
}
function showErrorSwal(message) {
Swal.fire(
'Error',
message,
"error"
);
}
</script>
And this is a script I'm using:
<script type="text/javascript">
$('#somthing-form').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
}
});
});
</script>
I want the result to work like this:
I press a submit button.
Display a SweetAlert with an OK button.
Wait for the user to press the OK button then go to the URL I set (not straight jump to URL before I press OK button).
you need to call the swal before you call the ajax
swal({
title: 'Are you sure to go ahead?,
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, please!'
}).then(function(result) {
if (result.value) { // when you click `yes, please!`
$.ajax({
type: 'POST', // GET, POST, PUT
url: form.attr('action'),
data: form.serialize(),
success: function(result) {
showSuccessSwal(result.message);
window.location.href="{{ route('something.index') }}";
},
error: function(xhr) {
var errorString = '';
var errors = xhr.responseJSON.errors;
Object.keys(errors).forEach(function(key) {
var error_message = errors[key];
$.each(error_message, function(key, value) {
errorString += value + '\n';
});
});
showErrorSwal(errorString);
});
}
});
Related
Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
How do i get my code so that if the 401 error appears with my AJAX button click code, then it either throws an error message when the button is clicked and says "you need to log in" or it redirects the user to login? at the moment it just throws the error in the dev console so a user has no idea on why the button isnt working.
Ajax js:
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
You could try the statusCode part of jQuery AJAX.
$('.visit').on('click', function (event) {
event.preventDefault();
// Make the button a variable here
var buttonToChange = $(this);
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: $(event.target).data("id"),
_token: token
},
statusCode: {
401: function() {
alert( "Not authenticated" );
}
}
success: function(){
// Change the button here
if(buttonToChange.hasClass('btn-visited')){
buttonToChange.addClass('btn-not-visited');
buttonToChange.removeClass('btn-visited');
buttonToChange.html('Not Visited');
//Count will go down
}
else{
// Do the opposite
buttonToChange.addClass('btn-visited');
buttonToChange.removeClass('btn-not-visited');
buttonToChange.html('Visited');
//count will go up
}
},
});
simple example
you can test this code by inspect in browser:
welcome.blade.php :
<script>
var urlVisit="{{route('route_test')}}"
var token = "{{csrf_token()}}"
$.ajax({
method: 'POST',
url: urlVisit,
data: {
place_id: 1,
_token: token
},
success: function (response) {
alert('ok')
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 419)
{
alert(xhr.responseText) // text of error
// do something
}
else if(xhr.status == 401)
{
// do something
}
}
});
</script>
web.php (route) :
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
Route::post('test', function (Request $request) {
$place_id= $request->get('place_id');
return ('yes');
})->name('route_test');
I want to show a button "Reload Game" after function success instead of this bootstrapDialog box
I need this button to fit over my <div class="tilting"></div> Instead of showing somewhere else on page
You need to use below code inside the success method,
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
If you are using jQuery Ajax try it below way,
function loadDoc() {
$.ajax({
type: 'POST',
url: 'APUC',
data: 'productName=' + productName,
dataType: 'html',
cache: false,
success: function (result) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
},
});
}
If you are using pure Ajax, try it like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementsByClassName("tilting")[0].innerHTML="<button type="button">Reload Game</button>";
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
<%: Html.ActionLink("Print", "Print", "Print", New With {.id = Model.ID}, New With {.target = "_blank", .class = "print"})%>
How to return to my actionlink's functionality once preventDefault is called? ( the _blank page is not being opened on return)
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
//return;
return true;
} else {
//do nothing
console.log('false');
}
}
});
});
Solution:
$('#NameOfButton').bind('click', function (e) {
e.preventDefault(); // Stop click event
//Gather Data
var el= $(this);
var data = $(this).parents('form').first().serialize();
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
window.location.href = el.attr('href');
} else {
//do nothing
}
}
});
});
You can trigger the event again:
$('#NameOfButton').bind('click', function (e, skip) {
if (skip) return; // check param
e.preventDefault(); // Stop click event
//Gather Data
var data = $(this).parents('form').first().serialize();
var el = $(this);
//Check Data , if saved to DB continue Click functionality
$.ajax({
url: '<%:Url.Action("Get")%>',
cache: false,
type: 'POST',
data: data,
success: function (result) {
if (result.Success == true) {
console.log('true');
el.trigger('click', [true]); // trigger same event with additional param
} else {
//do nothing
console.log('false');
}
}
});
});
I have a jquery that makes an AJAX call by clicking a button, but I want them without pressing the button, it should work when loading the page.
This is button
<div>
<form method="post" action="">
<button value="cars" type="submit" id="submitCars">Get Cars</button>
</form>
</div>
Script of button by ajax
<script>
<![CDATA[
$(document).ready(function(){
$('#submitCars').click( function(event) {
event.preventDefault();
var button = $(this).val();
$.ajax({
url: 'search-facet-form',
data: 'button=' + $(this).val(),
dataType: 'json',
success: function(data)
{
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d=document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
return false;
});
});
]]>
</script>
DIV in HTML:
<div id="wines" class="span-7 colborder">
</div>
Javascript will print data in here. Thanks.
Just remove the call to click:
$(document).ready(function(){
var button = $('#submitCars').val(); //You may not even need this, you could just hard code this value
$.ajax({
url: 'search-facet-form',
data: 'button=' + button ,
dataType: 'json',
success: function(data)
{
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d=document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
});
Try to hit the DOM only once when inserting elements. IF you need the submit button then:
function loadCars() {
$.ajax({
url: 'search-facet-form',
data: 'button=' + $(this).val(),
dataType: 'json',
success: function (data) {
$('#wines').html('');
var mycars = '';
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
mycars += '<img src="' + imgen + '"/>';
}
}
$(mycars).appendTo('#wines');// hit the DOM only once with images
}
});
}
$(document).ready(function () {
loadCars();
$('#submitCars').click(function (event) {
event.preventDefault();
loadCars();
return false;
});
});
If the submit button is NOT needed then simplify that part and remove the submit button:
$(document).ready(function () {
loadCars();
});
Remove click handler and replace $(this).val() with $('#submitCars').val();
$(document).ready(function () {
var button = $('#submitCars').val();
$.ajax({
url: 'search-facet-form',
data: 'button=' + $('#submitCars').val(),
dataType: 'json',
success: function (data) {
$('#wines').html('');
if (button == 'cars') {
for (var i in data.facet_counts.facet_fields.manufacturer) {
if (!$.isNumeric(data.facet_counts.facet_fields.manufacturer[i])) {
var imagen = 'img/logo-cars/' + data.facet_counts.facet_fields.manufacturer[i] + '-logo-small.gif';
d = document.createElement('img');
$(d).attr('src', imagen);
}
$('#wines').append(d);
}
}
}
});
});
Just remove the $('#submitCars').click( function(event) part and have the whole thing float inside the $(document).ready(function()