How call PHP from HTML to get url? - php

I am installing Disqus Comment system on my website. I understand that I can dynamically call the page url or id via php and thus do not need to hardcode the URL or page ID everytime I have a Discus comment box.
This question asked 7 years ago this answer was provided by #Yogus but I couldn't get it to work.
<HTML>
<title>HTML with PHP</title>
<body>
<h1>My Example</h1>
<?php
include 'testConnection.php';
?>
<b>Here is some more HTML</b>
<?php
//more php code
?>
</body>
</HTML>
I've hear that to use PHP I must change my website pages to end in .php rather than .html. I don't want to do this for every page as it would probably affect SEO and I've currently 325 pages.
I'd like to do a call to a PHP file, have it return a variable with the URL or Page ID and then I can plug this into the Discus. I've read there is a dedicated variable maybe $_SERVER which returns the page URL or ID.
Any help would be appreciated! Oh, a link to one page where I've Discus installed is here {go to bottom}. This page is hard coded in.
coinsandhistory.com/countries/Ancients_Rome/Ancients_48_Rome_Empire_Tetrarchy-Constantine.html

You can still keep your pages as HTML in this case.
You can make a call to the PHP page with Javascript, get the result via AJAX, and then use that result in a URL. In this example, I will feed the php a parameter that will determine what the URL will be. The HTML page will use javascript to populate the link in the anchor tag with the data coming from the php file.
example
the PHP code would look something like:
<?php
$p = $_REQUEST['p'];
if($p == 'one')
echo 'http://urlone.php';
if($p == 'two')
echo 'http://urltwo.php';
?>
the HTML code would look something like:
<html>
<script>
function populateURL(param){
//get the anchor tag
var link = document.getElementById('dlink');
//call the php file to return the url as a string,
//then set the url of the anchor to that string
fetch('url.php')
.then(response => (response){dlink.href = response});
}
//get the url if the value is 'one'
populateURL('one');
</script>
<body>
<a id="dlink">CLICK HERE </a>
</body>
</html>

I found a working answer on SO from ~10 years ago.
Get current URL with jQuery?
The solution was to use javascript from within the HTML which has queries for such things.
// Returns path only (/path/example.html)
var pathname = window.location.pathname;
// Returns full URL (https://example.com/path/example.html)
var url = window.location.href;
// Returns base URL (https://example.com)
var origin = window.location.origin;
To look at the results I just use the javascript to write out the answer, i.e
<p>JavaScript variables<br><br>
page url:
<script type="text/javascript"> document.write(page_url)
</script>
Thus php nor an external file wasn't needed. A note the javascript variable assigns MUST be done before the print commands, otherwise Chrome reports an error & nothing is displayed.

Related

