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
}
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);
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.
This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I am trying to fetch a data file from a URL given by the user, but I don't know how to do. Actually, I can get data from my server successfully. Here is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it into an image. But now I want it work without any server, which means users can give a URL and javascript can get the file and render it. I know it's about the cross-site request. Can you tell me about it and how to realize it?
Thanks in advance!
assuming your URL is the address of a valid XML document this example will go grab it. if the URL is on a different domain than the one that's holding your scripts you will need to use a server side scripting language to got out and grab the resource (XML doc at URL value) and return it your domain. in PHP it would be ...
<?php echo file_get_contents( $_GET['u'] );
where $_GET['u'] is a URL value from your USER. let's call our PHP script proxy.php. now our JavaScript will call our proxy.php and concatenate the URL value to the end which will allow us to pass the URL value to the PHP script.
addy = $("#idOfInputFieldhere").val();
$.ajax({
url: 'proxy.php?u='+addy, /* we pass the user input url value here */
dataType:'xml',
async:false,
success:function(data){
console.log(data); /* returns the data in the XML to the browser console */
}
});
you'll need to use the js debugger console in chrome to view data. at this point you'd want to pull out data in a loop and use find() http://api.jquery.com/?s=find%28%29
I'm not very familiar with jQuery, but as I know, due to the same origin policy, the browser won't let any JavaScript code to make an AJAX request to a domain other than its own. So in order to retrieve some data (specially JSON formatted), you can add a <script> element to your page dynamically and set its src property to the address of the data provider. Something like this:
<script src='otherdomain.com/give_me_data.json'/>
This only works if you need to access some static data (like the url above) or you have access to the server side code. Because in this scenario, the server side code should return an string like:
callbackFunction({data1: 'value1', data2: 'value2', ...});
As the browser fetches the item specified in src property, tries to run it (because it know it's a script). So if the server sends a function call as a response, the function would be called immediately after all data has been fetched.
You can implement the server side in such a way that it accepts the name of the callback function as a parameter, loads requested data and generates an appropriate output that consists of a function call with loaded data as a json parameter.
I have a page in which I am making an ajax call, which in turn gets forwarded to a jsp page and returns a table constructed in this jsp.
Till now this jsp used to return an html which the original page(table) used to append in a particular div. But now, we have a requirement that this jsp along with the table, returns some other info about the metadat of the query.
With this change, I would ideally not like to change the existing behaviour of some clients where they are just appending the html. But then, is there a way, in which the new pages which make this call can have both the html table(which can be appended) as well as metadata returned (which can be processed).
let me know if the question isn't clear enough.
Thanks!
The easiest and least destructive change would be to send it as response header.
In the servlet you can use HttpServletResponse#setHeader() to set a response header:
response.setHeader("X-Metadata", metadata);
// ...
(using a header name prefixed with X- is recommended for custom headers)
In JS you can use XMLHttpRequest#getResponseHeader() to get a response header:
var metadata = xhr.getResponseHeader('X-Metadata');
// ...
You can even set some JSON string in there so that (de)serialization is easy.
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.