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?
Related
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 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
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 want to send a URL in a POST request in a variable called surl. How should I encode it in JavaScript and decode it in PHP? For example, the value of surl could be http://www.google.co.in/search?q=javascript+urlencode+w3schools.
EDIT
Sorry, I forgot to mention, it's not form submission but a ajax request.
You don't need to to anything. Send it as is. Browser and PHP will do all escaping and unescaping for you (if you use form.surl.value = surl; form.submit() and $_POST['surl']). Or you can just use the plain form without any JavaScript (if it fulfills your needs).
Replying henasraf's comment. Try this.
<form id="form" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"
onsubmit="this.via_js.value=this.via_plain_form.value;">
<input type="hidden" name="via_js"/>
<input type="text" name="via_plain_form" value="Paste you url here"/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if (isset($_POST['submit'])) {
var_export($_POST);
}
?>
For http://www.google.co.in/search?q=javascript+urlencode+w3schools, it outputs
array (
'via_js' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
'via_plain_form' => 'http://www.google.co.in/search?q=javascript+urlencode+w3schools',
'submit' => 'Submit',
)
Use encodeURIComponent(uri) (for encoding) and decodeURIComponent(uri) for decoding,
E.g (encoding).
var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
document.write(encodeURIComponent(uri));
Output
http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab
Decoding is left for the reader. :-)
Source: http://www.w3schools.com/jsref/jsref_encodeURIComponent.asp
As for PHP, it's urlencode() and urldecode().
How can I extract the value attribute of an input tag? Using SIMPLE HTML DOM
let me give you an example:
<form action="#" method="post" name="test_form" id="test_form">
Name<input type="text" name="name" value="NaMe"/><br />
Address<input type="text" name="address" value="AdDrEsS"/><br />
<input type="hidden" value="sayantest" />
</form>
I want to extract just the value of hidden type input tag, not the others.
You want to put the id (so you can access the value in javascript), as well as a name (if you want to access the value on the server) in the tag you wish to get the value from.
e.g.
<input type="hidden" name="test" id="test" value="sayantest" />
then your javascript is as simple as:
<script type="text/javascript">
var val = document.getElementById('test').value;
alert(val);
</script>
using SIMPLE HTML DOM
Do you mean the PHP library of that name?
If so, you'd have to choose a way to identify the input. If you can't change the markup to add an id or name on the hidden input you want, you'd have to come up with something like “get the first input with type hidden in the form”:
$html= new simple_html_dom();
$html->load('<html><body<form action="#" method="post" name="test_form" id="test_form">Name<input type="text" name="name" value="NaMe"/><br />Address<input type="text" name="address" value="AdDrEsS"/><br /><input type="hidden" value="sayantest" /></form></body></html>');
$input= $html->find('#test_form input[type=hidden]', 0);
$input->value;
The easiest way, as already mentioned, is to give your hidden input an id attribute and then use getElementById and then .value or .getAttribute('value') to select it.
Alternatively, if you want to get the values of all hidden inputs on the page, or can't inject your ID, you could use something like this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++){
if(inputs[i].getAttribute('type') == 'hidden'){
alert(inputs[i].getAttribute('value'));
}
}
Here is what I came up with... using exactly what you showed in your initial question. Note that all I did was echo the value of all input hidden, where test_form.htm is your original:
<?php
function scraping_form()
{
// create HTML DOM
$html = file_get_html('test_form.htm');
// get input hidden value
$aObj = $html->find('input[type="hidden"]');
foreach ($aObj as $hKey=>$hidden)
{
$valueAttribute = $hidden->value;
echo "*TEST* ".$hKey.": ".$valueAttribute."<br />";
}
// clean up memory
$html->clear();
unset($html);
return;
}
// -----------------------------------------------------------------------------
// test it!
// user_agent header...
ini_set('user_agent', 'My-Application/2.5');
scraping_form();
?>