开发者

Sending select option with jquery to a php file...?

开发者 https://www.devze.com 2023-04-11 21:03 出处:网络
I have looked for 2 days to find out how to send a variable with jquery to php. I have searched for over 100 posts on stackoverflow, i tried multiple examples. But i just get it done. So i really hope

I have looked for 2 days to find out how to send a variable with jquery to php. I have searched for over 100 posts on stackoverflow, i tried multiple examples. But i just get it done. So i really hope someone over here would be kind enough to help me find out what i am doing wrong....

<?php
print_r(json_decode($_POST['country']));
?>
<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script type="text/javascript">

        $(function() {
            $('#country').change(function() {

                var country = $('#country').val();

                $.ajax({
                    type: 'POST',
                    data: country,
                    dataType: 'json',
                    url: 'timezone/timezone.php',
                })

                alert("Country: " + country);

            });
        });

    </script>

</head>

<body>

    <form method = "post" name="form1">
        <select name="country" class="country" id="country"&g开发者_如何学Pythont;
            <option value="NL">Nederland</option>
            <option value="BE">Belgie</option>
        </select>
    </form>

</body>

</html>


Data either needs to be a query string, or an object with a key and value.

As an object

           $.ajax({
                type: 'POST',
                data: { 'country': country }
                dataType: 'json',
                url: 'timezone/timezone.php', 
                success: function( data ) {
                   var element = data.wrap('<div />');  // wrap the response in a div 
                   $('body').append( element );   // append it to the body
                }
            }); 

as a query string

            $.ajax({
                type: 'POST',
                data: 'country='+country, 
                dataType: 'json',
                url: 'timezone/timezone.php'
            }); 

Whenever in doubt always go to the jquery docs. Here is an excerpt from the ajax documentation.

The data option can contain either a query string of the form key1=value1&key2=value2, or a map of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.

0

精彩评论

暂无评论...
验证码 换一张
取 消