Michal Kotus Michal Kotus - 1 year ago 48
Ajax Question

post php variable in ajax (no jQuery)

I guess this is simple question, but not for me.
I have got simple calendar, where is only month:

<div id="calendar">
<?php
$month_num=date('m');
echo $month_num . " ";
echo '<span onclick="next(this.value);" value="' . $month_num . '";> &gt; </span>';
?>
</div>


my script is:

function next(str) {

xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("calendar").innerHTML = this.responseText;
}
};
xmlhttp.open("POST","test3.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("n=" + str);
}


and
test3.php
is:

<?php
if (isset($_POST['n'])) {
$n = $_POST['n'];
}
if (isset($n)) {
echo $n + 1;}
?>


Problem is,
$n
is undefined and result is "1" . I guess there should be some nice simple way how to post
$n
.

Thank you.

Answer Source

A span does not have a value attribute according to specifications. So you will have a hard time access it in javascript. Try using the data-* attributes for that.

echo '<span onclick="next(this.getAttribute(\'data-value\'));" data-value="' . $month_num . '";> &gt; </span>';

May I also suggest that, since you are posting, and relying on a click event, a button would be much more appropriate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download