Laravel not getting redirected properly - javascript

In Laravel I have a web Route
Route::get('/signout', 'GlobalController#getLogout');
I use a logout option in my page as
<li>
<a href="{{ url('signout') }}">
<i class="icon-key font-red-thunderbird"></i> Log Out
</a>
</li>
The same way I have a ajax Change password success js script as
function parseError(response)
{
var res = 0;
$.each(response, function(i, item){
$('#'+i+'_message').html(item);
if(item!=1)
$('#'+i+'_message').css('display', (item!=1)?'block':'none');
else
res += parseInt(item);
});
if(res != 0 )
{
bootbox.alert("Password changed successfully..!");
window.location='/signout';
}
}
But the window.location='/signout'; is not touching the function getLogout() but the screen is changing to the login screen.
I have written a set of functions in getLogout which is not executing. What could be the problem.

You should try this:
<script>
// your "Imaginary javascript"
window.location.href = '{{url("yoururl")}}';
</script>
OR
<script>
window.location.href = '{{route("myRoute")}}';
</script>

Related

Pagination in .Net Core PartialView

I have a Partial View in which I load a pager for pagination.
The functionality of the pagination works, as the link changes as follows: http://localhost:1048/Trip -> http://localhost:1048/Trip?page=2 but it seems like my "request" to load the "next page" doesn't work as intended.
PartialView
//Here is a table view that
//that requires pagination.
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<ul class="pager">
<li>
<a asp-action="Index"
asp-route-page="#(Model.PageIndex - 1)"
class="btn btn-default #prevDisabled btn">
Previous
</a>
</li>
<li>
<a asp-action="Index"
asp-route-page="#(Model.PageIndex + 1)"
class="btn btn-default #nextDisabled btn">
Next
</a>
</li>
</ul>
I assume that my link is wrong (asp-action="Index"), but I have no idea what else to have it "navigate to" (I tried changing it to my controller function - but that result was very much unwanted) as I am still fairly new to .Net. Also I know that I have an error in my Controller function where I load page 1 always. How do I check whether a page is input to the function? (something like if (page == null) { page = 1 }) The function that loads my Partial View is as follows:
Controller function
[HttpGet]
public async Task<IActionResult> TripTable(int? page)
{
var trips = from t in _tripcontext.Tripmetadata select t;
page = 1;
int pageSize = 20;
return PartialView("PartialTripsView", await PaginatedList<Tripmetadata>.CreateAsync(trips.AsNoTracking().OrderBy(t => t.Tripid), page ?? 1, pageSize));
}
UPDATE
I guess I forgot to mention that whenever I use the Next button it just refreshed the entire Index page (without the Partial View in it). The Partial View is loaded when a button on the Index page is clicked, so when the page refreshes the Partial View is not present anymore.
I managed to figure it out after quite some reading online:
First of I changed my PartialView to the following:
#{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<ul class="pager">
<li>
<a id="prev" data-url="#Url.Action("TripTable", "Trip")" data-id="#Model.PageIndex" class="btn btn-default #prevDisabled btn">
Previous
</a>
</li>
<li>
<a id="next" data-url="#Url.Action("TripTable", "Trip")" data-id="#Model.PageIndex" class="btn btn-default #nextDisabled btn">
Next
</a>
</li>
</ul>
If someone else is stuck on the same problem I got most of my code from the Microsoft Docs on creating a pagination here.
My controller method was changed only a little:
public async Task<IActionResult> TripTable(int? page)
{
var trips = from t in _tripcontext.Tripmetadata select t;
int pageSize = 10;
return PartialView("PartialTripsView", await PaginatedList<Tripmetadata>.CreateAsync(trips.AsNoTracking().OrderBy(t => t.Tripid), page ?? 1, pageSize));
}
And in the bottom of my PartialView I added the following:
<script>
$("#prev").click(function () {
var _this = $(this);
var prevPage = _this.data('id') - 1;
$("#TripPartial").load(_this.data('url'), { page: prevPage }, function () {
});
});
$("#next").click(function () {
var _this = $(this);
var nextPage = _this.data('id') + 1;
$("#TripPartial").load(_this.data('url'), { page: nextPage }, function () {
});
});
</script>

Deleting href when clicked on a link (a delete icon) beside it (Javascript help)

