Passing array value from html to javascript - javascript

Note: using the Laravel framework but the concept shouldn't be too different.
How would I go about passing my $data['method'] and $data['id] to javascript?
<div id="player" data-method="{{ $data['method'] }}" data-id="{{ $data['id'] }}"></div>
Data method and Data id are passed through a controller.
In javascript I've currently got
var method = "<?php echo $data-id[]>";
var id = "<?php echo $data-method[]>";
Which obviously don't work

To get the method:
var method = document.getElementById("player").getAttribute("data-method");
And to get the id:
var id = document.getElementById("player").getAttribute("data-id");

In addition to #chris97ong answer, if you use jQuery, then you can use such constructions:
var method = $('#player').data('method');
var id = $('#player').data('id');
But if you want to paste id and method values directly to javascript, then use:
var method = "<?php echo $data['id']>";
var id = "<?php echo $data['method']>";
Exactly like in your own way.

Jeffrey Way provides a nice plugin to pass variables to JavaScript in your controller: https://github.com/laracasts/PHP-Vars-To-Js-Transformer

You can pass array as
<?php
$array = array("a","b","c","d");
$json_str = json_encode($array);
?>
<a str='<?php echo $json_str; ?>' class="array_pass">Pass Value</a>
<script>
$(document).ready(function(e) {
$(".array_pass").click(function() {
var str = $(this).attr("str");
var array = jQuery.parseJSON(str);
alert(array[0]);
});
});
</script>

Related

Passing my PHP variable value to Js file

Hiii Everyone,
<script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script>
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
And I tried to get that passing value in recordmp3.js is
var student_id = this_js_script.attr('data-my_var_1');
var test_no = this_js_script.attr('data-my_var_2');
And also by
var student_id = "<?php echo $_GET['id'];?>";
var test_no = "<?php echo $_GET['test_no'];?>";
And my value is not passing correctly.Instead only '0' is passing In my index page I have some PHP variable value I need to pass that value to recordmp3.js file.Please help me to solve this issue.Thank you so much in advance.
I tried like below its working fine
<script src="../../record/recordmp3.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["<?php echo $id; ?>", "<?php echo $test_no; ?>"]);
MYLIBRARY.helloWorld();
</script>
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
window.id= _args[0];
window.test_no= _args[1];
}
};
}());
You need to convert these values to json array. You cannot directly assign the php values to JavaScript variables.
Hope this answer is useful. Please let me know if you find any difficulties on converting to json value.
.js files don't execute and compile the php files,so in order to access the php variables in javascript the file should be .php.
script.php
<?php
$foo = 'Hello cool';
?>
<script>
var foo ='<?php echo $foo ?>';
console.log(foo);
</script>
i hope this example will solve your issue

Passing Array From PHP to JQuery json_encode

I have an HTML form generated by php which has a dropdown of voucherproviders.
I want to select the provider and have this populate the form for editing.
Here is my JQuery code:
$(document).ready(function() {
$(document).on('change','#id_voucherprovider',function(){
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
//The value I have got from the drop down is....
var value = $('#id_voucherprovider option:selected').val();
var vendortext = $('#id_voucherprovider option:selected').text();
//so the voucher provider is
alert(vendortext);
$('.ftext input').val(vendortext);
$("textarea#id_vendornotes").val(voucher_providers[value]);
});
});
voucherproviders is not being passed into the JQuery despite the echo json_encode($voucher_providers); code working when inline with the php code.
It seems to return a null array. Can anyone see what is wrong?
Many Thanks
Dave
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
json_encode returns a string, unless it is parsed it will not be usable. Use JQuery .parseJSON and you should have better results. :)
var jsonString = <?php echo json_encode($voucher_providers); ?>;
var voucher_providers = $.parseJSON(jsonString);
try this (note the quotes):
var voucher_providers = JSON.parse('<?php echo json_encode($voucher_providers); ?>');
parse your json ex: obj = JSON.parse(data);
Hi please check the json format at below site:-
http://jsonlint.com/
and check if this is fine.

Problems in passing PHP array to JavaScript

I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?
Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>
Try like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>
You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

how to use javascript variable inside php in javascript function

I'm using JavaScript to redirect a page with dynamic parameter.
Here is the code, I had to use the PHP function inside JavaScript. It works but it isn't using the javascipt variable
<script type="text/javascript">
var $map = jQuery.noConflict();
$map(document).ready(function(){
$map("#map_search").click(function(){
var staffname = $map("#staffname").val();//alert(staffname);
var from = $map("#cdate_from").val();
var to = "<?php echo site_Encryption(from); ?>";alert(to);
var status = $map("#status").val();
window.location = "http://localhost/staff/booking.php?date="+to+"&tdate="+to;
var to = "<?php echo site_Encryption(from); ?>";alert(to);
Here I use the PHP function and "from" is JavaScript variable that I want to use.
You can do an ajax request, something like:
var from = blablah...;
$.getJSON("encryption.php", {from : from}, function (data)
{
alert(data.to);
});
encryption.php :
<?php
blabla...
echo json_encode(array("to" => site_Encryption($_GET["from"])));
?>
(It's a sample code, don't copy-paste, read some ajax tutorials ^^)
An alternative could be to make the encryption on client side.

Categories