When the user likes a story on the card, users saves it with the "save" button. I do this as a savePost in my .js file. But if the user is not registered I am redirecting as "location.replace(APP_URL + "/login")".
I want to redirect to a modal on the homepage instead of /login. Is it possible for me to do this as a session or something?
function savePost(t) {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
$(this);
$.ajax({
url: APP_URL + "/save_favorite",
type: "POST",
dataType: "json",
data: {
item: t,
_token: $('meta[name="csrf-token"]').attr("content")
},
success: function(e) {
1 == e.bool ? $("#save-icon-" + t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-" + t).removeClass("icon-filled").addClass("text-muted")
},
error: function(e) {
location.replace(APP_URL + "/login")
}
})
}
Your current JS:
function savePost(t) {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
$(this);
$.ajax({
url: APP_URL + "/save_favorite",
type: "POST",
dataType: "json",
data: {
item: t,
_token: $('meta[name="csrf-token"]').attr("content")
},
success: function(e) {
1 == e.bool ? $("#save-icon-" + t).removeClass("text-muted").addClass("icon-filled") : 0 == e.bool && $("#save-icon-" + t).removeClass("icon-filled").addClass("text-muted")
},
error: function(e) {
location.replace(APP_URL + "/targetPage?showModal=1")
}
})
}
At the end of your target page add:
#if(isset($_GET['showModal']) && $_GET['showModal'] == 1)
<script type='text/javascript'>
$(window).on('load', function() {
$('#your modal id').modal('show');
});
</script>
#endif
In your routes/web.php add this:
Route::get('/', function () {
if(Auth::guest()){
return view('target.page');
} else {
return redirect('/somewhere');
}
});
Related
The below method returns 401 error on server. As I don't see any errors in this. Please suggest why its coming as 401 error
function loadSPANByMZ() {
try {
showLoading();
var OperationType = "";
if (R4GStateSelected != "Select") {
if ($(mzoneid).val() != "Select") {
if ($(activitytypeid).val() != "Select") {
//call CurrentGroupName UMS variable
var UserType = CurrentGroupName;
var SpanType = $(spantypeid + ' option:selected').val().toUpperCase();
var MZone = $(mzoneid + ' option:selected').val();
OperationType = $(activitytypeid + ' option:selected').val();
var Values = { "USERTYPE": UserType, "SPANTYPE": SpanType, "MZONE": MZone, "OPERATIONTYPE": OperationType.toUpperCase() };
//$(gridSpanlisttable).empty();
$.ajax({
type: "POST",
url: AppConfig.PrefixURL + "App/GetSPANList",
data: JSON.stringify(Values),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (response) {
displaySpanList(response, SpanType, MZone, OperationType);
//hideLoading();
},
error: function (response) {
hideLoading();
$(dataContent).hide();
},
complete : function(response)
{
hideLoading();
}
});
}
}
}
//},
}
catch (e) {
hideLoading();
$(dataContent).show();
}
}
I have a webshop, where user can order products only 1 piece/product. I need to check if that user already has same product in cart and if is, alert that and not add that product to cart again. If product is not in cart, add it to cart.
This is first what I tried, but it always adds product to cart even terms in If is true. Problem is cart.
$(".glyphicon-shopping-cart").on("click", function() {
$(this).css("color", "#29d646");
var BookID = $(this).parent().parent().prev().prev().prev().prev().prev().prev().text();
$.ajax({
type: 'GET',
url: '/api/selections/' + BookID,
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
},
success: function(sel) {
//check if Book is in cart already
$.ajax({
type: 'GET',
url: '/api/carts',
dataType: 'json',
success: function(cart) {
if (cart.CompanyID == JSON.parse(localStorage.getItem('userName')) && cart.ISBN == sel.ISBN) {
alert('Product is already in cart');
} else {
var toCart = {
CompanyID: JSON.parse(localStorage.getItem('userName')),
Orderdate: getdate(),
ISBN: sel.ISBN,
BookName: sel.BookName,
Author: sel.Author,
Publisher: sel.Publisher,
Price: sel.Price,
Season: sel.Season,
IsInCart: true,
};
$.ajax({
type: 'post',
url: '/api/Carts',
data: toCart,
success: function() {
console.log('Added to cart ' + BookID);
location.reload();
},
error: function() {
alert('Virhe!');
}
});
}
}
});
}
});
});
This in another way I tried to do this, now IF -statement is working but still product is added to cart. What should I do?
//check if Book is in cart already
$.ajax({
type: 'GET',
url: '/api/carts',
dataType: 'json',
success: function(cart) {
$.each(cart, function(i, carts) {
if (carts.CompanyID == JSON.parse(localStorage.getItem('userName')) && carts.ISBN == sel.ISBN) {
alert('Product is already in cart');
}
})
var toCart = {
CompanyID: JSON.parse(localStorage.getItem('userName')),
Orderdate: getdate(),
ISBN: sel.ISBN,
BookName: sel.BookName,
Author: sel.Author,
Publisher: sel.Publisher,
Price: sel.Price,
Season: sel.Season,
IsInCart: true,
};
$.ajax({
type: 'post',
url: '/api/Carts',
data: toCart,
success: function() {
console.log('Added to cart ' + BookID);
location.reload();
},
error: function() {
alert('Virhe!');
}
});
}
});
}
I don't know if this is right approach to this, if someone has better solution, please let me know.
var present=false;
$.each(cart, function(i, carts) {
if (carts.CompanyID == JSON.parse(localStorage.getItem('userName')) &&
carts.ISBN == sel.ISBN) {
alert('Product is already in cart');
present=true;
}
})
if(present===false){
other ajax part
}
You can get out of the function immediately by adding return. It 'early exits' the function and will prevent the program to proceed in adding cart.
if (...) {
alert('Product is already in cart');
return;
}
I have an action:
public function actionAjaxLoadBasketSmall() {
$this->enableCsrfValidation = false;
return $this->renderPartial('#app/views/basket/_small');
}
Some JavaScript
function loadBasketSmall() {
$.ajax({
method: "POST",
url: "/basket/ajax-load-basket-small",
dataType: "html",
beforeSend: function () {
$('#basketSmall').addClass('loading');
},
complete: function (data) {
$("#basketSmall").replaceWith(data.responseText);
}
});
}
Called from this function for example:
function handleProductTileButton(e) {
e.preventDefault();
var input = $(this);
$('#basketSmall').addClass('loading');
$.ajax({
method: "GET",
url: "/basket/ajax-add-product",
dataType: "html",
data: {
productId: input.data('product-id'),
quantity: 1,
},
beforeSend: function () {
input.addClass('loading');
},
complete: function (data) {
$('.top-bar .search-results').html(data.responseText);
input.removeClass('loading');
loadBasketSmall();
}
});
}
Whenever the Ajax call is complete the entire page gets redirected to /basket/ajax-load-basket-small
These are the response headers. Note the 302 response code.
So it was down to the language detection that was making the server send redirect responses.
To solve this I added this code to my base controller class
public function init() {
parent::init();
$this->initJsLang();
}
public static function jsDefineLang() {
return "const LANG = '" . \Yii::$app->language ."';";
}
protected function initJsLang() {
$this->getView()->registerJs(static::jsDefineLang(), \yii\web\View::POS_HEAD);
}
And updated my JavaScript accordingly:
function handleProductTileButton(e) {
e.preventDefault();
var input = $(this);
$('#basketSmall').addClass('loading');
$.ajax({
method: "GET",
url: "/" + LANG + "/basket/ajax-add-product",
dataType: "html",
data: {
productId: input.data('product-id'),
quantity: 1,
},
beforeSend: function () {
input.addClass('loading');
},
complete: function (data) {
$('.top-bar .search-results').html(data.responseText);
input.removeClass('loading');
loadBasketSmall();
}
});
}
function loadBasketSmall() {
$.ajax({
method: "GET",
url: "/" + LANG + "/basket/ajax-load-basket-small",
dataType: "html",
beforeSend: function () {
$('#basketSmall').addClass('loading');
},
complete: function (data) {
$("#basketSmall").replaceWith(data.responseText);
}
});
}
So final solution after Muhammad's suggestion
LanguageAsset.php
<?php
namespace frontend\assets;
use yii\web\AssetBundle;
/**
* Language application asset bundle.
*/
class LanguageAsset extends AssetBundle
{
public function init() {
parent::init();
$view = \Yii::$app->controller->view;
$language = \Yii::$app->language;
$js = "const LANG='{$language}';";
$view->registerJs($js, $view::POS_HEAD);
}
}
In my layout files I added:
use frontend\assets\LanguageAsset;
LanguageAsset::register($this);
While fetching data from the oracle database it showing "undefined" in Tree View structure using ASP.NET MVC and Gijgo tree view JQuery plug-in, The Tree View control can display a hierarchical (or nested, or recursive) collection of data in a tree of expandable nodes.. How to solve this?.Please, anyone helps me.
I am trying this link
https://www.codeproject.com/Articles/1185174/How-to-create-Dynamic-draggable-and-droppable-Tree
#section Scripts {
#Scripts.Render("~/bundles/Scripts/jqueryval") <script src="~/Scripts/jquery.validate.min.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Hierarchy/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'Id',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, ID, PID) {
currentNode = ID ? tree.getDataById(Id) : {};
console.log("current Node = " + currentNode);
parentNode = PID ? tree.getDataById(PID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PID === null && parentNode.PID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { id: ID, parentId: PID };
$.ajax({
type: "POST",
url: "/Hierarchy/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Hierarchy/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Hierarchy/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Hierarchy/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
Just make sure you name the property “text”, including lowercases, as the library binds this field to the label. Not having a property with this name renders it undefined.
I need to show a confirm box before performing this ajax request.
$(document).on("click", ".deletecustomer", function() {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
});
$(document).on("click", ".deletecustomer", function() {
if (confirm('Are you sure?')) {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
}
});