20 เมษายน 2554

การส่งค่าไปหลาย ๆ ค่าพร้อมกันโดย Ajax ของ Jquery

ส่งค่าไปหลาย ๆ ค่าพร้อมกันโดย Ajax ของ Jquery โดยใช้  serialize เข้าช่วย
--------------------------------------------------------------------------------------------------------------

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
      
        $('#button').click(function(){  
                var txt=$('#form1').serialize();  // ใช้ serialize() รวมเอา ค่าทั้งหมดที่อยู่ใน form     
                $.ajax({
                  type: 'POST',
                  url: "test.php",
                  data: txt,
                  success: function(data){
                     $('#result').html( data );                  
                  }
                
                });              
        })
      
    });
</script>
</head>
<body>

<form id="form1" name="form1" method="post" action="">
ชื่อ :<input type="text" name="name" id="name" />
นามสกุล :<input type="text" name="lastname" id="lastname" />
ที่อยู่ :<input type="text" name="address" id="address" />
<input type="button" name="button" id="button" value="Button"/>
</form>
<br />
<span id="result"></span>

</body>
</html>

---------------------------------------------------------------------------------------------------------------

 ไฟล์ test.php
<?php
    echo 'ชื่อ : '.$_POST['name'].' นามสกุล : '.$_POST['lastname'];
    echo '<br>';
    echo 'ที่อยู่ : '.$_POST['address'];
?>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น