简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM