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');
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);
I am trying to get data from controller and send it in ajax.
The script is in app.blade.php.
Controller
public function show()
{
$number=Order::where('user_id',Auth::user()->id)->count();
return $number;
}
Route
Route::get('product_number', 'OrderController#show')->name('product_number');
JS
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "product_number",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
</script>
In console it shows me the html view.
try this so you can get the error
public function show()
{
try {
$number=Order::where('user_id',Auth::user()->id)->count();
} catch (\Exception $e) {
echo $e->getMessage(); die;
}
return $number;
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "{{url('product_number')}}",
success: function (data) {
console.log(data);
},
error: function () {
console.log('Error');
}
});
});
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);
});
}
});
I am using chrome popup extension but no data is sent to the php file named api.php.I have searched on stackoverflow and found ajax related content but nothing is working.here is my popover.js file which uses ajax.I used $_POST['data'] to grab the data in api.php file
var api_url = "https://localhost/psol/api.php";
window.onload = function () {
$("#checkout_btn").click(function () {
chrome.runtime.sendMessage({
'btnClicked': true
}, function () {});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(request);
if (request.message === "show-loading") {
$(".psol-button").addClass('hide');
$(".psol-loader").removeClass("hide");
}
if (request.message === "hide-loading") {
$(".psol-button").removeClass('hide');
$(".psol-loader").addClass("hide");
}
if (request.message === "post-cart") {
console.log(request.data);
alert(JSON.stringify(request.data));
chrome.runtime.sendMessage({
'postCartDone': true,
'redirectTo': api_url
}, function () {});
$.ajax({
url: api_url,
type: "POST",
data: request.data,
// data:{name:'uzair'},
success: function (result) {
// alert("all done");
console.log(1, result);
}
}).done(function (result) {
console.log(2, result);
if (result.cartCount === 0) {
alert('There are no items in cart to checkout');
}else {
alert("this is also redirect");
}
});
}
});
};
I have a mobile application with MVC3 and Jquerymobile. At form submission (with ajax function) I want to display loading icon (ajax-loader.png) while submit and redirect.
Thanks!
my ajax function:
$("#add").click(function () {
$.validator.unobtrusive.parse($('form')); //added
if ($("form").valid()) {
var IDs = new Array($("#SelectedProduct").val(), $("#SelectedAccount").val(), $("#SelectedProject").val(), $("#SelectedTask").val(), $("#date").val(), $("#duration").val());
$.ajax({
url: '#Url.Action("SaveLine", "AddLine")',
type: 'post',
data: { ids: IDs },
dataType: 'json',
traditional: true,
success: function (data) {
if (data.success == true) {
$("#ajaxPostMessage").html(data.Success);
$("#ajaxPostMessage").addClass('ajaxMessage').slideDown(function () {
window.location.href = '#Url.Action("Index", "AddLine")';
}).delay(1800)
}
else {
$("#ajaxPostMessage").html(data.Error);
$("#ajaxPostMessage").addClass('ajaxMessage');
$("#ajaxPostMessage").show();
}
}
});
}
return false;
});
I would do something like this:
Ajax = {
Submit: function() {
Ajax.Loading();
//ajax stuff
//Ajax.Message('form complete, blah blah');
},
Loading: function() {
$('#ajax').html('ajax-loader.png');
},
Message: function(msg) [
$('#ajax').html(msg);
}
}