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
Related
I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP
something like :
<?php
$phpVar = "<script> function jsFunc(){ return 'Hello world';} </script>";
?>
is that even possible? if no, is there a way to do same thing?
If Ajax is the only solution, how do I retrieve a value of an input and store it as a php variable?
I tried something like this and it doesn't work.
<input type=text value="hello" id="myInput">
<?php
$phpVar = "<script>
function jsFunc(){
var inputVal = $('#myInput').val();
return inputVal;
}
</script>";
?>
PHP runs at server side and JS in the browser (apart node and related technologies).
Only way you can do something similar would be do to render from PHP in your HTML a tag <script> </script> and add you JS function and executing it there.
Al thought I would definitely not suggest it.
you can store this string in variable. for php interpreter it will be just a text string, nothing else. but when browser receives this data, string will be recognized as js function.
UPDATE
in this case easiest way for send data from browser to server is use a form. there is many examples in the web how to do it.
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.
Im trying to pass a parameter inside function with on click to a script tag, btw I do not want to use the global $result. I only want to use it from the parameter.
Heres my code:
<?php
$results = [person1:{}] // a bunch of different people in array
while($result in $results) //pseudo code to get each person in results
<div>
<input type="button" value="Submit" onclick="changeConfirmed($result)">
</form>';
echo '</div>';
?>
<script>
function changeConfirmed(val){
$maj=val['major'];
alert("Your major is: " + major);
}
</script>
try this
passing php variable in onClick function
Your PHP variables only live on the server. They are completely separate from the JavaScript variables on the client. The only mechanism for passing values from the server to the client is through the contents of the web page (or through specially requested behind-the-scenes web content through AJAX).
By the way, You can convert this array into JSON and then pass this string to function.
Check this way:
<input type="button" value="Submit" onclick="changeConfirmed(json_encode($result))">
Without knowing what your "array" is and based upon what I can gather from the question, a "mockup" $result array could have the simple form of...
$result = [ 'major' => 'General' ];
And the form code simplified to the format...
<form>
<input type="button" value="Submit" onclick=changeConfirmed('<?= json_encode($result); ?>')>
</form>
Then the jQuery being (and I just beat this to death to get something working after scouring Google and trying lots of things... So it might not be the optimal way)
<script>
function changeConfirmed(val) {
var obj = $.parseJSON(val);
console.log(val);
var major = obj.major;
alert("Your major is: " + major);
}
</script>
Results in the alert stating that "Your major is General".
But I am gathering that you would be using something that uniquely identifies each input row like a number.
If I am way off track to what you are after, at least I learned another little trick. :)
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.