Make an ajax request to get some data, then redirect to a new page, passing the returned data - javascript

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.

Related

Redirect to URL from URL

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);

php dynamic page content based on url

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
}

Can i pass information through the URL when i am using jQuery Mobile?

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 to correctly read Javascript hash in custom affiliate URL?

I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!
Now, how would I read the following URL?
www.mydomain.com/seo-friendly-url#ref=john
After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to
www.mydomain.com/seo-friendly-url
Any help is greatly appreciated!
Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).
The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:
To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john
if (window.location.hash.match(/#ref=/))
window.location = window.location.href.replace('#ref=', '/ref/')
... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.
(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])
window.onload = function () {
// grab the hash (if any)
var affiliate_id = window.location.hash;
// make sure there is a hash, and that it starts with "#ref="
if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
// clear the hash (it is not relevant to the user)
window.location.hash = '';
// initialize an XMLRequest, send the data to affiliate.php
var oXMLHttpRequest = new XMLHttpRequest;
oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
// do anything else that needs to be done after recording affiliate
}
}
oXMLHttpRequest.send(null);
}
}

Using PUT/POST/DELETE with JSONP and jQuery

I am working on creating a RESTful API that supports cross-domain requests, JSON/JSONP support, and the main HTTP method (PUT/GET/POST/DELETE). Now while will be easy to accessing this API through server side code , it would nice to exposed it to javascript. From what I can tell, when doing a JSONP requests with jQuery, it only supports the GET method. Is there a way to do a JSONP request using POST/PUT/DELETE?
Ideally I would like a way to do this from within jQuery (through a plugin if the core does not support this), but I will take a plain javascript solution too. Any links to working code or how to code it would be helpful, thanks.
Actually - there is a way to support POST requests.
And there is no need in a PROXI server - just a small utility HTML page that is described bellow.
Here's how you get Effectively a POST cross-domain call, including attached files and multi-part and all :)
Here first are the steps in understanding the idea, after that - find an implementation sample.
How JSONP of jQuery is implemented, and why doesn't it support POST requests?
While the traditional JSONP is implemented by creating a script element and appending it into the DOM - what results inforcing the browser to fire an HTTP request to retrieve the source for the tag, and then execute it as JavaScript, the HTTP request that the browser fires is simple GET.
What is not limited to GET requests?
A FORM. Submit the FORM while specifing action the cross-domain server.
A FORM tag can be created completely using a script, populated with all fields using script, set all necessary attributes, injected into the DOM, and then submitted - all using script.
But how can we submit a FORM without refreshing the page?
We specify the target the form to an IFRAME in the same page.
An IFRAME can also be created, set, named and injected to the DOM using script.
But How can we hide this work from the user?
We'll contain both FORM and IFRAME in a hidden DIV using style="display:none"
(and here's the most complicated part of the technique, be patient)
But IFRAME from another domain cannot call a callback on it's top-level document. How to overcome that?
Indeed , if a response from FORM submit is a page from another domain, any script communication between the top-level page and the page in the IFRAME results in "access denied". So the server cannot callback using a script. What can the server can do? redirect. The server may redirect to any page - including pages in the same domain as the top-level document - pages that can invoke the callback for us.
How can a server redirect?
two ways:
Using client side script like <Script>location.href = 'some-url'</script>
Using HTTP-Header. See: http://www.webconfs.com/how-to-redirect-a-webpage.php
So I end up with another page? How does it help me?
This is a simple utility page that will be used from all cross-domain calls. Actually, this page is in-fact a kind of a proxi, but it is not a server, but a simple and static HTML page, that anybody with notepad and a browser can use.
All this page has to do is invoke the callback on the top-level document, with the response-data from the server. Client-Side scripting has access to all URL parts, and the server can put it's response there encoded as part of it, as well as the name of the callback that has to be invoked. Means - this page can be a static and HTML page, and does not have to be a dynamic server-side page :)
This utility page will take the information from the URL it runs in - specifically in my implementation bellow - the Query-String parameters (or you can write your own implementation using anchor-ID - i.e the part of a url right to the "#" sign). And since this page is static - it can be even allowed to be cached :)
Won't adding for every POST request a DIV, a SCRIPT and an IFRAME eventually leak memory?
If you leave it in the page - it will. If you clean after you - it will not. All we have to do is give an ID to the DIV that we can use to celan-up the DIV and the FORM and IFRAME inside it whenever the response arrives from the server, or times out.
What do we get?
Effectively a POST cross-domain call, including attached files and multi-part and all :)
What are the limits?
The server response is limited to whatever fits into a redirection.
The server must ALWAYS return a REDIRECT to a POST requests. That include 404 and 500 errors.
Alternatively - create a timeout on the client just before firing the request, so you'll have a chance to detect requests that have not returned.
not everybody can understand all this and all the stages involved. it's a kind of an infrastructure level work, but once you get it running - it rocks :)
Can I use it for PUT and DELETE calls?
FORM tag does not PUT and DELETE.
But that's better then nothing :)
Ok, got the concept. How is it done technically?
What I do is:
I create the DIV, style it as invisible, and append it to the DOM. I also give it an ID that I can clean it up from the DOM after the server response has arrived (the same way JQuery cleans it's JSONP SCRIPT tasgs - but the DIV).
Then I compose a string that contains both IFRAME and FORM - with all attributes, properties and input fields, and inject it into the invisible DIV. it is important to inject this string into the DIV only AFTER the div is in the DOM. If not - it will not work on all browsers.
After that - I obtain a reference to the FORM and submit it.
Just remember one line before that - to set a Timeout callback in case the server does not respond, or responds in a wrong way.
The callback function contains the clean-up code. It is also called by timer in case of a response-timeout (and cleans it's timeout-timer when a server response arrives).
Show me the code!
The code snippet bellow is totally "neutral" on "pure" javascript, and declares whatever utility it needs. Just for simplification of explaining the idea - it all runs on the global scope, however it should be a little more sophisticated...
Organize it in functions as you may and parameterize what you need - but make sure that all parts that need to see each other run on the same scope :)
For this example - assume the client runs on http://samedomain.com and the server runs on http://crossdomain.com.
The script code on the top-level document
//declare the Async-call callback function on the global scope
function myAsyncJSONPCallback(data){
//clean up
var e = document.getElementById(id);
if (e) e.parentNode.removeChild(e);
clearTimeout(timeout);
if (data && data.error){
//handle errors & TIMEOUTS
//...
return;
}
//use data
//...
}
var serverUrl = "http://crossdomain.com/server/page"
, params = { param1 : "value of param 1" //I assume this value to be passed
, param2 : "value of param 2" //here I just declare it...
, callback: "myAsyncJSONPCallback"
}
, clientUtilityUrl = "http://samedomain.com/utils/postResponse.html"
, id = "some-unique-id"// unique Request ID. You can generate it your own way
, div = document.createElement("DIV") //this is where the actual work start!
, HTML = [ "<IFRAME name='ifr_",id,"'></IFRAME>"
, "<form target='ifr_",id,"' method='POST' action='",serverUrl
, "' id='frm_",id,"' enctype='multipart/form-data'>"
]
, each, pval, timeout;
//augment utility func to make the array a "StringBuffer" - see usage bellow
HTML.add = function(){
for (var i =0; i < arguments.length; i++)
this[this.length] = arguments[i];
}
//add rurl to the params object - part of infrastructure work
params.rurl = clientUtilityUrl //ABSOLUTE URL to the utility page must be on
//the SAME DOMAIN as page that makes the request
//add all params to composed string of FORM and IFRAME inside the FORM tag
for(each in params){
pval = params[each].toString().replace(/\"/g,""");//assure: that " mark will not break
HTML.add("<input name='",each,"' value='",pval,"'/>"); // the composed string
}
//close FORM tag in composed string and put all parts together
HTML.add("</form>");
HTML = HTML.join(""); //Now the composed HTML string ready :)
//prepare the DIV
div.id = id; // this ID is used to clean-up once the response has come, or timeout is detected
div.style.display = "none"; //assure the DIV will not influence UI
//TRICKY: append the DIV to the DOM and *ONLY THEN* inject the HTML in it
// for some reason it works in all browsers only this way. Injecting the DIV as part
// of a composed string did not always work for me
document.body.appendChild(div);
div.innerHTML = HTML;
//TRICKY: note that myAsyncJSONPCallback must see the 'timeout' variable
timeout = setTimeout("myAsyncJSONPCallback({error:'TIMEOUT'})",4000);
document.getElementById("frm_"+id+).submit();
The server on the cross-domain
The response from the server is expected to be a REDIRECTION, either by HTTP-Header or by writing a SCRIPT tag. (redirection is better, SCRIPT tag is easier to debug with JS breakpoints).
Here's the example of the header, assuming the rurl value from above
Location: http://samedomain.com/HTML/page?callback=myAsyncJSONPCallback&data=whatever_the_server_has_to_return
Note that
the value of the data argument can be a JavaScript Object-Literal or JSON expression, however it better be url-encoded.
the length of the server response is limited to the length of a URL a browser can process.
Also - in my system the server has a default value for the rurl so that this parameter is optional. But you can do that only if your client-application and server-application are coupled.
APIs to emit redirection header:
http://www.webconfs.com/how-to-redirect-a-webpage.php
Alternatively, you can have the server write as a response the following:
<script>
location.href="http://samedomain.com/HTML/page?callback=myAsyncJSONPCallback&data=whatever_the_server_has_to_return"
</script>
But HTTP-Headers would be considered more clean ;)
The utility page on the same domain as the top-level document
I use the same utility page as rurl for all my post requests: all it does is take the name of the callback and the parameters from the Query-String using client side code, and call it on the parent document. It can do it ONLY when this page runs in the EXACT same domain as the page that fired the request! Important: Unlike cookies - subdomains do not count!! It has to he the exact same domain.
It's also make it more efficient if this utility page contains no references to other resources -including JS libraries. So this page is plain JavaScript. But you can implement it however you like.
Here's the responder page that I use, who's URL is found in the rurl of the POST request (in the example: http://samedomain.com/utils/postResponse.html )
<html><head>
<script type="text/javascript">
//parse and organize all QS parameters in a more comfortable way
var params = {};
if (location.search.length > 1) {
var i, arr = location.search.substr(1).split("&");
for (i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
params[arr[i][0]] = unescape(arr[i][1]);
}
}
//support server answer as JavaScript Object-Literals or JSON:
// evaluate the data expression
try {
eval("params.data = " + params.data);
} catch (e) {
params.data = {error: "server response failed with evaluation error: " + e.message
,data : params.data
}
}
//invoke the callback on the parent
try{
window.parent[ params.callback ](params.data || "no-data-returned");
}catch(e){
//if something went wrong - at least let's learn about it in the
// console (in addition to the timeout)
throw "Problem in passing POST response to host page: \n\n" + e.message;
}
</script>
</head><body></body></html>
It's not much automation and 'ready-made' library like jQuery and involes some 'manual' work - but it has the charm :)
If you're a keen fan of ready-made libraries - you can also check on Dojo Toolkit that when last I checked (about a year ago) - had their own implementation for the same mechanism.
http://dojotoolkit.org/
Good luck buddy, I hope it helps...
Is there a way to do a JSONP request using POST/PUT/DELETE?
No there isn't.
No. Consider what JSONP is: an injection of a new <script> tag in the document. The browser performs a GET request to pull the script pointed to by the src attribute. There's no way to specify any other HTTP verb when doing this.
Rather than banging our heads with JSONP method, that actually won't
support POST method by default, we can go for CORS .That will provide no big changes in the conventional way of programming. By simple Jquery Ajax call we can go with cross domains.
In CORS method, you have to add headers in server side scripting file, or in the server itself(in remote domain), for enabling this access. This is much reliable, since we can prevent/restrict the domains making unwanted calls.
It can be found in detail in wikipedia page.

Categories