开发者

How to pass values of form input fields to a script using AJAX/jQuery?

My current code is like this.

index.php

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>

<select id="开发者_开发百科dropdown_id">
<option value="one.php">One</option>
<option value="two.php">Two</option>
</select>

<div id="workspace">workspace</div>

one.php

$arr = array ( "workspace" => "One" );
echo json_encode( $arr );

two.php

$arr = array( 'workspace' => "Two" );
echo json_encode( $arr );

JS

jQuery('#dropdown_id').live('change', function(event) {
    jQuery.getJSON($(this).val(), function(snippets) {
        for(var id in snippets) {
            // updated to deal with any type of HTML
            jQuery('#' + id).html(snippets[id]);
        }
    });
});

Above code is working perfectly. When I select One from dropdown then one.php is loaded in workspace DIV using JSON. When I select Two then two.php is loaded in workspace DIV.

What I want to do next:

Now I want to add another dropdown in index.php:
<select id="myinput" name="alpha">
  <option value="a">a</option> 
  <option value="b">b</option>
  <option value="a">c</option>
  <option value="b">d</option>
</select>

When user select any option from first dropdown then that script(value) should be loaded with the value of second dropdown in workspace DIV.

For example:

When I select One from first dropdown then:

one.php

$arr = array ( "workspace" => $_GET['alpha'] ); // Should load 'a'
echo json_encode( $arr );

Now When I select b from second dropdown then:

one.php

$arr = array ( "workspace" => $_GET['alpha'] ); // Should load 'b'
echo json_encode( $arr );


I hope it can help you :

one.php

$arr = array ( 'workspace' => 'One');
if(isset($_GET['myinput_val']))
{
     $arr['workspace'] = $_GET['myinput_val'];
}
echo json_encode( $arr );

JS

$('#myinput').live('change', function(event) {
$.getJSON("one.php", { myinput_val: $(this).val() } , function (snippets) {
    for(var id in snippets) {
        // updated to deal with any type of HTML
        $('#' + id).html(snippets[id]);
    }
});
});


How about something like:

$('#mypage').bind('change', function () {
    var self = $(this);

    $('#workspace').load('/' + self.val(), {
        input: $('#myinput').val();
    });
});

Then your PHP files will look at the $_POST['input'] value to output the value.

<?php echo $_POST['input']; ?>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