Retrieve URL Parameters Sent Through JQuery .load() - javascript

I am not sure if what I'm trying to do is possible or if I'm going about this the right way. In some circumstances I want them to have a GET parameter as part of the URL. I want the receiving page to be able to differentiate whether the sending load has a parameter or not and adjust accordingly.
Here is what I have that is sending the load:
$(document).ready(function () {
$("a").click(function () {
$("div.pageContent").html('');
$("div.pageContent").load($(this).attr('href'));
return false;
});
});
In this case, the load could have "example.php" or "example.php?key=value". In looking around (primarily on this site), I've found things that seem to be close, but don't quite get there. In the page that is getting loaded (example.php), I have the following:
function $_GET(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
$(document).ready(function () {
var URL = "example2.php";
if ($_GET('key'))
{
URL = "example2.php?key=" + $_GET('key');
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
If the sending source includes a query string, I want to add that to the URL and load it in a div that is unique to this page, otherwise I want to just load it as is without the query string. The big issue I'm running into (I believe) is since this is coming from an AJAX call, the "window.location.href" is not what was sent from the JQuery but rather the URL of the root page which never changes. Is there a way to be able to know what the full URL is that was sent from the load() in the first page by the second one?
Thank you in advance for your help.

I realized that the GET parameters were getting passed as I could access them through php without issue. I didn't know that I could insert php code into a javascript block but once I tried it, all worked out. My new code looks like this:
$(document).ready(function () {
var URL = "example2.php";
var myValue = "<?php echo $_GET['key']; ?>";
if (myValue !== "")
{
URL = "example2.php?key=" + myValue;
URL = URL.split(' ').join('%20');
}
$("div.output").load(URL);
});
I was able to get rid of the GET function out of javascript entirely. I probably made this much more difficult from the start but hopefully it can help someone else in the future.

Related

Calling an external html file using JSONP and PHP

It is possible this question might be a little vague for the liking of many people here, but my knowledge of the topic is vague also, and despite some searching I have not been able to find anywhere online with clear instructions on how to do this although (in my view) it should probably be one of the simpler cross-domain JSONP operations.
I will explain what I am trying to do. I am trying to retrieve the contents of a HTML file on an external server using both JSONP and a PHP script. I have access to the server - my PHP script is as follows:
<?php
$callback = '';
if (isset($_GET['callback']))
{
$callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);
}
$html = include($callback);
echo $callback . '('.json_encode($html).');';
?>
Using this it seems that when I type www.myurl.com/myscript.php?callback=filename.html, the correct file is displayed (although, for some reason, the ?callback is duplicated in the address, and the filename is appended to the end of the output displayed...
I have tried a few different scripts for my HTML file but currently have the following...
function request_jsonp(){
var script = document.createElement('script');
var url = 'http://www.myurl.com/myscript.php?callback=filename.html';
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
Now obviously this doesn't work because the output of the PHP script isn't a working function of any sort, but I am not sure of the best way to go about making it one. I would like to somehow wrap the output in something like this:
function DisplayOutput() {
document.getElementById('output').innerHTML = ...external HTML goes here!... ;
}
...but currently I'm really not sure of the best way to do this.
Any help would be very much appreciated.
callback needs to be the name of the callback function. You should generate a unique one each time the function is called.
You should use a second, different query string variable to determine what URI to fetch.
var jsonp_counter = 0;
function request_jsonp(url, callback){
jsonp_counter++;
var callback_name = "jsonp_function_" + jsonp_counter;
window[callback_name] = callback;
var jsonp_url = 'http://www.myurl.com/myscript.php" +
"?callback=" + encodeURIComponent(callback_name) +
"&url=" + encodeURIComponent(url);
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
request_jsonp("filename.html", function (data) {
do_something_with(data);
});

Tidying Javascript, Catching and manipulating URLs

Im very new to Javascript and have created the following code through lots of googling and finally have it doing what it needs to however, I am sure i will have done it the messy way.
I want it to get the current URL, remove the domain, then replace any _ with a space and finally place that value in a div.
$(document).ready(function() {
//pure javascript
//var URLname = window.location;
var URLname = "www.blahblah.com/John_Smith";
var CutURL = URLname.substring(URLname.lastIndexOf("/"));
var result = CutURL.substring(1);
var result = result.replace(/_/g, ' ');
document.getElementById("URLHolder").innerHTML = result;
});
Have i done this in the simplest form already? I just think passing the variable though could be done in one go but I'm unsure 100% how.
I will have a further play as I wait for advice.
Many thanks.
It might be easier to use window.location.pathname which will return just the bit after the domain.
// with url: "www.blahblah.com/John_Smith";
var cutURL = window.location.pathname; // John_Smith
var result = cutURL.replace(/_/g, ' ');

Changing how URL parameters are appended to links based on destination

My company is serving up PPC landing pages with Unbounce (on a subdomain), which then links back to our website. We're using the following code to append the AdWords gclid variable to outgoing links:
$(document).ready(function() {var params = window.location.search.replace(/\+/g,'%20'); var button = $('a').each( function(i) {this.href = this.href + params;});});
The issue arises when the Gclid gets appended to a URL that already has a parameter (like our checkout forms). You end up with a URL that looks like this:
domain.com/checkout?EventID=15546?Gclid=jdkI324kd
I'm wondering if there's a way to change the Glid's '?' to an '&' for certain URLs that already have parameters, while keeping the existing functionality of using the '?' for the others.
Thanks!
Edit: Seems like there's some redirection going on, this is how the href looks for the links in question:
http://domain.com/lp/clkg/https/domain.com/cart.aspx?EventID=125160?gclid=CPfO1JaOx7oCFQZyQgod5A4AFw
Simply replace it yourself:
$(document).ready(function() {
var params = window.location.search.replace(/\+/g,'%20');
var button = $('a').each( function(i) {
if (this.href.indexOf('?') == -1) {
this.href = this.href + params;
} else if (params.length) {
this.href = this.href + '&' + params.substr(1);
}
});
});
Edit: and are you aware that you are replacing subsequent spaces with only one single '%20'?

What's the best way to force a hashchange?

My website uses hashchange-triggered AJAX (to make it more bookmark-friendly). The problem I am having is that when I click "submit" in a form, all the form data that is serialize()'d to be sent via $.post() gets lost. I know this because I get the "Flag 1" alert after I click submit, and various other tests (alerting, echoing, etc.) show this to be true.
Here's my current code:
$(document).ready(function() {
var data = '';
var hash = '';
newPage();
alert('Flag 1');
$(window).bind('hashchange', function() {
hash = window.location.hash;
if (hash == '') {
path = window.location.pathname;
hash = '#' + path.replace(/^\/+/, '');
}
data += '&func=' + hash;
var xhr = $.post(hash, data, function(result) {
$("maincontent").html(result);
})
.done(newPage);
});
// Initialize vars and handle new form elements
function newPage() {
data = '';
$('form').submit(function() {
data = $(this).serialize();
// Flag 2 - What do I do here?
});
}
// Load ajax content on first run of document
if ($('#maincontent').html() == '')
$(window).trigger('hashchange');
});
What I am trying to do is manually fire a hashchange event while also changing the URL. The trouble is that if I just set window.location.hash = $(this).attr('action'); then return false; where the "Flag 2" comment is, then I wind up getting unwanted trash in the URL, possibly due to the hashmark being encoded for a URL (...%23, etc).
I am wondering what the best way to set the hash is, and whether there is a simpler way to do what I am trying to do to begin with.
(I'm also open to comments suggesting alternate approaches for the style of navigation I am trying to achieve)
Well, I understand there are lots of errors doing this. But we have alternative options for this you will surely like:
jQuery History Plugin : http://plugins.jquery.com/history/ (Demo: http://4nf.org/)
History JS: https://github.com/browserstate/history.js/
But I would recommend HTML5 history.pushState if you are willing to avoid older browser support. (Demo: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
Good luck!!

Can you pass URL parameters to a Javascript file?

<script src="myscript.js?someParameter=123"></script>
From within myscript.js, is there any way to obtain that someParameter was set to 123? Or is the only way to use server side scripts that generate the javascript file with the parameters in it?
Well, you get URL parameters from window.location.href. As the name says, it refers to the current window. What the <script> tag does it to embed the linked file into the current document, thus into the same window. If you parsed window.location.href from the linked JavaScript file, you'd only get the URL from the embedding document.
There are two ways to pass parameters to another JavaScript file:
As #Dave Newton suggested, just declare a variable, then embed the JS file like you did (without the parameters of course, because they have no effect).
Create an iframe, pass the parameters you want to the URL of the iframe, then embed the JavaScript file inside the iframe. An iframe will create a new window instance.
Jquery Address does this, so i've been checking their code out and this is the improved solution I just created myself:
$.each($('script'), function(id, val){ //loop trough all script-elements
var tmp_src = String($(this).attr('src'));//store the src-attr
var qs_index = tmp_src.indexOf('?');//check if src has a querystring and get the index
//Check if the script is the script we are looking for and if it has QS-params
if(tmp_src.indexOf('myscript.js') >= 0 && qs_index >= 0)
{
//this is myscript.js and has a querystring
//we want an array of param-pairs: var1 = value1, var2 = value2, ...
var params_raw = tmp_src.substr(qs_index + 1).split('&');
//create empty options array
var options = [];
//loop troug raw params
$.each(params_raw, function(id, param_pair){
//split names from values
var pp_raw = param_pair.split('=');
//store in options array
options[pp_raw[0]] = pp_raw[1];
});
//check the results out in the console!
console.log(options);
}
});
I hope this does what you need?
The answer is a definite "YES". I've been doing this on various projects for over a decade. The solution is actually easy, it's just non-intuitive (you have to generate an error). To be clear, the following code lets you do something like this:
<script src="https://example.com/script.js?id=1&bar=this works!" />
All you need to do is initiate a silent error, which takes less than 1/1000 of a second even on the worst outdated mobile browsers. You shouldn't do it a ton, but you only need to do it once. This error is processed, so it won't show up as an error in telemetry or 3rd party error trackers either.
// Generic function used to see if a param exists in a URL string.
// Provided here in case you don't know how to do it.
// This is not needed for the solution.
function getParameter (name, url) {
if (!url) url = scriptName()
name = name.replace(/[\[\]]/g, '\\$&')
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)')
var results = regex.exec(url)
if (!results) return null
if (!results[2]) return ''
return decodeURIComponent(results[2].replace(/\+/g, ' '))
}
// Gets the name of this script (whatever this file runs in)
// You can use this name to get parameters just like you would for the window URL :)
function getScriptName () {
var error = new Error(),
source,
lastStackFrameRegex = new RegExp(/.+\/(.*?):\d+(:\d+)*$/),
currentStackFrameRegex = new RegExp(/getScriptName \(.+\/(.*):\d+:\d+\)/)
if ((source = lastStackFrameRegex.exec(error.stack.trim())) && source[1] !== '')
return source[1]
else if ((source = currentStackFrameRegex.exec(error.stack.trim())))
return source[1]
else if (error.fileName !== undefined)
return error.fileName
}

Categories