Forgive me for asking a seemingly obvious question, but all of my searching is turning up guides on how to create POST values with JS, not how to grab (and utilize) them.
What I want to do:
step1.php -- form POSTing to step2.php
step2.php -- also a form, JS grabs one particular POST value and does some work with it, then updates this new form accordingly
for reasons not worth getting into, the process needs to be a 2 step//2 page process.
The obvious solution is just to do something like:
<script type="text/javascript">
function damn_ugly () {
var shameful = <?php echo $_POST['desiredDatum']; ?>;
do more stuff...
}
</script>
but that seems a bit dirty to me.
Is there a better way? or is that really how I'm supposed to do it?
var postData = <?php echo json_encode($_POST); ?>;
You can obviously change that to include only certain fields from $_POST by passing a custom array to json_encode.
var desiredDatum = <?php echo json_encode($_POST['desiredDatum']); ?>;
There is no nicer way to do it - and using json_encode ensures no matter what's contained in the POST variable nothing will break (at least not during the assignment).
That is how you are supposed to do it, JavaScript cannot access the POST values in another way.
Offcourse you can make it a bit more beautiful: have your php-script put the POST variables in an array, and print the array in JSON format. Now your javascript has the array.
POST values are being sent to the server. Once submitted only the server can work with those values. Your example is pretty much the only option you have to "access" POST values that have been sent to the server in the previous request.
JS has no access to POST values, it can only retrieve GET values. However, since you're using a PHP script and you're able to pass the data to JS - why not give your JS functions data in JSON format? You can use PHP's json_encode function to encode all POST values to JSON that you can use then easily in your JS code.
Try this
On second step Page 2:
Set hidden text box on page:
<input type='hidden' name='text1' id = 'text1' value='<?php echo $_POST['desiredDatum']; ?>' />
Now if you use jQuery the wirite below given code
$(document).ready(function() {
var shameful = $('#text1').val();
});
if not using jQuery Then
var shameful = document.getElementById('text1').value;
I hope this is what you are looking for.
Related
I have the below code, and I'm not sure if it even works. Basically, I want to do a like system, whereby when I click on the link, it adds a +1 to the user's likes.
I've tried so hard to read up but I just don't get anything, and I found a code similar below.
When I clicked on the link, it does process my insert.php page, but I don't know how to get the variable values...
What should I do? I'm not sure if the code structure below is correct...
Thanks!
<script>
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
</script>
<div id="current-salary">
<a id="salary" onClick="insertSalary();">+1</a>
</div>
The variable will be in your php script as $_POST['salary']
The value of salary is passed as part of the post method in jquery.
So you can do:
$.post('script.php', {salary: 100}, function(data){...});
and this will pass the value 100 to your php script as the salary value.
In php the $_POST and $_GET hashes contain the data that you pass with a given request. In jquery $.post, $.get $.ajax create requests and take data hashes to build the data you want to pass with the request.
While this may work, I would recommend separating your logic from your website by putting the javascript in an external file and then link your HTML page to it.
I would also advise against declarative event binding which you have done by specifying onClick="insertSalary()".
jQuery provides a method to pro-grammatically assign functions to events using the on method. So for your code, you could use:
$('#current-salary').on('click', insertSalary());
Let's say I have set up a PHP variable like this:
$phpurl = $_GET["url"]
where url value will be from GET variable query. The value of "url" will be some sort of html page link with some content like "myContent.html" I want to load.
How can I get this "url" value, which I have assigned to the variable "$phpurl"
and use it in the Ajax/Jquery page load request?
$('.content').load(' ** need the value of "$phpurl" to be placed here ** ');
Hope the question is clear. I am pretty new into programming. Thanks.
EDIT:
$('.content').load('<?php echo json_encode($phpurl); ?>');
will do
You'll want to take precaution to escape the value properly
<script type="text/javascript>
var url = decodeURIComponent('<?php echo rawurlencode($phpurl) ?>');
</script>
Or you could try something like https://github.com/allmarkedup/jQuery-URL-Parser
// requires no PHP at all!
var url = $.url(window.location).attr('url');
$('.content').load(url);
As a generic rule you should properly escape variables when you move them between two realms, in this case from PHP to JavaScript.
This is especially true if you don't have full control over the variable contents, such as those coming from $_GET, $_POST, etc.
This is a safe bet, using json_encode() to form a proper JavaScript value:
$('.content').load(<?php echo json_encode($phpurl); ?>);
I've built an online community in Drupal with a homepage that is kind of like the Facebook wall. You see the 25 most recent posts, with the two most recent comments below those posts. There is also a textarea right below those comments so that you can quickly post a new comment on a particular post.
These Facebook-style posts have a lot of functionality built into them via JavaScript. Clicking a "view all comments" link directly below a post makes an AJAX call that grabs all the comments for that post and displays them right below it. You can also mark posts as helpful, as the solution to your question, edit comments inline, etc. All of these actions require AJAX requests, which means that the JavaScript making the request needs to know essential information such as the Node ID (the unique identifier of the post), the comment ID (unique identifier of the comment), etc.
My initial implementation had these pieces of essential data sprinkled all over the posts, making it more complicated to write the JS that needed to find it. So my second implementation simply output all this data into a JSON-compatible string in the main wrapping element of each post. While this made it much easier for the JS to find the data it needed, writing JSON as a string is a pain (escaping quotes, no line breaks).
So now I have a third idea, and I'm looking for feedback on it prior to implementation. The idea is to create a single global JS Array for all these posts that contains within it objects that hold the data for each post. Each element in that array would hold the necessary data needed for the AJAX calls. So it would look something like this:
Facebook-style post template
<div class="post" data-postindex="<?php echo $post->index; ?>">
<!-- lots of other HTML for the post -->
</div>
<script type="text/javascript">
globalPostArray.push({
nid: <?php echo $post->nid; ?>,
authorID: <?php $post->authorID; ?>,
//etc. etc. etc.
});
</script>
The result of the above code is that when a link gets clicked that requires an AJAX request, the JS would simply traverse the DOM upwards from that link until it finds the main .post element. It would then grab the value of data-postindex in order to know which element in globalPostArray holds the data it needs.
Thoughts? I feel like there must be some standard, accepted way of accomplishing something like this.
I've never heard of a standard way to "pass" information between PHP and Javascript, as they are a server-side and client-side language, respectively. I would personally use a hybrid of your second and third solutions.
Store the post id in a data-postindex attribute (data attributes are newish, and the "right" way to store small amounts of data). But I would still just use a JSON array for the rest, as storing lots of data in data-attributes (and escaping them!) is potentially problematic. PHP has a json_encode function that takes care of all the escaping and such for you - just build a PHP array (say, $postdata) like you normally would, and then throw this in your post template:
<script type="text/javascript">
globalPostArray.push(<?php echo json_encode($postdata) ?>);
</script>
Where $postdata is something like the following:
$postdata = array(
'nid' => 5,
'authorId' => 45
...etc...
);
It should be easy enough to generate such an array from your existing code.
I wrote a blog post a while back about my implementation of this kind of thing, but it sounds like all you need is a pointer at json_encode.
The most reliable way to pass any PHP variable to JavaScript is json_encode.
<script type="text/javascript">
var something = <?php echo json_encode($var); ?>;
</script>
You can't pass closures and resources, but otherwise anything's game for being passed.
I would store the data inside the element:
<div class="post" data-postindex="<?php echo $post->index; ?>"
data-nid="<?php echo $post->nid; ?>"
data-authorID="<?php echo $post->authorID; ?>">
...or storing a complete JSON-string in 1 data-attribute:
<div data-data="<?php echo htmlentities(json_encode($somedata));?>">
My answer is about the same as the other guys but more detailed. I usually do it like this and i think is the best approach: (of course you can grab the data using ajax, but depends on the context)
somefile.html
<html>
<head>..</head>
<body>
html code
<script>
window.my_data = <?php echo json_encode($my_php_var); ?>
</script>
</body>
</html>
somefile.js
$(function() {
window.myitem = new myClass(window.my_data);
});
var MyClass = function(init_data) {...}
Hi I'm trying to create a form that is pre-populated partially by form on the page before. This information is then posted to this new page which is then populated into the form on that page ready to be submitted to a database.
I'm not a developer so I'm a little out of my depth here but this is what I've got so far..
<?php
$amount = $_GET['text-386'];
$covermultiple = $_GET['radio-30'];
$coverdobd = $_GET['d-o-b-d'];
$coverdobm = $_GET['d-o-b-m'];
$coverdoby = $_GET['d-o-b-y'];
?>
<script type="text/javascript">
document.getElementById('text-386').value = "<?=$amount ?>";
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = "<?=$coverdobd ?>";
document.getElementById('d-o-b-m').value = "<?=$coverdobm ?>";
document.getElementById('d-o-b-y').value = "<?=$coverdoby ?>";
</script>
I'm getting the values out of the URL ok and can echo these out on the page fine, I've even managed to get text-386 appearing in the right place.. so thats one down! The problem is the other elements are a radio button with two options (radio-30) and a 3 select boxes with the days, months and year of a persons d-o-b. These two bits are populating.
So in a nutshell..
How can I use javascript (if that is the right way) alongside php to populate the radio and select tags on this form using information in the url? In a preferably straight forward way as possible?
The url if it helps is..
http://localhost/datacapture/form-page/radio-30=Just+for+me&text-386=%C2%A340%2C000&d-o-b-d=11&d-o-b-m=05&d-o-b-y=1977
Thats obviously on the local build I'm using so that URL wouldn't work for you. I can see when googling lots of help posting information using radio/select etc but I want the opposite, how do you populate these from a url?
Any help would be a lifesaver
I would just use an if statement.
if( $covermultiple == "Just for me" ) {
// Echo the field here
echo "<input type='radio' name='radio-30' value='Just for me' checked />";
}
else {
// Check for the next case
}
Put this block right where you want the radio buttons to be.
I think something like that will work fine. I don't think you really need javascript in this case unless you really want to use it.
Im not 100% I have an answer, but I cant find comment anywhere so I will joust post here.
You cant access PHP variables from Javascript. PHP is running on the server, and Javascript is inside users browser.
Javascript cant get $_GET and $_POST variables like PHP.
Now what you can do is this, with JavaScript you can get document.location string that holds your current URL. And you can brake that URL into parts. To do that use this function:
<script>
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
alert($_GET['someVar']); // This will alert content of someVar
Now you can use $_GET['vars'] to get your URL vars.
And then you dont use PHP to echo variable content, you joust prepare your URL so it holds variables you want to insert into your form.
So you do something like this:
<script type="text/javascript">
document.getElementById('text-386').value = $_GET['urlVar'];
document.getElementByName('radio-30').checked = "checked";
document.getElementById('d-o-b-d').value = $_GET['urlVar'];
document.getElementById('d-o-b-m').value = $_GET['urlVar'];
document.getElementById('d-o-b-y').value = $_GET['urlVar'];
</script>
So as you can see, JavaScript takes variables from URL, using function $_GET you wrote and it dosent needs PHP. And you can use PHP to generate URLs you need, so they contain variables you can get using $_GET javascript function.
Hope this answers your question.
here is the code??
posting code:
$.post('get.php',{selected:"aaaa"},function(return){alert(return);});
when i check the values of "selected" value using
<?php
$r=$_POST['selected'];
echo $r;
?>
is displays the value "aaaa" correctly..
this code works fine...
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";
when we echo the value"welcome" it is stored in the variable answer.and i could print that...
but when i put like this....
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";
an empty value is stored in answer... and nothing gets displayed....
whether specifying $r inside " " is not right... how to specify that......
Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:
javascript in original page:
$.post('get.php',{selected:"aaaa"},function(data){
var answer = data;
});
get.php
<?php
$r=$_POST['selected'];
echo $r;
?>
$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).
Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:
var answer = <?php echo json_encode($_POST['selected']); ?>
Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.