How can i redirect the user after a form validate in Jquery using load() function [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How can I redirect the user from one page to another using jQuery or pure JavaScript?
One does not simply redirect using jQuery
jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.
window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
location.href
If you want to simulate an HTTP redirect, use location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
WARNING: This answer has merely been provided as a possible solution; it is obviously not the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution.
$(location).prop('href', 'http://stackoverflow.com')
Standard "vanilla" JavaScript way to redirect a page
window.location.href = 'newPage.html';
Or more simply: (since window is Global)
location.href = 'newPage.html';
If you are here because you are losing HTTP_REFERER when redirecting, keep reading:
(Otherwise ignore this last part)
The following section is for those using HTTP_REFERER as one of many security measures (although it isn't a great protective measure). If you're using Internet Explorer 8 or lower, these variables get lost when using any form of JavaScript page redirection (location.href, etc.).
Below we are going to implement an alternative for IE8 & lower so that we don't lose HTTP_REFERER. Otherwise, you can almost always simply use window.location.href.
Testing against HTTP_REFERER (URL pasting, session, etc.) can help tell whether a request is legitimate.
(Note: there are also ways to work-around / spoof these referrers, as noted by droop's link in the comments)
Simple cross-browser testing solution (fallback to window.location.href for Internet Explorer 9+ and all other browsers)
Usage: redirect('anotherpage.aspx');
function redirect (url) {
var ua = navigator.userAgent.toLowerCase(),
isIE = ua.indexOf('msie') !== -1,
version = parseInt(ua.substr(4, 2), 10);
// Internet Explorer 8 and lower
if (isIE && version < 9) {
var link = document.createElement('a');
link.href = url;
document.body.appendChild(link);
link.click();
}
// All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
else {
window.location.href = url;
}
}
There are lots of ways of doing this.
// window.location
window.location.replace('http://www.example.com')
window.location.assign('http://www.example.com')
window.location.href = 'http://www.example.com'
document.location.href = '/path'
// window.history
window.history.back()
window.history.go(-1)
// window.navigate; ONLY for old versions of Internet Explorer
window.navigate('top.jsp')
// Probably no bueno
self.location = 'http://www.example.com';
top.location = 'http://www.example.com';
// jQuery
$(location).attr('href','http://www.example.com')
$(window).attr('location','http://www.example.com')
$(location).prop('href', 'http://www.example.com')
This works for every browser:
window.location.href = 'your_url';
It would help if you were a little more descriptive in what you are trying to do. If you are trying to generate paged data, there are some options in how you do this. You can generate separate links for each page that you want to be able to get directly to.
<a href='/path-to-page?page=1' class='pager-link'>1</a>
<a href='/path-to-page?page=2' class='pager-link'>2</a>
<span class='pager-link current-page'>3</a>
...
Note that the current page in the example is handled differently in the code and with CSS.
If you want the paged data to be changed via AJAX, this is where jQuery would come in. What you would do is add a click handler to each of the anchor tags corresponding to a different page. This click handler would invoke some jQuery code that goes and fetches the next page via AJAX and updates the table with the new data. The example below assumes that you have a web service that returns the new page data.
$(document).ready( function() {
$('a.pager-link').click( function() {
var page = $(this).attr('href').split(/\?/)[1];
$.ajax({
type: 'POST',
url: '/path-to-service',
data: page,
success: function(content) {
$('#myTable').html(content); // replace
}
});
return false; // to stop link
});
});
I also think that location.replace(URL) is the best way, but if you want to notify the search engines about your redirection (they don't analyze JavaScript code to see the redirection) you should add the rel="canonical" meta tag to your website.
Adding a noscript section with a HTML refresh meta tag in it, is also a good solution. I suggest you to use this JavaScript redirection tool to create redirections. It also has Internet Explorer support to pass the HTTP referrer.
Sample code without delay looks like this:
<!-- Place this snippet right after opening the head tag to make it work properly -->
<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->
<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.example/"/>
<noscript>
<meta http-equiv="refresh" content="0;URL=https://yourdomain.example/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
var url = "https://yourdomain.example/";
if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
{
document.write("redirecting..."); // Don't remove this line or appendChild() will fail because it is called before document.onload to make the redirect as fast as possible. Nobody will see this text, it is only a tech fix.
var referLink = document.createElement("a");
referLink.href = url;
document.body.appendChild(referLink);
referLink.click();
}
else { window.location.replace(url); } // All other browsers
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->
But if someone wants to redirect back to home page then he may use the following snippet.
window.location = window.location.host
It would be helpful if you have three different environments as development, staging, and production.
You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.
JavaScript provides you many methods to retrieve and change the current URL which is displayed in browser's address bar. All these methods uses the Location object, which is a property of the Window object. You can create a new Location object that has the current URL as follows..
var currentLocation = window.location;
Basic Structure of a URL
<protocol>//<hostname>:<port>/<pathname><search><hash>
Protocol -- Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname -- Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port -- A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname -- The path gives info about the specific resource within the host that the Web client wants to access. For example, stackoverflow.com/index.html.
query -- A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash -- The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components
hash -Sets or returns the anchor portion of a URL.
host -Sets
or returns the hostname and port of a URL.
hostname -Sets or
returns the hostname of a URL.
href -Sets or returns the entire
URL.
pathname -Sets or returns the path name of a URL.
port -Sets or returns the port number the server uses for a URL.
protocol -Sets or returns the protocol of a URL.
search -Sets
or returns the query portion of a URL
Now If you want to change a page or redirect the user to some other page you can use the href property of the Location object like this
You can use the href property of the Location object.
window.location.href = "http://www.stackoverflow.com";
Location Object also have these three methods
assign() -- Loads a new document.
reload() -- Reloads the current document.
replace() -- Replaces the current document with a new one
You can use assign() and replace methods also to redirect to other pages like these
location.assign("http://www.stackoverflow.com");
location.replace("http://www.stackoverflow.com");
How assign() and replace() differs -- The difference between replace() method and assign() method(), is that replace() removes the URL of the current document from the document history, means it is not possible to use the "back" button to navigate back to the original document. So Use the assign() method if you want to load a new document, andwant to give the option to navigate back to the original document.
You can change the location object href property using jQuery also like this
$(location).attr('href',url);
And hence you can redirect the user to some other url.
Basically jQuery is just a JavaScript framework and for doing some of the things like redirection in this case, you can just use pure JavaScript, so in that case you have 3 options using vanilla JavaScript:
1) Using location replace, this will replace the current history of the page, means that it is not possible to use the back button to go back to the original page.
window.location.replace("http://stackoverflow.com");
2) Using location assign, this will keep the history for you and with using back button, you can go back to the original page:
window.location.assign("http://stackoverflow.com");
3) I recommend using one of those previous ways, but this could be the third option using pure JavaScript:
window.location.href="http://stackoverflow.com";
You can also write a function in jQuery to handle it, but not recommended as it's only one line pure JavaScript function, also you can use all of above functions without window if you are already in the window scope, for example window.location.replace("http://stackoverflow.com"); could be location.replace("http://stackoverflow.com");
Also I show them all on the image below:
Should just be able to set using window.location.
Example:
window.location = "https://stackoverflow.com/";
Here is a past post on the subject: How do I redirect to another webpage?
Before I start, jQuery is a JavaScript library used for DOM manipulation. So you should not be using jQuery for a page redirect.
A quote from Jquery.com:
While jQuery might run without major issues in older browser versions,
we do not actively test jQuery in them and generally do not fix bugs
that may appear in them.
It was found here:
https://jquery.com/browser-support/
So jQuery is not an end-all and be-all solution for backwards compatibility.
The following solution using raw JavaScript works in all browsers and have been standard for a long time so you don't need any libraries for cross browser support.
This page will redirect to Google after 3000 milliseconds
<!DOCTYPE html>
<html>
<head>
<title>example</title>
</head>
<body>
<p>You will be redirected to google shortly.</p>
<script>
setTimeout(function(){
window.location.href="http://www.google.com"; // The URL that will be redirected too.
}, 3000); // The bigger the number the longer the delay.
</script>
</body>
</html>
Different options are as follows:
window.location.href="url"; // Simulates normal navigation to a new page
window.location.replace("url"); // Removes current URL from history and replaces it with a new URL
window.location.assign("url"); // Adds new URL to the history stack and redirects to the new URL
window.history.back(); // Simulates a back button click
window.history.go(-1); // Simulates a back button click
window.history.back(-1); // Simulates a back button click
window.navigate("page.html"); // Same as window.location="url"
When using replace, the back button will not go back to the redirect page, as if it was never in the history. If you want the user to be able to go back to the redirect page then use window.location.href or window.location.assign. If you do use an option that lets the user go back to the redirect page, remember that when you enter the redirect page it will redirect you back. So put that into consideration when picking an option for your redirect. Under conditions where the page is only redirecting when an action is done by the user then having the page in the back button history will be okay. But if the page auto redirects then you should use replace so that the user can use the back button without getting forced back to the page the redirect sends.
You can also use meta data to run a page redirect as followed.
META Refresh
<meta http-equiv="refresh" content="0;url=http://evil.example/" />
META Location
<meta http-equiv="location" content="URL=http://evil.example" />
BASE Hijacking
<base href="http://evil.example/" />
Many more methods to redirect your unsuspecting client to a page they may not wish to go can be found on this page (not one of them is reliant on jQuery):
https://code.google.com/p/html5security/wiki/RedirectionMethods
I would also like to point out, people don't like to be randomly redirected. Only redirect people when absolutely needed. If you start redirecting people randomly they will never go to your site again.
The next paragraph is hypothetical:
You also may get reported as a malicious site. If that happens then when people click on a link to your site the users browser may warn them that your site is malicious. What may also happen is search engines may start dropping your rating if people are reporting a bad experience on your site.
Please review Google Webmaster Guidelines about redirects:
https://support.google.com/webmasters/answer/2721217?hl=en&ref_topic=6001971
Here is a fun little page that kicks you out of the page.
<!DOCTYPE html>
<html>
<head>
<title>Go Away</title>
</head>
<body>
<h1>Go Away</h1>
<script>
setTimeout(function(){
window.history.back();
}, 3000);
</script>
</body>
</html>
If you combine the two page examples together you would have an infant loop of rerouting that will guarantee that your user will never want to use your site ever again.
var url = 'asdf.html';
window.location.href = url;
You can do that without jQuery as:
window.location = "http://yourdomain.com";
And if you want only jQuery then you can do it like:
$jq(window).attr("location","http://yourdomain.com");
This works with jQuery:
$(window).attr("location", "http://google.fr");
# HTML Page Redirect Using jQuery/JavaScript Method
Try this example code:
function YourJavaScriptFunction()
{
var i = $('#login').val();
if (i == 'login')
window.location = "Login.php";
else
window.location = "Logout.php";
}
If you want to give a complete URL as window.location = "www.google.co.in";.
Original question: "How to redirect using jQuery?", hence the answer implements jQuery >> Complimentary usage case.
To just redirect to a page with JavaScript:
window.location.href = "/contact/";
Or if you need a delay:
setTimeout(function () {
window.location.href = "/contact/";
}, 2000); // Time in milliseconds
jQuery allows you to select elements from a web page with ease. You can find anything you want on a page and then use jQuery to add special effects, react to user actions, or show and hide content inside or outside the element you have selected. All these tasks start with knowing how to select an element or an event.
$('a,img').on('click',function(e){
e.preventDefault();
$(this).animate({
opacity: 0 //Put some CSS animation here
}, 500);
setTimeout(function(){
// OK, finished jQuery staff, let's go redirect
window.location.href = "/contact/";
},500);
});
Imagine someone wrote a script/plugin with 10000 lines of code. With jQuery you can connect to this code with just a line or two.
So, the question is how to make a redirect page, and not how to redirect to a website?
You only need to use JavaScript for this. Here is some tiny code that will create a dynamic redirect page.
<script>
var url = window.location.search.split('url=')[1]; // Get the URL after ?url=
if( url ) window.location.replace(url);
</script>
So say you just put this snippet into a redirect/index.html file on your website you can use it like so.
http://www.mywebsite.com/redirect?url=http://stackoverflow.com
And if you go to that link it will automatically redirect you to stackoverflow.com.
Link to Documentation
And that's how you make a Simple redirect page with JavaScript
Edit:
There is also one thing to note. I have added window.location.replace in my code because I think it suits a redirect page, but, you must know that when using window.location.replace and you get redirected, when you press the back button in your browser it will not got back to the redirect page, and it will go back to the page before it, take a look at this little demo thing.
Example:
The process: store home => redirect page to google => google
When at google: google => back button in browser => store home
So, if this suits your needs then everything should be fine. If you want to include the redirect page in the browser history replace this
if( url ) window.location.replace(url);
with
if( url ) window.location.href = url;
You need to put this line in your code:
$(location).attr("href","http://stackoverflow.com");
If you don't have jQuery, go with JavaScript:
window.location.replace("http://stackoverflow.com");
window.location.href("http://stackoverflow.com");
On your click function, just add:
window.location.href = "The URL where you want to redirect";
$('#id').click(function(){
window.location.href = "http://www.google.com";
});
Try this:
location.assign("http://www.google.com");
Code snippet of example.
jQuery is not needed. You can do this:
window.open("URL","_self","","")
It is that easy!
The best way to initiate an HTTP request is with document.loacation.href.replace('URL').
Using JavaScript:
Method 1:
window.location.href="http://google.com";
Method 2:
window.location.replace("http://google.com");
Using jQuery:
Method 1: $(location)
$(location).attr('href', 'http://google.com');
Method 2: Reusable Function
jQuery.fn.redirectTo = function(url){
window.location.href = url;
}
jQuery(window).redirectTo("http://google.com");
First write properly. You want to navigate within an application for another link from your application for another link. Here is the code:
window.location.href = "http://www.google.com";
And if you want to navigate pages within your application then I also have code, if you want.
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
JavaScript is very extensive. If you want to jump to another page you have three options.
window.location.href='otherpage.com';
window.location.assign('otherpage.com');
//and...
window.location.replace('otherpage.com');
As you want to move to another page, you can use any from these if this is your requirement.
However all three options are limited to different situations. Chose wisely according to your requirement.
If you are interested in more knowledge about the concept, you can go through further.
window.location.href; // Returns the href (URL) of the current page
window.location.hostname; // Returns the domain name of the web host
window.location.pathname; // Returns the path and filename of the current page
window.location.protocol; // Returns the web protocol used (http: or https:)
window.location.assign; // Loads a new document
window.location.replace; // RReplace the current location with new one.
In JavaScript and jQuery we can use the following code to redirect the one page to another page:
window.location.href="http://google.com";
window.location.replace("page1.html");
ECMAScript 6 + jQuery, 85 bytes
$({jQueryCode:(url)=>location.replace(url)}).attr("jQueryCode")("http://example.com")
Please don't kill me, this is a joke. It's a joke. This is a joke.
This did "provide an answer to the question", in the sense that it asked for a solution "using jQuery" which in this case entails forcing it into the equation somehow.
Ferrybig apparently needs the joke explained (still joking, I'm sure there are limited options on the review form), so without further ado:
Other answers are using jQuery's attr() on the location or window objects unnecessarily.
This answer also abuses it, but in a more ridiculous way. Instead of using it to set the location, this uses attr() to retrieve a function that sets the location.
The function is named jQueryCode even though there's nothing jQuery about it, and calling a function somethingCode is just horrible, especially when the something is not even a language.
The "85 bytes" is a reference to Code Golf. Golfing is obviously not something you should do outside of code golf, and furthermore this answer is clearly not actually golfed.
Basically, cringe.
Javascript:
window.location.href='www.your_url.com';
window.top.location.href='www.your_url.com';
window.location.replace('www.your_url.com');
Jquery:
var url='www.your_url.com';
$(location).attr('href',url);
$(location).prop('href',url);//instead of location you can use window
Here is a time-delay redirection. You can set the delay time to whatever you want:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Your Document Title</title>
<script type="text/javascript">
function delayer(delay) {
onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
}
</script>
</head>
<body>
<script>
delayer(8000)
</script>
<div>You will be redirected in 8 seconds!</div>
</body>
</html>

Php mysqli likes without page reload [duplicate]

This question already has answers here:
Update data on a page without refreshing
(4 answers)
Closed 6 years ago.
I have some post and like button with code:
Like
Now In the likes.php I have some Get coding for userid and postid to find which user liked which post and to store it into database. It works good but it reload page. It goes to likes.php and if it is successful it header back to home page or any other I want to. Now my question is how can I do it without reloading a page should I include likes.php code into page where are the posts and like buttons. And use a <a ref=""></a> if it is possible that way? Or if somebody have a better explanation he can post it as well.
Yes because you used the code ahref tag and this is how it is supposed to work.If you dont want it to reload try using AJAX.This is not the complete answer but you need to make that work through ajax only.You will find a lot of videos and demos regarding it.
Check this Example:
http://www.w3schools.com/ajax/ajax_php.asp
Update:
Mainfile.php
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<?php
session_start();
$userid=$_SESSION['userid'];
?>
<div id="like">
Like
<!-- here id should be different for every post .I would prefer using post id to this ahref id because i would use that to detect what post it is actually. -->
</div>
</html>
<script type="text/javascript">
function likeclick(element)
{
var postid=element.id;
var userid=<?php echo json_encode($userid);?>;
//You can use different methods to pass variable to javascript.I used this one because it is easy to implement
//it has some cons to it .Do check for that on google also.
//http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript
//Check this link for more.
$.ajax({
type:'POST',
url:'getlike.php',
data:{"userid":userid,"postid":postid},
success : function(content)
{
$('#like').html(content);
//This gets the html content from the getlike page and displays in the div on this page.
//Note:I have used .html which replaces any previous content inside the 'like' div.
})
}
</script>
getlike.php
<?php
require 'connect.inc.php'; //This make a connection to the database
$userid=$_POST['userid'];
$postid=$_POST['postid'];
$statement=$mysqli->prepare("select `likes` from `posts` where `postid`=?");
$statement->bind_param("s",$postid);
$statement->execute();
$result=$statement->get_result();
while($row=$result->fetch_assoc())
{
$likes_on_this_post=$row['likes'];
}
$likes_on_this_post=$likes_on_this_post+1; //Added one like more.
$statement=$mysqli->prepare("update `posts` set `likes`=?");
$statement->bind_param("s",$likes_on_this_post);
$statement->execute();
echo "+".$likes_on_this_post;
//This echo is actually the main thing.When this page runs through ajax the response is given back to the calling object
//What goes with response are the html contents on this page as well as whatever i echo on this page.
//Considering this example i have only echoed the no of likes and it doesn't contain any sort of html content so only the echoed element goes.
?>

how to get share buttons to use the current URL?

<a href="http://www.linkedin.com/shareArticle?url=MY_URL" class="in-share-button" target="_blank">
<img src="my_img" alt="linkedin share button" title="Share on Linked In" /> </a>
This is currently my share button. I want it to share the url that's currently in the address bar, and not a fixed preset url like it does atm.
I found
<?php $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; echo $url; ?>
what seems to fit my needs. But when I change "MY_URL" with this it just creates a link to the main page of my website.
The URL it SHOULD display looks like "www.myurl.de/#/id_of_a_post".
I feel like the # is the problem. . .
can you provide me any help with this?
You cannot read the hash portion of the URL in your server side code. The part that follows # is never sent to the server by the browser. So if you're trying to tackle this issue with PHP, you won't get the behavior that you're are expecting.
It looks like you're relying on static links to perform the sharing. I can only answer for Google+, but with Google+ you have two options:
Use the Google+ widget rather than a static link and do not specify the HREF parameter:
<div class="g-plusone" data-annotation="none"></div>
<!-- Place this tag after the last +1 button tag. -->
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
When the href is not specified and you do not specify a canonical URL, the widget falls back to default to the URL value that comes from document.location.href, which will be your visitor's current page, including the hash portion of the URL.
Use JavaScript to rewrite the URLs in your links to append your current hash location, for example, lets assume that you placed all your social links into a div with class "sharing" and then you need to modify all the hrefs within that div using jQuery:
var hash = document.location.hash;
// Loop through each link in the sharing div
$('.sharing a').each(function(){
// Append the hash to the end of each already populated URL
$(this).attr('href', $(this).attr('href') + encodeURIComponent('#' + hash));
});
It just worked another way.
My friend created a script that saves the ID of the individual posts:
(function(){
var numbers = document.URL.match(/\d+/g);
if(numbers != null){
$('#right-col').addClass('shown').removeClass('hidden');
$('#left-col').addClass('colPositioning');
$('#right_'+numbers).addClass('shown1');
;}
}());
Afterwards I was able to use:
<img src="img_src">
The trick about it was to replace the # with the "%23". I think it's called encodedURI.
What do you guys think about this solution?
The share might not work exactly the way you think it will. You're using the anchor part of your URL to link to a specific place on your page, and probably using some javascript to then process that and load new or different information, or display/hide other parts of the page, depending on the value of that anchor.
While this works for people who visit your website, it won't work for bots that visit your website (such as the bots used by Facebook and Google+, although I don't know if Linkedin does this as well) which try to get a snippet of information to show as a preview. So while the link itself might work, the preview shown on the website will almost certainly not reflect the contents of the anchored URL.

Calling JQuery .load after html redirect

I am writing an application that I want to make more user friendly by removing the amount of clicks needed to navigate.
At the moment pages are loaded like so:
<a class='pageloader' name='page1.html'>Page 1</a>
<script>
$('.pageloader').click(function(){
// Load the page that the user clicked on by taking the name property and appending it to includes/
$('.content').load("pages/" + this.name);
});
</script>
Basicly this takes the name of the clicked link and replaces the content div's content with whatever is inside the file that matches the name property.
Now my only problem is that I can't redirect people to pages using HTML because the only page that has proper styling is index.php.
Obviously I am now redirecting people to index.php after an action is finished, but I would like to redirect them to a specific page.
I've thought about calling
$('.content').load('pages/edit-plein.php');
(This code is inside a .php script that writes to a file)
But that only gives me an error since it cannot find the .content div.
Would anyone know a good method to redirect a user to the page I want?
As far as i understand you want to make shure the right content gets loaded (inside that div) when you share the link to a specific subpage on your site, but can only share a link of your index.php because of its styling.
I would suggest you add a variable to your URL, i.e. like
index.php?page=edit-plein
then get that var with PHP and create a JS call to your pageloader, like this:
<?php
if ( $_GET['page'] != '' ) {
echo '<script>$(".content").load("pages/'. $_GET['page'] .'");</script>';
}
?>
This is not a good way for links:
<a class='pageloader' name='page1.html'>Page 1</a>
Maybe you can try this:
Page 1
Page 2
And JS must be like this:
$('.pageloader').click(function(){
$('.content').load("pages/" + $(this).attr('id') + ".html");
});
I hope this solves your problem.

Pass value to PHP file using JavaScript and receive new set of values from PHP to JavaScript and display in Browser

I have a page called test.html. This HTML page will contain 2 JavaScripts file. I need to pass a variable value to a PHP file using the first JavaScript file. The user can copy this javascript on as many pages as he wants for displaying output.
The PHP file that receives the variable from the JavaScript file retrieves some data from database depending upon the variable's value. This retrieved value can contain HTML content. This PHP file will always reside on my server.
All of the retrieved content (from the PHP file) needs to be passed to the second JavaScript file so that the data can be displayed in browser. This JS file will need to stay together with the first JS file in order for the data to be displayed.
So I have this:
JavaScript File
<script type= "text/javascript" src="http://www.myserver.com/custom_script.php?unique_id=12"></script>
PHP FILE
//custom_script.php
<?php
$unique_id= (int)$_GET['unique_id'];
$res = db_res(" SELECT col1, col2, col3, .... col10 FROM table WHERE unique_id = $unique_id
LIMIT 1 ");
$rows = mysql_fetch_array($res);
?>
<div id="1"><?php echo $rows['col1']; ?></div>
<div id="2"><?php echo $rows['col2']; ?></div>
<div id="3"><?php echo $rows['col3']; ?></div>
.
.
.
<div id="10"><?php echo $rows['col10']; ?></div>
I need to send all the HTML above from the PHP file to the second JavaScript file so that the output can be displayed. Please note that the CSS styling is also applied using Div ID, so I am expecting those styles would show up too. Please note that there may be more than 10 columns, so an efficient way of passing data is highly appreciated.
So what would be the easiest and the best way to send all the HTML data from the PHP file in one go to the 2nd javascript file residing in test.html page, so that the HTML data can be displayed in test.html file?
EDIT 1:
I apologize to everyone if my question has been confusing. I just thought of an example and hence wanted to add it my edit. I hope you are all aware of what Google Analytics (GA)(or any other Website Visits Stats Tracker) does. Right? You register for a Analytics account and Google gives you a piece of JS code that you copy and paste in your website. And after couple of days, you can login into your GA account to see the stats. Correct? What I am trying to do here is just the same.
Users come to MY WEBSITE and register for an account and I give them JS files that they can paste in their website. The only difference between GA and my website is that GA is personal to you and no one else, but you, the account holder can see it. Whereas in my case, your data can BE SEEN by others as well, as long as you include the JS file on your website. Because users can't just take my PHP file and run it on their server, I am trying to access MY PHP file by giving the full path to it in the JS file.
For example:
<script type= "text/javascript" src="http://www.myserver.com/custom_script.php?unique_id=12"></script>
This is not an actual JS file, rather it is just a medium for my custom_script.php script to receive the unique_id of the user, query MY database and send back the HTML data related to this requesting user. And I am stuck with this part. Hope this clairifies what I am trying to do.
The jQuery documentation actually gives an example almost identical to your problem:
http://api.jquery.com/jQuery.get/
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
This will get an html page and insert it under an html element with class 'result'.
You should be able to replace your php script url and specify where the output should be displayed.
If youre worried about conflicts with other jQuery instances, have a read of this:
http://api.jquery.com/jQuery.noConflict/
If you want to write your own AJAX handler check out this page :
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Essentially you will do something like this (taken from the link):
function reqListener () {
console.log(this.responseText);
};
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();
I think its worth doing if you've never had to do it before, but you will open yourself up to lots of potential problems that have been solved for you.
Ideally if I were doing this I would return json from the handler and allow the user to decide how to display it, but thats your call.

Categories