简体   繁体   中英

Why, when I pass the selected option in a dropdown to PHP through Ajax, does it always give me the first option?

This is my code:

<html>
    <head>
        <script>
            comenzar = function(){
                document.getElementById('gene').onclick = xmlhttpPost("generador.php");
            }

            xmlhttpPost = function(strURL){
                xmlHttpReq = false;
                self = this;
                self.xmlHttpReq = new XMLHttpRequest();
                self.xmlHttpReq.open('POST', strURL, true);
                self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                self.xmlHttpReq.onreadystatechange = function(){
                    if(self.xmlHttpReq.readyState == 4){
                        update(self.xmlHttpReq.responseText);
                    }
                }
                self.xmlHttpReq.send(getquerystring());
            }

            getquerystring = function(){
                form = document.getElementById('formu');
                combi = document.getElementById('sele').options[document.getElementById('sele').selectedIndex].value;
                qstr = "tres=" + escape(combi);
                return qstr;
            }

            update = function(resu){
                document.getElementById('tag').innerHTML = resu;
            }
            window.onload = comenzar;
        </script>
    </head>

    <body>
        <form id=formu>
            <select id=sele>
                <option>C</option>
                <option>v</option>
            </select>
            <button id=gene><p>generate</p></button>
        </form>
        <p id=tag></p>
    </body>
</html>

//generador.php
<?php
    echo( "tu combinacion" . $_POST['tres'] );
?>

The problem is not the getting of the value. The hook are these two things:

document.getElementById('gene').onclick = xmlhttpPost("generador.php");

...you may think that you set something to be executed to the onclick-Event of the button, but you don't. This function will be executed immediately, not onclick.

You should write it that way:

document.getElementById('gene').onclick = function(){xmlhttpPost("generador.php");}

The other problem:

The default type of a <button> is submit, so if you click on the button, the form will be sent. You can either set the type of the button to "button" or cancel the submitting of the form via JavaScript, otherwise your Ajax request is useless, because the form will be sent (and the page reloaded).

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