Get current DOM element - javascript

I have a functioning site that includes a search function that loads results into a <div> element via a jQuery $.ajax call like so:
$.ajax({
url: '{{ path('order_search') }}',
type: $(this).attr('method'),
data: $('#search_form').serialize(),
success: function (data) {
$('#js-search-results').html(data);
}
});
I'm working in a twig template within a symfony project, thus the url notation. This is working perfectly.
This is on a site that requires login. I have an event listener in symfony that checks for a period of inactivity at each each kernel request (taken from here), and if the inactive period exceeds a maxIdleTime then the user is redirected to the login page.
My problem is that if the user is inactive for a period and then enters a search, the js-search-results div is filled with the login page. What I would like to happen is to have the entire window redirect to the login page. Seems simple, but I haven't figured out how to do it.
One what I thought to handle would for my login page script to check whether it was being loaded into the full window (rather than just a div element), and if not then refresh the entire window. How to do this?

You can check the content inside the variable "data" to check if it contains elements from the login page and then use an if else statement.
if(data.includes("username") && data.includes("password")){
window.location.assign("https://your.login.page.html");
}else{
$('#js-search-results').html(data);
}

It sounds like you want to find out what type of data is there and if it is the login page do a redirect.
Find out if the data contains elements that are in the login page. if it is do a window.location.href = "/login" if not display the search results in the div. send data from backend like {page : "login"}

Related

Using Ajax to load beta signup page & clicking opt in without showing page