I have a link <a href="#"> and beside that there is a delete png icon (which is also <a href="#"> link.
So what I want is, when clicked on that delete icon, the link <a href="#"> should get deleted with a confirmation window.
So far I have got like,
html:
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
My javascript for data-request
var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
success: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
}
This doesn't seem to be working! When I am clicking on the delete icon, it is displaying the confirmation window but not doing anything.
Is there any other simple way of achieving this? If not, can anyone tell me where am I going wrong?
Thanks.
var join_request = function(evnt){
evnt.preventDefault();
var $a = $(this);
var request = $a.data('request') || 'POST';
if (confirm("Are you sure want to delete it?")) {
$.ajax($a.attr('href'), {
type: request,
context: $a,
error: join_request_success
});
}
return false;
};
var join_request_success = function(data, a, b){
this.trigger('executed');
this.prev().remove();
};
$(document).ready(function(){
$('a[data-request]').bind('click', join_request);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>link <a class="delete" href="#" data-request="POST" >....</a></li>
</ul>
Note that I had to change success: to error: for demonstration.

isNan using this selector with dynamic content in jQuery

Here's the function I'm trying to use
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var data = {"action": "voteKarma", "id": $(this).data("id"), "value": $(this).data("val")}
$.post(window.apiURL, data, function(result) {
switch(result['status']) {
case 1:
var vote_sum_text = $(this).next(".sum").text();
if (!isNaN(parseInt(vote_sum_text, 10))) {
var vote_sum_text = $(this).next(".sum").text();
} else { alert("isNaN Variable") }
break;
}, 'json');
});
When the Ajax result returns 0 It's returning an alert with isNaN Variable which is my fallback to debug with problem.
Here's my HTML layout which is grabbed dynamically using another Ajax request there are multiple of these divs listed in <li> format :
<div class="votes pull-left">
<a class="up-vote" href="#" data-id="20" data-val="1"><span class="fa fa-arrow-circle-o-up"></span></a>
<span class="sum" style="font-weight:400;color:#666;">
0
</span>
<a class="down-vote" href="#" data-id="20" data-val="0"><span class="fa fa-arrow-circle-o-down"></span></a>
</div>
In simple terms; when you click .up-vote or .down-vote it'll send an AJAX request that'll then grab the text() of the .sum value.
Try use
$(event.currentTarget).next(".sum").text();
Because this in .post does not refer to element
You can also use the following:
$('body').on('click', '.up-vote', function(event) {
event.preventDefault();
var up_vote_this = $(this);
....
....
//now you can use the variable in the success function...
var vote_sum_text = up_vote_this.next(".sum").text();

Angular.bootstrap throwing error

I am trying to my migrate my website to angular but slowly. Current scenario is i am having a plain HTML login page in which there is a link to open a forget password popup. I have migrated the Forget password page to Angular. So what i am doing is when the user clicks on the link, i load the angular library, controller and application through $.getscript and then do a AJAX call to load the ForgetPassword page content in the popup. I can see in console evrything has loaded prioperly but error comes when i try to bootstrap. Please find below my JS code.The error i am getting in console is "ReferenceError: angular is not defined angular.bootstrap(document, ['myApp']);"
$(document).ready(function () {
$("#complementary-nav ul li a#popup").bind("click", function () {
loadfiles(function () {
OpenPopup();
angular.bootstrap(document, ['myApp']);
});
});
});
// Code to open in pop up
function loadfiles(callback) {
var scripts = ['/js/angular.min.1.2.9.js', '/js/Controller.js', '/js/application.js'];
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {});
}
if (typeof callback === "function") {
callback();
}
}
function OpenPopup() {
var url = "/dev/Forgot-Password.aspx";
$.ajax({
type: "GET",
async: false,
contentType: "charset=UTF-8",
url: url,
success: function (data) {
$("#common-popup").html("").append($(data));
$("#common-popup_overlay").fadeIn(500);
},
error: function () {
console.log("error")
}
});
}
The Forgot Password HTML looks like this
<div ng-controller="ForgotPasswordController" id="lostPasswwordOverlayContent" class="overlayContent">
<p>
<label>E-Mail<span class="mandatory">*</span></label>
<input type="email" ng-class="{'input-error':(_ServerForm.email.$dirty && _ServerForm.email.$error.emailValidate) || (blankSubmit && _ServerForm.email.$invalid)}" ng-model="user.email" email-validate required name="email" placeholder="" maxlength="100" id="EmailAddress" />
<span class="ui-state-error h5-message" ng-show="(_ServerForm.email.$dirty && _ServerForm.email.$error.emailValidate) || (blankSubmit && _ServerForm.email.$invalid)">
<span class="h5-arrow"></span>
<span class="h5-content">Invalid Email</span>
</span>
</p>
<div class="button buttonSimple buttonRight greenbutton forgotpassword">
<a name="fgtpassword" id="fgtpassword" href="#" class="" ng-click="submitform($event)"><span>Submit<span class="visual"></span></span></a>
</div>
I have tested the functionality seperately for this page and it works fine if opened an independent HTML page whereas when i try to make changes and open it as a popup, i am getting error
I never used $.getScript() but according to the documentation you can provide a callback when the scripts have arrived and have been executed. Why don't you call your own callback then?
function loadfiles(callback) {
var scripts = ['/js/angular.min.1.2.9.js', '/js/Controller.js', '/js/application.js'];
var scriptsAlreadyFetched = scripts.length;
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
scriptsAlreadyFetched--;
if (typeof callback === "function" && scriptsAlreadyFetched== 0) {
callback();
}
});
}
}
#meilke Yes the solution worked for me. But i found an alternative for doing it .
I am using the modernizr approach for the loading the JS files. With this approach i am also able to load CSS files together with the JS files
$("#complementary-nav ul li a#popup").bind("click", function () {
loadfiles(function () {
angular.bootstrap(document, ['myApp']);
});
});
function loadfiles(callback) {
var modernizrLoad = [{ load: ['//code.angularjs.org/1.2.8/angular.min.js', '/js/application.js', '/js/Controller.js', '/css/Styles_v2.css', '/css/tyles.css'], complete: function () { OpenPopup(callback); } }];
Modernizr.load(modernizrLoad);
}

