Modify the current URL with dynamic values in php using Javascript - javascript

I'm trying to get current URL, modify a couple of string parameters in the URL with dynamic values, and redirect to that modified URL.
I have obtained current URL with 'location.href' : http://dev.azima.com/#mt.everest2017#/page-content/about-us/5
I tried to replace last two parameters (strings) 'about-us' and '5' with $page->slug and $page->id respectively.
I tried string manipulation methods, but couldn't figure out the problem.

If the URL pattern is fixed, it can be achieved in PHP with help of explode/implode functions. Like This:
$url = "http://dev.azima.com/#mt.everest2017#/page-content/about-us/5";
$url_arr = explode("//", $url);
$url_arr[count($url_arr) - 1] = $page->id;
$url_arr[count($url_arr) - 2] = $page->slug;
$url = implode("//", url_arr);
header("location:$url");
Hope this helps.

Let me write what I understood of what you want to do:
User is going to an URL
Some code is done in PHP
User is redirected to a new URL through Javascript
If there is no user interaction, it is possible without any other step.
But you really need to understand that PHP is a server side language and
Javascript is a client side language.
You can't pass content from JS to PHP without any AJAX call.
Solution
So basically, you will do that
<?php
/** YOUR PHP CODE WITH $_GET $_POST RETRIEVALS OR WHATEVER **/
$javascript = '(function() {
// your redirection
})();';
?><html>
<head>
</head>
<body>
Your HTML here
<script>
<?php echo $javascript; ?>
</script>
</body>
</html>
To be honest, I would rather consider this type of code which is pure PHP, faster and easier:
<?php
/** YOUR PHP CODE WITH $_GET $_POST RETRIEVALS OR WHATEVER **/
if(!empty($redirectIsNeeded)) {
header('Location: http://foo.bar');
}
?><html>
<head>
</head>
<body>
Your HTML here
</body>
</html>
You can also consider, if a load is not needed and only want to "display" the right URL in URL bar, using history.pushstate.

Related

fingerprintjs2 to php variable

I like to get fingerprint as php variable, I get the follow but do not want to work.
<p>fingerprint2: <strong id="fp2"></strong></p>
<script src="/fingerprintjs2/fingerprint2.js"></script>
<script>
var fp2 = new Fingerprint2();
fp2.get(function(result) {
console.log(result);
$("#fp2").text(result);
});
</script>
$myphpvar = "<script>document.write(fp2.get());</script>";
echo $myphpvar;
That's really not how PHP works at all. PHP cannot process client side JavaScript. If you want access to client side information in PHP then you should probably put it in a form and post it to another page in PHP. There are many good tutorials on PHP forms, such as this one.
The Javascript is run after the PHP has completed. Client side VS server side code. I have solved this in the past by running the PHP within a PHP file that renders an image. This method is often referred to pixel tracking.
Here are the basics, you need to pass your variables in Javascript to a PHP file that renders an image:
document.write("<img src=fingerprint.php?x="+x+"&y="+y+" width=1 height=1>");
In the above case it passed Javascript variables x and y to the PHP image.
Then the fingerprint.php script looks like:
<?php
header("Content-type: image/png");
session_start();
$x = $_REQUEST['x'];
$y = $_REQUEST['y'];
$_SESSION['x'] = $x;
$_SESSION['y'] = $y
// SHOW THE IMAGE
$im = imagecreatefrompng("fingerprint.png");
imagepng($im);
imagedestroy($im);
?>
The png image can be anything you want as it will just be a 1 x 1 image on your final screen. You now have the Javascript variables in your PHP. As the code starts a session you could write the variables to a session and collect them later in another script, or write them to a database and recover later. Try with my simple example to ensure you have it working then expand from there.
There are lots of ways you can send data from JavaScript back serverside
set a cookie and read it in the next request
request further content by injecting a script / IMG / iframe tag (but not using document.write) adding the fingerprint in the query of the url
make an AJAX request
add a hidden input to a form on the page - requires the user to navigate out of the page using the form

Getting URL including # value

