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.
Related
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
i have a html table and it has expandable row
but when i added json encode code to the javascript code. the html table row expand without the user interaction. when the page is loaded. it just expand. and i need to put the code in a sigle javascript because i need to use the data from other javascript function. hope my question is clear. sorry for my bad english
<script type='text/javascript'>//<![CDATA[
var tracknumberreceiveglobal;
$(document).ready(function(){
$("#report tr:odd").addClass("odd");
$("#report tr:not(.odd)").hide();
$("#report tr:first-child").show();
$("#report tr.odd").click(function(){
tracknumberreceiveglobal = $(this).closest("tr").find("td:eq(0)").text();
$(this).next("tr").toggle();
$(this).find('i').toggleClass('glyphicon-plus-sign').toggleClass('glyphicon-minus-sign');
});
});
function functiontwo() {
var tnum = <?php echo json_encode($_tempp1); ?>;
var tsign = <?php echo json_encode($_temppp1); ?>;
var signatoryidglobal = <?php echo json_encode($_SESSION['signatoryid']); ?>
}
</script>
this is the page looks like without json encode
this is the page looks like with json encode
The PHP function json_encode() returns a string (a JSON representation) and not an actual JavaScript object. You have to parse it in order to make use of the data passed through JSON.
var tnum = JSON.parse('<?php echo json_encode($_tempp1); ?>');
var tsign = JSON.parse('<?php echo json_encode($_temppp1); ?>');
var signatoryidglobal = JSON.parse('<?php echo json_encode($_SESSION['signatoryid']); ?>');
You can now access properties using dot notation or brackets.
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>
I have a php array:
$array = array(‘1234’=>”Acme Company”,
“4321”=>”CustomerX”,
”1056=>”CustomerY”,
”1058”=>”google”,
”1059”=>”Yahoo”,
”1060”=>”apple”);
I am attempting to create an autocomplete with this data. so step 1 is to iterate through in javascript.
var clients = '<?php echo json_encode($array);?>';
$.each(clients, function(i,el){
alert(i+","+el);
});
When i do this, I get the error:
Uncaught TypeError: Cannot use 'in' operator to search for '2847' in {“1234”:”Acme Company”,”4321”:”CustomerX,”1056”:”CustomerY”,”1058”:”google”,”1059”:”Yahoo”,”1060”:”Apple}
I can not figure out why. if i alert(clients), it looks like a good array..
Try it like this, you had error with passing php variable into your js var.
Now it`s iterating through all of the array elements.
<?php
$array = ['1234'=>'Acme Company',
'432'=>'CustomerX',
'1056'=>'Customer',
'1058'=>'google',
'1059'=>'Yahoo',
'106'=>'apple'];
$array = json_encode($array);
?>
<script type="text/javascript">
var clients = <?php echo $array; ?>;
console.log(clients);
$.each(clients, function(i,el){
alert(i+","+el);
});
</script>
Use clients = $.parseJSON(clients); before each ( and remove " ' from the numbers.
var client_parsed = JSON.parse(client);
and then use client_parsed
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);
});
});