I have a JavaScript function :
function post(aAction) {
var form = document.createElement("form");
form.action=aAction;
document.body.appendChild(form);
form.submit();
alert(form.action);
}
( I'm an experienced developer but not much experience with JScript - lifted that post() function from some website. )
I am passing this string into the function: A URL with query information:
http://testServer:3072/aQuerySite.dll/GetErrors?server=server1:5678
This URL returns a page listing error messages from the specified server: "server1:5678" - an argument passed to a server side query as
server=server1:5678
in the URL.
If I paste that URL directly into a browser and post it, the correct page with appropriate data is returned, and the browser address shows the complete URL as it was sent.
But when I pass the URL into my function, I get back a correctly formatted page but no records, and the browser address shows the URL truncated after the ? token : http://testServer:3072/aQuerySite.dll/GetErrors? The page returns showing no records because the query parameters after ? never got to the server for evaluation - query runs looking for nothing.
alert(form.action) in the function, which I added for debugging, shows the correct URL with query arguments, as does my debugger (WebStorm) and as mentioned, if I hit the URL directly from the browser, I get the correct result. I can only conclude that my URL is getting truncated in the form.submit() call.
This happens in IE, FireFox and Chrome. I also tried using ? for "?" - same result.
Why is this happening? How can I fix it?
It seems like you're trying to use a newly created form to redirect a user through its submission.
That is not necessary, as you can simply redirect the user using the following:
window.location = 'your_url';
In your case, you say that the querystring is being replaced with a simple ?.
That's because you created a form, and this form uses GET to post its data.
So if the form action is https://www.stackoverflow.com, the query string will be added with a interrogation following by the key/value pairs.
Let's suppose you have a form with two inputs named a and b, when you submit them, the query string would look like this:
https://www.stackoverflow.com?a=zzz&b=zzz
If you simply put this url in your form action, it will replace the query string with its own data when you submit it. Since your form has no named inputs, the query string will be empty, that's why you have an empty ? after the url.
Related
I am wondering how to deal with a simple redirect. I have a domain, for example: stackguy.com. And I want to redirect users to specific URLs from this url.
Let's say, stackguy.com/redirect=youtube.com/watch/xxx
And this URL (youtube.com...) needs to be elastic. What the user enters, it should redirect to the website the user wants.
I have totally no idea, to be honest. I've tried to do it by using database and by separating all urls but it's a lot of work and can't be automated easily.
It can also be done like stackguy.com/red=<id of YT video>
Doesn't matter to me.
The other solution talks about using javascript which runs on the client side. And you probably want this on the server side.
You still need to use a parameter
stackguy.com?redirect=https://www.youtube.com/watch/xxx
But you can use php to do the redirect.
$par = filter_var ($_GET ['redirect'] ?? '', FILTER_SANITIZE_STRING);
if ($par)
{header('Location: ' . $par, true, 302); }
The first line gets the parameter after sanitizing it. It returns blank if its null (or missing)
The second line checks if there is a string
The third line does a redirect using a 302. This is a temporary redirect, I wouldn't advise using a 301 (permanent).
Note that this will only work if the PHP file has done NO HTML output.
I think you should use query parameters for this and handle the redirect in your javascript. Instead of:
stackguy.com/redirect=youtube.com/watch/xxx
use
stackguy.com?redirect=https://www.youtube.com/watch/xxx
Then in your js you can check if the redirect paramter is set and redirect the user to the link in the query parameter.
Here is an example:
function redirectUrl() {
// Get the value of the "redirect" query parameter
const redirect = new URLSearchParams(window.location.search).get("redirect");
// If the "redirect" parameter is not null, redirect the user to the specified URL
if (redirect) {
window.location = redirect;
}
}
To use the function you will need to call it in your code for example:
window.addEventListener("load", redirectUrl);
My problem that I am trying to resolve is that I made an Ajax-autocorrect input feature and "onclick" of a button I get the value inside that input and attempt to make the page redirect to a Django URL.
Here is the URL inside my url.py file:
url(r'^groups/add-member/(?:/(?P<pk_group>[-\w]+))?/(?:/(?P<pk_member>[-\w]+))?/$', views.add_member, name='add-member')
inside the HTML I have this script:
<script>
function add_member(id){
var input=document.getElementById("myText").value
console.log(id) //Correctly gets ID #
console.log(input) //Correctly gets the name (string) of member instance
url = "{% url 'add-member' 0 zzzz %}".replace('0', id).replace('zzzz',input);
}
</script>
And the resulting error that I get is:
Reverse for 'add-member' with arguments '(0, '')' not found. 1 pattern(s) tried:
['flexfeed/groups/add-member/(?:/(?P<pk_group>[-\\w]+))?/(?:/(?P<pk_member>[-\\w]+))?/$']
I'm having trouble understanding my error. If anyone could suggest how to fix this issue or possibly suggest a difdferent approach to this particular problem I'd really appreciate it!
The end goal is that I want my page to redirect to my update view at the correct link!
Ok, so there is a problem with the order of what's happening. When Django renders your template it processes the tags. This happens before any javascript is called.
So you are trying to call the url with 0 and zzzz as the arguments. Django tries to fetch this and because the second argument is an empty variable here it doesn't match anything.
I would fix this by calling the url with two variables that are valid, then changing them with javascript.
url = "{% url 'add-member' 0 'change-team' %}";
url = url.replace(0, id).replace('change-team', input);
You might also be able to just put quotation marks around the zzzz.
So, there are 3 urls:
example.com/first
example.com/middle
example.com/last
In my sql db, there is table with each terms that correspond to related posts:
ID NAME POSTS
1 first 12,3,343
2 middle 23,1,432
3 last 21,43,99
So if an user visits example.com/first, then I want to show posts of "12,3,343" and other posts based on what url they are visiting.
Now, this is the sequence how it would work in my head:
User types "example.com/first"
js (ajax) or something detects the url (in this case, detects "first").
the term is sent to php query.
Gets appropriate info then sends it out (either by ajax or something else).
Am I approaching this right?
How does the server detects what url was requested? I supposed I can skip the first two steps if I know how the server detects the url and I can query the correct info directly instead of relying on js to detect it.
Thanks!
When you mention ajax, I assume you are not navigating away from the page your are on. Am I correct?
If so, you have to create another php file to respond to the requests:
A request is sent to file.php with the url as a query string
In file.php, let it query the DB and json_encode the data.
Retrieve the data and update the fields without navigating away.
PHP is only executed once (Server-side). if you want to execute another query you have to either navigate to other URL or just send your request to a php file via ajax.
You can get the segments of a url request using below statements
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $url);
Now you have all the segments in an array ($segments)
print_r($segments) to get the index of the segment you require.
Now compare that segment with your value
For Eg :
if( $segments[2] == 'first')
{
//Your Piece of code
}
I'm really confused how many times should I encode a URL when it is set as a value in a querystring 'coz we know browser has their own encoding process. Here's the scenario:
I want to redirect to another location which I want to pass the previous URL:
Note: the current URL is http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
Method A (without encodeURIComponent()):
window.location = 'CostEstimateApproval.aspx?CEMID=40' +
'&ToStatus=1CE'+
'&PrevURL=' + window.location;
I get this in the address bar
http://localhost:8081/CostMonitoring/CostEstimateApproval.aspx?CEMID=40&ToStatus=1CE&PrevURL=http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
without encodeURIComponent(), everything works fine and the value of Request.Querystring("PrevURL") in the receiving page is
http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
which is correct.
Method B (with encodeURIComponent()):
window.location = 'CostEstimateApproval.aspx?CEMID=40' +
'&ToStatus=1CE'+
'&PrevURL=' + encodeURIComponent(window.location);
with this method I get this in the address bar:
http://localhost:8081/CostMonitoring/CostEstimateApproval.aspx?CEMID=40&ToStatus=1CE&PrevURL=http%3A%2F%2Flocalhost%3A8081%2FCostMonitoring%2FMainMenu.aspx%3FOption%3DAllCE
and the value of Request.Querystring("PrevURL") in the receiving page is
http://localhost:8081/CostMonitoring/MainMenu.aspx?Option=AllCE
which is also decoded correctly.
My questions:
Should I encode the URL-as-value? Will it be redundant if I encode it then the browser encode it again?
or should I let the browser encode it for me? If I let the browser, will the receiving page be confused from URL-as-a-value's value to the real URL value? Please consider this example:
http://www.domain.com/newpage.aspx?SameName=DifferentValue&PrevURL=http://www.domain.com/oldpage.aspx?SameName=DifferentValue&PrevURL=http://www.domain.com/anypage.aspx
as you can see, both URL (the real URL and the URL-as-a-value) when not encoded has the same data name which is SameName. How does the receiving side handle this? or the HTTP server?
Thanks in advance!
You should use encodeURIComponent (once), since you're encoding a url parameter.
As you noted at the end of your question, failing to encode the url with encodeURIComponent would be problematic if your url included an &, for example.
Note that your Method A only worked because your example prevUrl is somewhat simply formed, e.g. it doesn't include a second url parameter.
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.