Javascript problem when receiving variable with date

Asked

Viewed 153 times

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>

In the var_dump correctly appears the variable $dta_inicial, but in javascript when 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 the correct 3, only it does not go when the same date, formatted, appears a numbers 0.2324934334 ...

  • 2

    What is the date format? If it’s XX/XX/XX, I think JS is splitting with the date, so 0.232xxxx... Try to put <?php echo "$dta_inicial"; ?>... with "...

  • 1

    @gustavox I think you correctly identified the problem. But the quotes are to be inside the echo or out? And by the way, in case they need to be simple quotes, otherwise it will conflict with the calling code.

  • 1

    You’re right @mgibsonbr, the quotes got in the wrong place, and they should be really simple... it was inattention, but this is not even a question I thought I could answer, because as much as I identified the problem, I wouldn’t know how to explain the solution (though the quotes were right hehe) with the perfection you made. + 1 Think of my comment above as an enthusiast’s ball roll to the expert (who he knew was right behind). : -) +1

1 answer

4


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

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

You’ll 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 numerical expression (such as pointed out by gustavox in the comments) and then evaluated (resulting in a number).

If you want 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; ?>'))

Which 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 pass the data as the same string and deal with the format in the Javascript function itself (unless you find it easier to do this in PHP, your criterion):

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

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


Updating: if what you want in Javascript is a string (i.e. a representation of a date, not an object Date), but in a different format than its variable $dta_inicial has, it is necessary to convert string to date and then format the date again to string.

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

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

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

Or on the Javascript side:

var arr = data.split('/');
var str = arr[2] + "-" + arr[1] + "-" + arr[0];
  • I did something like this and now returns the date correctly, Gracias to your code, but it came in a strange date format with more things. There would be no way I could send the date in the American format already using the new date, that year-month-day, which I add, which with it already resolves me ?

  • @Andrésilveiramachado Yes, try doing date_format($dta_inicial, 'm/d/Y') before sending by echo. Also works(ria) with 'Y-m-d', the difference is that for some reason that I do not know Javascript will treat the first as local time and the second as UTC (which in my opinion does not make much sense, because it is only date and not date+time...).

  • Only I only advise making one new Date(...) if you really need of an object Date - otherwise, if it’s just to display for example, just pass the string, even if formatted by the above method.

  • With Date(...) it worked, but I want it to either send in the American format Y-m-d or the javascript at the time you receive it, turn this format, I think your second tip does not solve, because back to the problem I imagine.

  • So... if what you have is a string, and what you want is a string (but in another format), then you’ll have a time to convert that string to a date and then format that date again into a string. This can be done in PHP (via DateTime::createFromFormat and format) or in Javascript (via new Date and .toIsoString().slice(0,10)).

  • I will try to form the code there at the time it receives the javascript

  • The codiso that Voce inserted in "Update" did not work, but I’ll try this new date on the javascript side, I’m taking the date in the day/month/year format and giving a new date in php and sending, then it arrives in javascript with Thu Jan 01 ..., is that Thu jan 01... I’m trying to break there for day/month/year.

  • Also did not work this last Datetime, I returned exactly to the starting point: 0.034398432478 .... &#xA;&#xA;Código:&#xA;&#xA;$fecha = new StdClass;&#xA;$fecha->innertext = $dta_inicial;&#xA;&#xA;$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);&#xA;if ( false===$eventDate ) {&#xA; die('invalid date format');&#xA;}&#xA;$dado = $eventDate->format('Y-m-d'); $dado = $eventDate->format(’d/m/Y'); ________________________ .

  • Here is the code: http://pastebin.com/ZNth06Xv

  • I’m really confused, PHP is not my strong... I think I’ll leave it to someone with more experience to answer. :(

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.