I am getting a value with php $_GET[], and I want to pass it as the value of a simple html input element. I know I can do it like this:
<?
$value = $_GET['value'];
echo '<input type="text" name="value" value="'.$value.'" />';
?>
But is there any way to separate the php from html, giving the value to the textbox without echoing it?
I would like to create the textbox as regular html element, and only use php in the part where I set its value.
The answer of Iaroel was more practical for my purposes, but I liked the way that the accepted answer covered many concerns - I think it will be more valuable to other users.
You don't want an error when the $_GET['value'] becomes undefined.
<?php
$value = isset($_GET['value'] ? $_GET['value'] : '');
?>
<input type="text" name="value" value="<?php echo $value; ?>">
But be mindful with malicious data that can be inserted in $_GET['value'] so you've got to apply proper sanitation to $value
With regards to "Getting $_GET['value'] without PHP"
You can get it without PHP script by creating a small javascript function:
<script type="text/javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
</script>
What the hell was that regular expression? It's just a matter of matching pattern from the URL.
Now, you can use this $_GET() method to assign the value to that textbox. In this example, I used jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('input[name="value"]').attr('value', $_GET('value'));
});
</script>
Now your HTML code will be as simple as this:
<input type="text" name="value">
Reference: http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/
If you don't wish to echo anything inside HTML, use Ajax call to get values.
$.ajax({
url: 'getValues.php',
type: 'post',
dataType: 'json',
success: function (json) {
if (json) {
$.each(json, function (k, v) {
$(k).val(v);
});
}
}
});
[PHP]
echo json_encode(array('#first_input_id' => 'val1', '#second_input_id' => 'val2', '.some_classes' => 'val5'));
Or if values are static, you can use local json file.
Do you mean like this?
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?php echo $value;?>" />
Or this (not advised):
<?php
$value = $_GET['value'];
?>
<input type="text" name="value" value="<?= $someVar ?>" />
But i would suggest looking into a template engine for example http://www.smarty.net/
If your php configuration allows short tags you can do this:
<input type="text" name="value" value="<?=$_GET['value'];?>" />
you can try without echo
<?php $value = $_GET['value'];?>
<input type = "text" name = "value" value="<?= $value; ?>" />
If its really important for your project, ideally you want to separate your php code from your html tags. this can achieve by using some template engine.
There are some well known options available, best if you check and see which one suites your use-case best.
Mustache
Smarty
and of course Twig
You can use PHP Heardoc option. find the link here.
http://www.hackingwithphp.com/2/6/3/heredoc
Related
I send an array from form1.php to form2.php
<input id="hidden_all_headers" type="hidden" name="hidden_all_headers" value="<?php echo json_encode($all_headers_array); ?>">
The inspector in form1.php
<input id="hidden_all_headers" type="hidden" name="hidden_all_headers" **value="[" region","countries_of_origin","visits_in_milions","receipts_in_milions_euro","nights_in_thousands","expenditure_per_visit_euro","cost_per_night_euro","average_length_of_stay"]"="">**
which looks fine.. but in form2.php
--html
<input id="hidden_all_headers" type="hidden" name="hidden_all_headers" value="<?php echo json_decode($_POST['hidden_all_headers'],true); ?>">
</html>
<script type="text/javascript">
var obj = "<?php echo json_decode($_POST['hidden_all_headers']) ?>";
for(var i=0; i<obj.length; i++){
alert(obj[i]);
};
</script>
inspector for form2.php
-- html
<input id="hidden_all_headers" type="hidden" name="hidden_all_headers" **value=""**>
--script
**var obj = "";**
for(var i=0; i<obj.length; i++){
alert(obj[i]);
};
$('#hidden_all_headers').val(obj);
Can you please help me out why I can not receive the array in form2.php?
Thanks in advance.
The attributes for your HTML elements should be generally wrapped in double-quotes (there are exceptions but the don't really apply here). JSON data wraps all its keys and values in double quotes too, so your value attribute looks like this:
value="[" region","countries_of_origin","visits_in_milions","receipts_in_milions_euro","nights_in_thousands","expenditure_per_visit_euro","cost_per_night_euro","average_length_of_stay"]"=""
See how the double-quotes open and close in all the wrong places. The browser can't make sense of it, so it ignores it all.
Your solution is to encode the JSON data using htmlspecialchars()
value="<?php echo htmlspecialchars(json_encode($all_headers_array)); ?>"
So, starting from this:
{"val1":"value1","val2":"value2"}
This will give you a value attribute like this:
value="{"val1":"value1","val2":"value2"}"
To use that value in your PHP you need to decode it with htmlspecialchars_decode() and then json_decode() it.
However, I would question why you're sending this data to a form in the first place. Doesn't your server already know what it should be getting?
This question already has answers here:
passing php variable from controller to javascript function in the head of a view
(3 answers)
Closed 3 years ago.
I have the following defined in my controller:
$data['is_amazon'] = $product->is_amazon;
$data['is_ebay'] = $product->is_ebay;
Directly below this in the controller I'm calling a .js file (jQuery).
$this->template->add_js('js/is_ebay_amazon_prouct_edit.js');
I'd like to access these php variables in my jQuery script, I've tried this approach:
var amazon = '<?php echo $is_amazon; ?>';
var ebay = '<?php echo $is_ebay; ?>';
jQuery(document).ready(function($) {
alert(amazon);
//alert(ebay);
});
Although this just displays my physical text in the alert, I.E:
<?php echo $is_ebay; ?>
What is the best approach here in terms of making these variables accessible in my jQuery?
Try this
do one thing.. you need to create two input hiddent field in view.
like this
<input type='hidden' id="amazon" value="<?php echo $is_amazon; ?>" />
<input type='hidden' id="ebay" value="<?php echo $is_ebay; ?>" />
and call that value in you jquery lik this
$(document).ready(function() {
//alert($('#amazon').val()+" "+$('#ebay').val());
console.log("amazon"+$('#amazon').val());
console.log("ebay"+$('#ebay').val());
});
now it will work for u.. try it.
There is no option to directly assign php variables to javascript. To do this you need to assign assign it to html elements like,
<input type="hidden" id ="amazon" value="<?php echo $is_amazon; ?>">
We can get the value in jquery from this html element by using this code,
var amazon = $('#amazon').val();
For security reasons the php variables cant assign to javascript variables.
Try this
<input type="hidden" id="fromAmazon" value="<?php echo $is_amazon ?>"/>
<input type="hidden" id="fromEbay" value="<?php echo $is_ebay ?>"/>
In jquery
After loading jquery.js file
jQuery(document).ready(function($) {
var amazon = $("#fromAmazon").val();
var ebay = $("#fromEbay").val();
console.log("amazon",amazon);
console.log("ebay",ebay);
});
I'm trying to pass some array values to php page using ajax.this is what i have tried.but it's pass only first value.not all the array values
<script>
function priceSub() {
var price = $("input[name='price[]']").val();
$.post('db_price.php', {prce:price});
return true;
}
</script>
<?php //this is come from another page
$itemCount = count($_POST["price"]);
for($i=0;$i<$itemCount;$i++) {
$op_name=$_POST['price'][$i];
?>
<input type="hidden" value="<?php echo $price;?>" name="price[]" id="price"/>
<?php
}
?>
<input type="submit" value="Submit" class="suboderbtn" onclick="return priceSub();"/>
Try using json_encode function :
$.post('db_price.php', <?php json_encode($_POST["price"]); ?>);
do like this for posting an array field
Javascript
<script>
function priceSub() {
var price = $('input#price').serialize();
console.log(price)
$.post('db_price.php', {price:price});
return true;
}
</script>
html
<input type="hidden" value="10" name="price[]" id="price"/>
<input type="hidden" value="20" name="price[]" id="price"/>
First thing you need to know is you have {prce:price}, and use $_POST['price'], so you need to use {price:price} instead.
However, you can send any number of data via ajax:
$.post('db_price.php', {price:price, data1: "value1", data2: "value2",...});
And you can access data with $_POST['price'] , $_POST['data1'], $_POST['data2'],... in the php script.
Edit:
You can't send array with one text field. For do this, you can separate values with , and explode the value in the php script. For example the text field value may be "value1, value2". Now you can use this code for getting array value :
$prices = explode(",", $_POST['price']);
Now $prices[0] will be "value1" and $prices[1] will be "value2".
What I want to do is that only when I click on a div with id="$project['slug']", it will load the iframe inside that div.
So, i removed the src attribute from the iframe, and add it on onclick event.
I have this in my HTML/PHP:
<div class="box" id="<?=$project['slug']?>" onclick="load_frame();">
<iframe id="frame_<?=$project['slug']?>" frameborder="0"></iframe>
</div>
Js:
function load_frame() {
id = location.hash.replace('#', '');
var source = "<?php echo $project['video']; ?>";
$('#frame_'+id).attr("src", source);
}
Unfortunately, when I inspect the iframe it shows: src="<?=$project['video']?>" instead of the value that the variable holds.
Do you have any idea what i am doing wrong?
thank you!
jQuery is a client side language and have access only to the DOM elements once they have been rendered. So what you need to do is store $project['video'] variable in a hidden field and then using the id of that field get access to the rendered data.
Also, i noticed that you should use <?php instead of <?
You may try something like this.
<div class="box" id="<?php echo $project['slug']; ?>">
<iframe id="frame_<?php echo $project['slug']; ?>" frameborder="0"></iframe>
<input type="hidden" id="<?php echo $project['slug']; ?>" value="<?php echo $project['video']" />
</div>
Then in jQuery do:
$(document).ready(function(){
$('.box').click(function(){
var slug = $(this).attr('id');
var source = $('input#' + slug).val();
$('iframe#' + slug).attr("src", source);
});
});
add hidden input on html page
<input type="hidden" id="hidsource" value="<?php echo $project['video']" />
edit your function in js like this
function load_frame() {
id = location.hash.replace('#', '');
$('#frame_'+id).attr("src", $('input#hidsource').val());
}
hope this will work
You might not have the shorthand syntax enabled on the server. Try standard PHP instead:
<?php echo $project['slug']; ?>
I am creating a form and am just looking for more efficient ways to do things. What I have so far is:
<p><input type="text" name="transmission" value="" /></p>
<p><input type="text" name="model" value="<?=$model;?>" /></p>
So some of them will have a value already set, and some will be blank. What I want to do is see if the form has been set, and if it has then use $_POST['name'] as the value, if not then use either blank or use the previous variable I have.
<p><input type="text" name="name" value="<?php if isset($_POST['submit'])) { echo $_POST['name']; } else { echo ""; } ?>" /></p>
But there has to be a shorter way to do that.
IF anyone could point me in the direction I would really appreciate it.
Thank you!
You can define variables in beginning of your script before HTML output, for example:
$name = isset($_POST['submit']) ? $_POST['name'] : null;
in your html section you can print $name without worrying it was not defined
<p><input type="text" name="name" value="<?php echo $name ?>" /></p>
Also if $_POST['submit'] does not contain any value you are more likely to receive FALSE statement. To avoid such issues use array_key_exists
Like Nazariy said, you should avoid as much PHP in the template as possible.
In fact, you should have in your template already prepared variables only.
So, in your code have something like this
$FORM = array();
$form_fields = array('name','sex');
foreach($form_fields as $fname) {
if (isset($_POST[$fname])) {
$FORM[$fname] = htmlspecialchars($_POST[$fname]);
} else {
$FORM[$fname] ='';
}
}
and then you have smooth and neat template:
<p><input type="text" name="name" value="<?=$FORM['name']?>" /></p>
Without going into the reasons not to use <p> to structure your forms, there's not much that can be done besides removing the else.
<p><input type="text" name="name" value="<?php if isset($_POST['name'])) echo $_POST['name']; ?>" /></p>
Shorthand <?=$_POST['name'] ?: ''?>
Use the php error control operator: #.
<?php
$posted_text = #$_POST['posted_text'];
echo $posted_text
?>
If the POST variable is set, it will be echo-ed out. If not, nothing will show up.
You could try this...
$_POST['submit'] ? echo $_POST['name'] : echo '';
I'm using a boolean compare instead of the isset function (see link for table)
http://www.php.net/manual/en/types.comparisons.php
or an other option is...
echo ($_POST['submit'] ? $_POST['name'] : '');
<?= isset($_POST['submit'])? $_POST['name'] : ""; ?>
Is the shortest you'll get it, apart from say <?= $_POST['name']; ?> (if submit is not set name should be empty anyway) - you probably need to turn warnings off.
All that being said, this is very very poor practice and opens you up to cross site scripting (XSS). You should NOT be doing this. Even on an intranet, if an attacker ever owns a computer that has access to it they can use XSS to perform any actions the user can.
From your question and how much distaste you have for this type of echoing on screen I'd suggest you use some form of templating library such as Smarty. This allows your html code to look like this:
<p><input type="text" name="name" value="{name}" /></p>
I just saw this from wordpress coding standard. although they not encourage for the readability..
isset( $var ) || $var = some_function();
reference here