I'm trying to build a button that will allow users to automatically opt into all of a developer's beta apps (or the ones they select from a list I'll present) without the need to navigate to each beta app's sign-up page on the google playstore. I've tried the following, it loads the page, but I can't get the button-click/form submit right when trying it through ajax.
$.ajax({
url: 'https://play.google.com/apps/testing/com.joaomgcd.autoshare',
success: function( data ) {
// process data (which is actually your page contents)
//console.log(data);
alert("Loaded");
//$("input.action").click();
//var clickme = document.querySelector(".action");
$('.joinForm').submit()
//clickme.click();
alert("Done");
}
});
I get the first popup, but not the second one. This particular developer has each link on one page of their website, I'm just trying to make it easier for his communities to opt into all betas instead of one-by-one. What am I doing wrong in my above code? Do I need to be clicking the input button titled "Become a Tester" (class input.action) or submitting the form that contains that input button (form class joinForm)?
Per request: Code of the Beta Opt-In page
Error being thrown:

How to change URL path when paging using ajax + jQuery

I am using ajax post requests for doing paging on a feed in my site. When getting the post request data I am reforming the page by clearing previous data and rendering the new data that came from the request. I want to be able to change the URL as well so saving the new page link will get the user to the current page.
Example:
User on page example.com/feed - seeing content of page #1
User clicking to get to page #2 -> ajax post is send and data on the page is changed using js (no refresh)
URL is still example.com/feed but the content is of example.com/feed?page=2
How can I set the URL to point to the new page without triggering a refresh (no redirect) ?
I am using Nodejs + express.
I understand you are aiming at a single page application.
While keeping the url is nice, note you might want distinct urls for directly accessing different parts of your application. Still, you can load content with AJAX and keep a smooth application. The way to go is using the hash part of the location.
The Sammy.js framework gives you a nice base to build upon, you can try it out.
You can use history pushstate but some browsers does not support.
history.pushState({id: 'SOME ID'}, '', 'myurl.html');
And don't forget about window.onpopstate, it pops if user clicks back button.
Redirect the user to an anchor point.
Page 2
And in your document.ready:
if (window.location.hash.length > 1){
var pageNumber = window.location.hash.substring(1);
loadPage(parseInt(pageNumber));
} else{
loadPage(0);
}
I don't believe it is possible to change the query part of the URL without triggering a refresh (probably due to security issues). However you may change the anchor and use an event listener to detect when the anchor is being changed.
//Listener
$(window).on('hashchange', function() {
if(loaction.hash.length > 1) {
//The anchor has been changed.
loadPageWithAjax("example.com/feed.php?page=" + location.hash.substring(1));
} else {
//Load standard page
...
}
});
Change the anchor to load new feed
Page 2
Remember to not use an anchor that is used as an id, since this makes the browser scroll to that element.

call spring action from jquery without ajax for multiple buttons like view edit etc

I am working on Spring MVC. I have a page having list of items in table. I need jquery to pick up the radio selected and then user can click on view or edit or delete. According to the button clicked, ajax block invokes proper action with the form object serialized and the id goes to the action for processing.
Everything went fine till here.
Then, when the action returns back to ajax success: block
$.ajax({
type : "post",
data : str,
url : newUrl ,
async : false,
success : function(data) { <----- here
I need to redirect to page action has in its view object. Instead, as we know, its ajax, so I need to show the result in some div on that page itself. But I need to go to the page directed by spring action. Please help me do this.
In short, I don't want to show the details on a pop up but another page.
Thanks.
get url of page directed by page action and use following statement to redirect page
window.location = pathReturned;
above statement will simply redirect users' browser window. So if you may require to persist state of the page.

Check for page refresh or close with jQuery/javascript

I am looking to check if a page has been refreshed or closed with jQuery or javascript.
What I have currently is I have some database values that I want to delete if the user either navigates away or refreshes the page.
I am using AJAX calls to delete the values.
Right now, I have the following code:
The handler:
window.beforeunload = cleanUp;
The cleanUp() method:
function cleanUp() {
// Check to see if it's an actual page change.
if(myActualLeave) {
$.ajax({
type: "POST",
url: "/api/cleanup",
data: { id: myLocalId },
success: function (data) {
console.log(myLocalId + " got removed from the database.");
}
});
}
// Reset the flag, so it can be checked again.
myActualLeave = true;
}
Where myActualLeave is a flag that I set to false when AJAX calls are made, so they don't trigger the beforeunload handler.
The problem I am running into is that when I click a link on my page, so for instance a link to Google, the window.beforeunload doesn't trigger. I may have a misunderstanding of this, but I have tried using jQuery's $(window).unload(...); and the onbeforeunload trigger as well.
What should I use to call javascript when:
the user refreshes the page,
when the user navigates away from the page, or
when the user closes the page?
Edit: It came up in a comment that I could use a click() jQuery handler to detect navigating away. I should have made it more specific that I don't mean when the user clicks a link only then I want it to proc. I want it to trigger when they change pages in any way. So if the address bar gets typed in, for instance.
You should try "onbeforeunload" :
window.onbeforeunload
But i think you can't put "active" (ajax call) code in this callback function. All you can do is defining a confirm modal window that will be displayed to the user before leaving like :
Are you sure you want to leave because...
So you should do as #Leeish said : put a code in the .on('click') of the link so it can launch the ajax call before sending to another page.
But for the "refresh" or "close" scenario, you can consider marking your database row as "draft" (or whatever) and if not saved when on the next page, delete the draft line.

Remove URL Variable on after some time

I have a div identified as emailsuccess. A user fills out a contact form and submits it he is redirected to http://www.mysiteurl.com?email=success. I have a div that only will display when the URL contains email=success. (Basically it just displays a message "You're email has been sent".) I'd like to have the message display for about 5 seconds, then fade out and remove the email=success variable from the URL so if the user reloads the page or shares it with a friend, they won't be getting notifications that an email has been sent.
Maybe using the .delay() function I have set the integer to 5000 but I do not know how to have the content fade out and remove the variable from the URL.
Here's my code until now:
$(document).ready(function(){
var url = document.location.href;
if (url.indexOf('/Contact-us-a/7.htm?email=success') >= 0) {
$('#emailsuccess').show();
} else {
$('#emailsuccess').hide();
};
});
Unless you limit yourself to browsers that support the History API, you'll have to redirect the browser to a URL that doesn't contain that part of the URL (will cause page reload).
Symfony Framework for PHP solves this using flash variables in templates (has nothing to do with Flash) - variables that are available on the next request, but are deleted on the next. That way, you wouldn't have to pass that state via URL and a refresh of the same URL will not redisplay that message.

Categories

Resources