javascript problem receiving variable with date

3
<td class="A8" style="text-align:center;">
    <?php
    $dta_inicial = $dados['data_inicial'];
    var_dump($dta_inicial);
    ?>
    <div class="B2" onclick="preencheform_edicaoJS(<?php echo $dados['etapa_projeto_id']; ?>,<?php echo $dados['etapa_id']; ?>,<?php echo $dados['dias_total']; ?>,<?php echo $dta_inicial; ?>)">
        <img src='resources/images/andremachado/editar.png' width='20' title='Editar' alt='editar' border = '0' />
    </div>
</td>

No var_dump appears correctly the $dta_inicial , but in javascript giving alert a wrong value appears.

function preencheform_edicaoJS(etapa_projeto_id,etapa_id,dias_total,data_inicial){
    alert(data_inicial);
}

But if I set the $ dta_initial = 3 ;, it sends right the 3, it just does not go when the date is even, formatted, it appears a numbers 0.2324934334 ...

    
asked by anonymous 17.12.2015 / 17:06

1 answer

4

If your variable $dta_inicial contains a string representing a date (ex: 17/12/2015 ) and you make a echo of that variable, then its contents will be inserted as such in the output. That is, this:

preencheform_edicaoJS(...,<?php echo $dta_inicial; ?>)

It will end up generating this:

preencheform_edicaoJS(...,17/12/2015)

And since JavaScript does not have a literal for dates, this will be interpreted as a numeric expression (such as #

If you want the JavaScript code to receive a date, an option would be to issue the code that creates a date:

preencheform_edicaoJS(..., new Date('<?php echo $dta_inicial; ?>'))

That works, but only if the date is in month / day / year format:

preencheform_edicaoJS(..., new Date('17/12/2015')) // Invalid Date

So I suggest simply passing the date as the same string and handling the format in the JavaScript function itself (unless you find it easier to do this in PHP, your criteria):

preencheform_edicaoJS(...,'<?php echo $dta_inicial; ?>')

(note the use of single quotes, not to conflict with the calling code, which uses double quotes - onclick="preencheform_edicaoJS(...)" )

Update: If what you want in JavaScript is a string itself (ie the impersonation of a date, not a Date object), but in a different format of its variable $dta_inicial has, it is necessary to convert from string to date and then format the date back to string.

This can be done "formal" (using methods that deal with dates in one or another language, such as pointed at comment ), but being a simple format you can also do manually, type like this:

$dta_array = explode("/", $dta_inicial);
$dta_transformada = $dta_array[2] . "-" . $dta_array[1] . "-" . $dta_array[0];
...
preencheform_edicaoJS(...,'<?php echo $dta_transformada; ?>')

(reverse the indexes 1 and 0 if the date is originally in month / day / year format)

Or on the JavaScript side:

var arr = data.split('/');
var str = arr[2] + "-" + arr[1] + "-" + arr[0];
    
17.12.2015 / 17:30