I need to grab the value of URL after #. For example in this URL: http://url.com/index.php#33/1032. I just need to get "33/1032" But PHP seems to not allow any value after #. So I used JS. Here is how I am doing it.
<script>
function curState(){
var state = window.location.hash.substr(1);
return document.write(state);
}
</script>
Now that I have the url I need to pass this portion of the URL 33/1032 back again to the url after POST call. Here is how I am trying to do:
<?php
$copyVal = " <script> curState(); </script> ";
echo $copyVal; // displays value in browser perfectly
?>
Now,
<form action="index.php#<?php echo $copyVal ?>" method = "post" >
// form code
</form>
After submit it displays
http://url.com/index.php# <script> curState(); </script>
But I want
http://url.com/index.php#33/1032
Please help.
Thank You.
Use jQuery -
<form action="index.php" method = "post" id="myform" >
The jQuery will be -
var state = window.location.hash.substr(1);
$('#myform').attr('action', $('#myform').attr('action') + '#' + state);
FIDDLE
Instead of PHP code, use JavaScript:
copyVal = curState();
copyVal = "index.php#"+copyVal;
function for_action()
{
document.getElementById('myForm').action = copyVal;
}
Now, In form tag:
<form id="myForm" onsubmit="for_action();" method = "post" >
First figure out your problem:
PHP is a server side scripting language. Server-side scripting is distinguished from client-side scripting where embedded scripts, such as JavaScript, are run client-side in a web browser, but both techniques are often used together.
So codes under <?php tag will run first in server side and give output as HTML and/or JavaScript and/or CSS respectively. So
<?php
$copyVal = " <script> curState(); </script> ";
echo $copyVal; // displays value in browser perfectly
?>
this code will run in the server and first assign <script> curState(); </script> as a string in php variable $copyVal. And secondly, when you echo $copyVal, this will output <script> curState(); </script> in your source code.
AS <script> curState(); </script>
is a Javascript code as well so curState(); function call your javscript function you have define earlier. On that function you have used document.write to write something in your browser, so you see the output in your browser. But if you see the source code of your page, you can still see that there is no specific Hash value but a JavaScript code [<script> curState(); </script>].
As similar as that when you print your php variable $copyVal in
<form action="index.php#<?php echo $copyVal; ?>" method = "post" >
this variable output the JavaScript code rather than any hash value.
Second, How to do this?
You can do this in many way with php or JavaScript. If you want to do this with php, one simple way is that, first parse_url your current url. and than get the fragment value. like-
$url=parse_url("http://url.com/index.php#33/1032");
echo $url["fragment"]; //This variable contains the fragment
If you are not sure, how to grab the current url in php see Get the full URL in PHP
you can take the link and use the function substr..it does what you want after a specific sign:
$id = substr($url, strrpos($url, '#') + 1);
this should do the job

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.
Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.
So I have a PHP webpage where I POSTed some variables to:
DOCTYPE HTML
...
<?php
$id = $_POST["id"];
$name = $_POST["name"];
?>
...
HTML code with some usage of PHP variables
javascriptFunction()
end page
Then in a separate javascript file I have:
var markerlocation = '<?php echo $point; ?>';
function javascriptFunction () {
alert("markerlocation");
});
This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.
I can delete this when done.
Sincere thanks for any help.
My way:
Declare a Array to store variable for passing variable to JavaScript
Encode the Array to JSON in php
Decode the JSON String from php and store as a JavaScript variable
PHP
<?php
//You may declare array for javascript
$jsVal = array(
'user_name' => 'Peter',
'email' => 'peter#gmail.com',
'marker_location' => '102,300'
);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>
Separated javascript file
alert(phpConfig.marker_location);
You can try it
You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)
Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.
On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

How to call PHP script from within JavaScript

I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.

Send JS variable to PHP on-click

I have this JS function and I'm looking for the simplest way to send a variable to php and have php return an array to my JS. I have the second part down I just need help sending the variable. Here's my function:
function myEvent(){
//console.log(uploaded);
var length = uploaded.length;
var content = document.getElementById("Profile");
if(length == 0){
content.innerHTML = '<p style="text-align:center"><b> You uploaded no events. </b></p>';
}
else {
content.innerHTML = " ";
for(var i=0; i<length;i++){
var entry = document.createElement('li');
var EID = uploaded[i][0];
entry.innerHTML= ''+uploaded[i][1]+'​';
content.appendChild(entry);
}
return false;
}
}
I want to be able to send EID which is a unique ID to a PHP script every time I click the link.
Any help? I'm using Jquery but I'm not too familiar with it. If there's an option using JS alone I would really appreciate it.
You can do that using Ajax. There's also another really simple way to send data to a php script on any server (same domain or not) while making that php script interact with your page
first you create a script tag:
var tag = document.createElement('script');
the src of that tag will be the url of the php script that will receive the variable:
var myVar = 'foo';
tag.src = '/path/to/my/script.php?variable='+myVar;
you add the script tag to the dom to request it
document.getElementsByTagName('head')[0].appendChild(tag);
on the server side the php script receives the variable and does whatever it should do with it, and optionally it can echo any javascript that will run on the page afterwards:
<?php
echo "alert('".$_GET['variable']."')";
that's pretty much it, WARNING, be aware that this is just a simple example, to implement something like this on a production site you need to make sure that doing so won't open your site to XSS attacks, code injection etc... how to do that is beyond what is being discussed here but be aware
Make sure you view this using firebug, or anything similar in order to see the returned results, in the jquery done function you can then do data[0], etc for the arrays
html
<!DOCTYPE html>
<html>
<head>
<title>JQuery Test</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="myjs.js"></script>
</head>
<body>
<button id="sendData">Send Data</button>
</body>
</html>
JS
$(document).ready (function (){
$("#sendData").on ("click", function (){
jQuery.ajax ({
url: "index.php",
type: "POST",
data: {returnArray: 1}
}).fail (function (){
console.log ("failed");
}).done (function (data){
console.log (data);
});
});
});
PHP
if (isSet ($_POST ['returnArray']))
{
$a = array ("a", "b", "c", "d");
header('Content-type: application/json');
echo json_encode ($a);
exit;
}
I am sure you can figure this out... show some effort.. and don't be afraid to ask if you still don't understand.. just as long as you try.
Use JavaScript's XMLHttpRequest to send a message to the server running PHP. When the PHP script responds, the XMLHttpRequest object will let you know and you'll be able to grab the XMLHttpRequest.responseText.
It would be a good idea to have PHP respond with JSON, which it can do easily. Then you can parse the responseText with JavaScript's JSON.parse function and just use it.
The following two articles will show you how to use the standard objects.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
http://www.php.net/manual/en/function.json-encode.php
You'll just have to be sure you don't try talking to a different website than the one your page is loaded from, unless you want to learn all about cross domain requests.

Categories