Reputation: 767
I'm trying to pass an array from an included php file to a javascript (external too);
They both seems to work because: 1) if I try echo json_encode($array)
on the main page instead of passing it in the script, the output is correct;
2) if I copy and paste this output to the javascript, the script works correctly and add the elements as options of a Select tag.
But if I try to assign in Javascript
var arrayConduttori = <?php echo json_encode($array); ?>;
Like I've found in similar questions here on stackoverflow the whole script doesn't run, and nothing happens with the click event;
var clo; //clone della riga in modifica, se devo annullare operazione
//funzione al clikc per immettere entrega
$(document).on('click', "table td a[id^='entr']",function(){
//se ci sono altre righe in modifica le faccio ridiventare normali
$('tr.edita').removeClass('edita').replaceWith(clo);
// mi identifico la riga su cui devo lavorare
var riga=$(this).attr('id').substr(4,12);
var trriga='#tr'+riga;
//mi faccio la copia di backup della riga nella variablie clone
clo=$(trriga).clone();
//mi segno i dati che mi servono immettere automaticamente
var turno=$('#turn'+riga).text();
$(trriga).addClass('edita').html('<td id=form colspan=5><h2>Taxi '+riga.substr(1.11)+'</h2>' +
'Turno '+turno +
'<ul>' +
'<li>Conductor</label><select id=selcond></select></li>' +
'<li><label>Entrega</label><input type=text></li>'+
'<li><label>Ahorro</label><input type=text></li>'+
'<li><label>Gastos</label><input type=text></li>'+
'</ul></td>');
//aggiungo al campo Select le opzioni conduttori dall'array
var arrayConduttori = <?php echo json_encode($array);?>;
$.each(arrayConduttori, function(key, value) {
$('#selcond').append($("<option></option>").attr("value",key).text(value));
});
});
Upvotes: 0
Views: 120
Reputation: 2104
if you want to echo php variables it has to be in a .php
file.here in your case you are
echoing in a .js
page
php is run on server side and js is loaded from client side .so by the time you are loading .js file,
php is already executed in the server and output is printed in html page.so when u try
<?php echo json_encode($array); ?>
on client side it ll not work.the best way is to send it from server or create a js variable in main page before loading your external js file like this
var arrayConduttori = <?php echo json_encode($array); ?>;
and after this include your script
<script src='/your script'></script>
Upvotes: 1
Reputation: 1840
Hang on! If the JavaScript file is external, how would it know what $array actually is?
Upvotes: 0