The actual scenario is like I have 6k table rows which coming after the new action call. Below is call
var url = parent.getActionURL('fullExpand') + '?object=' + getTableBeanName();
if (typeof levels !== 'undefined') {
url += '&expandTo=' + levels;
}
window.location.replace(url);
The reponse is coming from server but it is not rendering in ui if we touch any dom element then reponse is rendering.if we change window.location.replace to window.location.href = url. Then problem get resolved for first time the behaviour is not consistent
The question is not totally clear, but they both navigate to the URL. replace() replaces the current document and it doesn't add a record to history, the behavior should be consistent in both cases.
With replace(), when the user clicks the back button they are returned to the page before the page that they were redirected from, this might cause your confusion. (read here)
You should use what is best for your use case.
Related
I'm trying to add this specific string to the end of my url on page load:
?aa_campaign=f45632
(http://examplesite.com/test.html)
It's for marketing and tracking.
I've tried this:
if window.location.href.indexOf("http://examplesite.com/test.html") {
window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}
That straight up didn't work but the idea is what I'm looking for. Any thoughts?
No need for jQuery, you can do this with pure JavaScript in most "modern" browsers, i.e.:
if (window.location.href === "http://examplesite.com/test.html") {
window.history.pushState("object or string", "Title", "http://examplesite.com/test.html?aa_campaign=f45632");
}
The pushState() method
pushState() takes three parameters: a state object, a title (which is
currently ignored), and (optionally) a URL. Let's examine each of
these three parameters in more detail:
state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever
the user navigates to the new state, a popstate event is fired, and
the state property of the event contains a copy of the history entry's
state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored
after the user restarts the browser, we impose a size limit of 640k
characters on the serialized representation of a state object. If you
pass a state object whose serialized representation is larger than
this to pushState(), the method will throw an exception. If you need
more space than this, you're encouraged to use sessionStorage and/or
localStorage.
title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe
against future changes to the method. Alternatively, you could pass a
short title for the state to which you're moving.
URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to
pushState(), but it might attempt to load the URL later, for instance
after the user restarts the browser. The new URL does not need to be
absolute; if it's relative, it's resolved relative to the current URL.
The new URL must be of the same origin as the current URL; otherwise,
pushState() will throw an exception. This parameter is optional; if it
isn't specified, it's set to the document's current URL.
SRC : https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
You can add the string to window.location.search instead, for a more general solution.
if (location.origin + location.pathname === 'your url here') {
location.search += 'additional data here';
}
The advantage of this approach is that you can apply this code to multiple pages with less changes to the same code.
Note that this will cause a page reload, which might not be optimal to user experience. Since you said you are doing this for tracking, you can instead ping the page by appending an image with the new url to DOM. Something like this:
var pinger = new Image(0,0); // keep the size of the image 0
pinger.src = 'changed url here, with the new query param appended';
document.body.appendChild(pinger); // ping sent
pinger.parentNode.removeChild(pinger); // remove the node when ping is sent
Hope that helps :)
This version will preserve any existing query string, and properly append your "aa_campaign=f45632" parameter string.
var w = window.location;
if (w.search.indexOf("aa_campaign") == -1) {
window.location = w + (w.search.indexOf("?") == -1 ? "?" : "&") + "aa_campaign=f45632";
}
Example:
http://example.com --> http://example.com?aa_campaign=f45632
http://example.com/page.html?id=1 --> http://example.com/page.html?id=1&aa_campaign=f45632
try this:
if (window.location.href.indexOf("http://examplesite.com/test.html" !== -1) {
window.location = "http://examplesite.com/test.html?aa_campaign=f45632";
}
I have a mobile application that opens an in-app browser that uses the URL to pass information to my server , like the deviceID.
For example the browser will open the web-page (jquery Mobile) : www.myserver.com/doWork.html#deviceID
On the server part using JavaScript inside the doWork.html file, I get the deviceID like this:
var userId = window.location.hash.substring(1);
Is it ok that i pass information using the hash # ? In jquery mobile the hash # is used to change between pages when someone uses the Multi-Page template structure . So i am afraid that maybe i should use something else , like a question mark (?) ?
Or its perfectly fine ?
NO. Stop using # for your data transfers. Let jQM do its thing. Don't disturb it. Use Query strings( adding ? in url). My advice is to stop using query strings (? tags) and # tags to send data to the next page. Handle it using localStorage. Its more secure compared to Query strings because the user wont see the URL change, so your sensitive data is hidden, at least to a little extent. localStorage is HTML5's API which is like a temporary storage set aside per domain. This data will persist until data is cleared in cache. Assuming you have an anchor tag which goes to dowork.html,
Go to Do work
Add an attribute for device ID in the tag itself, like this :
Go to Do work
You'd be doing this dynamically you might also use it the same way. You get the gist right?
A click event for this would look like this :
$(document).on("click", "a", function(e) //use a class or ID for this instead of just "a"
//prevent default
e.preventDefault();
//get device id from tag attribute
var deviceId = $(this).data("deviceid");
//set it in localStorage
localStorage["dId"] = deviceId;
//redirect
$.mobile.changePage(this.href);
});
Then, in the other page's pageinit (or any event), get the device id from storage and send the ajax call to the server.
//assuming #dowork is the id of a div with data-role="page"
$(document).on("pageinit", "#dowork", function() {
//get from storage
var deviceId = localStorage["dId"];
//make ajax call or server call with deviceId here
});
But, if you still want to use URL for this, look at this question. I've given a decent enough answer over there.
To pass variables to the server you should avoid using the # symbol because regardless of the framework you are using this symbol is used for other purposes, to pass info to the server in a GET request you should use the ? symbol, something like this should do it: www.myserver.com/doWork.html?deviceID=1233455
How can I execute jQuery/JS code as soon as a jQuery/JS redirect like...
$(location).attr('href','/target_path');
...or...
window.location.href = "/target_path";
...has finished loading the new page?
Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page.
You can't. Once the redirect happens you are no longer on that page. You can't execute code on a page you are no longer on. If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so.
It is impossible to tell JavaScript to execute some code after a redirect.
However you have different options:
Pass a string in the redirect URL and then do something on "ready"
Store some information in a cookie and then do something on "ready"
Store some data using DOM storage (namely sessionStorage) if you don't mind the smaller browser support
You can't do that in the page that's redirecting. You can read the referrer in the landing page (document.referrer), and then decide whether to display an alert based on that, though.
var x = "It's some text";
var loc = '/target_path';
loc += '?message=' + encodeURI(x);
The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected.
You can use window.location.search on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object.
Hashchange is for when
index.php
Changes to, say
index.php#my-hash
i.e.
$(window).bind('hashchange', function() {
// do stuff
});
But is there an event for when there is a ? after the url, i.e.
index.php?id=foo&something_else=bar...
Edit
Okay, it's when I submit a form. I submit the form and then the URL changes to
index.php?id=blah#my-hash
However I tried listening for a) the hashchange and b) the form submit:
$('form').submit(function() {
go_to_signup_form();
});
Neither of which work (I think the page is refreshing?). I can't alter the php too much because it's part of a cms and I don't want to break anything that's happening in say, the controller class so I would rather just try to see when:
index.php
changes to
index.php?id=blah#my-hash
Edit #2
Thanks everyone for the feedback, got it working with:
if (url.indexOf("?") !== -1) {
go_to_signup_form();
}
Nope, that is because the parameters (?foobar) aren't usually used for client-side code. Linking to a new parameter on the same url (index.php -> index.php?foo=bar) makes your browser load a new page, while adding a hash (index.php -> index.php#foo=bar) does not make the browser transmit any data to the server.
The hash section of a url, it's a client-side piece of data. As such, it is useful to have a change event listener for it.
Try these in your console, on a random site that doesn't have a hash in the url yet:
window.location.href += "?test"
and:
window.location.href += "#test"
You will see that the first one will reload the page (Send a new HTTP request), the second one will not appear to do anything.
To prevent a form from submitting:
$('#target').submit(function() {
// Your onclick code here
return false; // Do not submit.
});
The problem with that is that the "hashchange" (technically it means navigation to an anchor) is an entirely client-sided operation. But an URL with arguments (the "?" operator) is fulfilled with a new HTTP request to the server, which results in a new document being sent to the user. That means when a user clicks on a link index.php?id=foo, the page is reloaded.
But you can check the arguments of the URL the page was loaded with by examining the window.location.href string.
I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.