how to pass a php values to javascript? - php

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.

Related

Using PHP variable and use it in Jquery/Ajax page load request

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); ?>);

PHP run in iframe

I created iframe where source is my PHP file, the file should display data from GET method the code is:
<?php
if (isset($_GET["phpMap"])){
var $response = $_GET["phpMap"];
echo $response;
}
?>
but when i run button that send data to that iframe nothing happens.
Plz correct your code as follow,
remove "var"
<iframe src="iframe.php?phpMap='google'" ></iframe>
in iframe.php put code
if (isset($_GET["phpMap"])){$response = $_GET["phpMap"]; echo $response; }
If data is sent using POST then you should update your code and change $_GET[] to $_POST[]
You also dont need to declare your variable like that outside of a Class.
$response = $_POST['phpmap'];
You can also troubleshoot by adding print_r['$_POST'] or print_r['$_GET'] at the top of the script to see what variables if any are coming over. Firebug is also good for capturing POST/GET transmissions and allowing you to see the values being passed back and forth.
You have to change the $_GET into $_POST then it should work with a button click.
If you need to send data from outside of the iframe into the iframe you need to make sure that you write query strings in theurl of the iframe source:
<iframe src="yourfile.php?var=someting"></iframe>
Like that you can recieve the valeue of $var in the script with
<?php $variable = $_GET['var'] ?>

Populating a form using a url - multiple input types

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.

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

grabbing POST values with javascript

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.

Categories