Jquery Mobile Listview Clicked Item - Pass parameter to another page

I've a index.html page. Also this page contains lots of page like #home, #list #contacts etc.
in #list part i dynamically get data from my webpage and generate listview. I want that, when user click any of list item, redirect to #imageDetail page and pass image URL to page and show image
here is the #imageDetail page part
<div data-role="page" id="detailedIMAGE" data-theme="a">
<div data-role="header" data-theme="b" data-position="fixed">
<h1>Image Detail</h1>
</div>
<div data-role="content">
<img id="imageDetayURL" name="imageDetayURL" src="glyphish-icons/158-wrench-2.png"/>
<input type="text" disabled="disabled" id="brewername" name="brewername" />
</div>
</div>
</div>
And below code is my javascript code to get json data dynamically.
<script>
$('#last5').live("click", function() {
$.ajax({
url: "http://mysqlservice.com/getdata.json",
dataType: 'jsonp',
success: function(json_results){
$("#imageListDetay").html('');
console.log(json_results);
$('#imageListDetay').append('<ul data-role="listview" id="tweetul" data-theme="c"></ul>');
listItems = $('#imageListDetay').find('ul');
$.each(json_results.results, function(key) {
html = '<h3>'+json_results.results[key].screen_name+'</h3><span id="detailed_image">'+json_results.results[key].resim_url+'</span><img WIDTH=200 HEIGHT=100 src="http://mywebpage.org/upload/'+json_results.results[key].resim_url+'" /><p class="ui-li-bside"><img WIDTH=8 HEIGHT=13 src="images/07-map-marker.png"/> '+json_results.results[key].adres_data+'</p>';
listItems.append('<li><a name="imageDetayGoster" href="#detailedIMAGE">'+html+'</a></li>');
});
$('#imageListDetay ul').listview();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//error
}
});
})
$("#detailedIMAGE").live("pagebeforeshow", function (e, data) {
var brewername = $('#detailed_image',data.prevPage).text();
$('#brewername').val(brewername);
$('#imageDetayURL').attr('src', 'http://mobil.harmankaya.org/'+brewername);
alert(brewername);
});
</script>
The problem is after page change alert(brewername) fires. But list all image urls that listed in listview not my selected.
How can i fixed this issue
Thanks in advance.
jQM Docs:
http://jquerymobile.com/test/docs/pages/page-dynamic.html
This is just quoting the docs but if you read the page it should give you an idea on how to accomplish this.
The application uses links with urls that contain a hash that tells
the application what category items to display:
<h2>Select a Category Below:</h2>
<ul data-role="listview" data-inset="true">
<li>Animals</li>
<li>Colors</li>
<li>Vehicles</li>
</ul>
Well, this is my way and works very good.
HTML
<div data-role="page" id="myPage">
<div data-role="content" id="myContent">
<ul data-role="listview" data-inset="true/false/whatever" id="myList"></ul>
</div>
</div>
Javascript
$("#myPage").live("pageshow",function(event){
// get your id from LINK and parse it to a variable
var json_list_callback = getUrlVars()[id];
// verify the URL id
if (json_list_callback === '') {json_list_callback === ''} //or what value you want
// define your path to JSON file generated by the ID declared upper
var json_URL = 'http://your.path.to.json.file.php.json?id=' + json_list_callback;
// get the JSON data defined earlier and append to your LIST
$.getJSON(json_URL,function(data){
var entries = data;
//populate our list with our json data
$.each(entries,function(index,entry){
// i use dummy data here, you can have whatever you want in youre json
$("#myList").append(
'<li>' +
// remember that this "page.html?id=' + entry.json_id + '" will be the link where getUrlVars will get the id declared earlier in function
'<a href="page.html?id=' + entry.json_id + '">' + entry.json_title + '<\/a>' +
'<\/li>'
);
});
//must refresh listview for layout to render
$("#myList").listview("refresh");
});
});
//this function gets from URL the id, category, whatever you declare like this: getUrlVars()['id'] or getUrlVars()['category'] after last symbol of "?"
// you can define your own symbol with this function
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.lastIndexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
This works for me like a charm and i'm using it very often!
live event has been deprecated, use 'on',
exmple: $("#detailedIMAGE").on("pagebeforeshow", function (e, data){ // code });

Categories