Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > บทความจากสมาชิก > jQuery Ajax กับ JSON (Web Service) ทำความเข้าใจ การรับส่งข้อมูล JSON ผ่าน jQuery กับ Ajax



 
Clound SSD Virtual Server

jQuery Ajax กับ JSON (Web Service) ทำความเข้าใจ การรับส่งข้อมูล JSON ผ่าน jQuery กับ Ajax

jQuery Ajax กับ JSON (Web Service) ทำความเข้าใจ การรับส่งข้อมูล JSON ผ่าน jQuery กับ Ajax JSON เป็นรูปแบบ string ชนิดหนึ่งที่ถูกจัดเก็บในรูปแบบที่สามารถอ่านและเข้าใจได้ง่าย ถ้าจะให้เข้าใจง่าย ๆ ก็คือ JSON เปรียบเสมือนรูปแบบของ array ชนิดหนึ่งที่ใช้รับส่งข้อมูลผ่าน ajax เพราะซึ่งปกติแล้วถ้าเราต้องการรับ-ส่งข้อมูลผ่าน ajax ต่าง ๆ นั้น จะต้องรับ-ส่งมาในรูปแบบของ string ทั้งก้อน และเมื่อฝั่ง ajax ทำการรับค่าที่ return กลับมาจาก server ก็จะต้องนำ string เหล่านั้นมาตัดตำแหน่งที่ต้องการ เพื่อเอา string ตัวที่ต้องการมาใช้ แต่สำหรับ JSON แล้ว สามารถรับส่งชุดค่าตัวแปรได้ทั้งฝั่ง client และฝั่ง server โดยทั้ง 2 ฝั่งสามารถใช้ JSON encode และ decode เพื่ออ่านค่าตัวแปรเหล่านั้น และจะเรียกใช้งานมันได้อย่างไร ซึ่งปกติแล้วจะอยู่ในรูปแบบของ Array และสำหรับตัวแปร JSON นั้นไม่จำกัดแค่รับส่งข้อมูลผ่าน Web Browser เท่านั้น แต่ยังสามารถนำ JSON ไปประยุกต์กับการรับส่งข้อมูลในรูปแบบอื่น ๆ ได้ เช่นการจับเก็บข้อมูลในรูปแบบของ String ใน Text หรือการรับส่งผ่าน Web Service ก็สามารถทำได้เช่นเดียวกัน ซึ่งในตัวอย่างนี้มีการรับส่งค่าจาก Web Serviceในรูปแบบ JSON Code ด้วย

อ่านเพิ่มเติมเกี่ยวกับ JSON
http://th.wikipedia.org/wiki/เจซัน
http://www.json.org/


บทความที่แนะนำให้ควรอ่านพื้นฐาน jQuery + Ajax + JSON

jQuery กับ Ajax ใช้ Serialize() ส่งค่า Form อ่านค่า JSON (Content-Type: application/json)

jQuery กับ Ajax ส่งค่าจาก Form และจัดเก็บลงใน MySQL และการรับ-ส่ง ด้วย JSON


สำหรับ Format ของรูปแบบค่า JSON นั้นจะครอบด้วยเครื่องหมาย { } ตัวอย่างเช่น

สมมุติว่า Array คือ
$myArr[name] = "Weerachai Nukitram";
$myArr[email] = "[email protected]";


ตัวแปรค่า JSON ที่ได้คือ
{
"name":"Weerachai Nukitram",
"email":"[email protected]"
}


สำหรับใน php สามารถแปลง JSON ด้วย function ที่ชื่อว่า json_encode() และแปลงกลับด้วย json_decode()

รูปแบบ Array 2 มิติกับ JSON โดยใช้ json_encode() ของ PHP

Code PHP
<?php
$arr[0]["CustomerID"]="C001";
$arr[0]["Name"]="Weerachai Nukitram";
$arr[0]["Email"]="[email protected]";
$arr[0]["CountryCode"]="TH";
$arr[0]["Budget"]="1000000";
$arr[0]["Used"]="600000";

echo json_encode($arr);
?>


JSON Code
[{
"CustomerID":"C001",
"Name":"Weerachai Nukitram",
"Email":"[email protected]",
"CountryCode":"TH",
"Budget":"1000000",
"Used":"600000"
}]


กรณีที่ Array มีมากกว่า 1 มิติ ค่าตัวแปร JSON จะมีเครื่องหมาย [ ] มาด้วย


และในขณะเดียวกันก็สามารถเอาข้อความ JSON มาทำการ decode ได้เช่นเดียวกัน

Code PHP
<?php
$str = '
[{
"CustomerID":"C001",
"Name":"Weerachai Nukitram",
"Email":"[email protected]",
"CountryCode":"TH",
"Budget":"1000000",
"Used":"600000"
}]
';

echo '<pre>';
var_dump(json_decode($str));
echo '</pre>';
?>









array(1) {
  [0]=>
  object(stdClass)#1 (6) {
    ["CustomerID"]=>
    string(4) "C001"
    ["Name"]=>
    string(18) "Weerachai Nukitram"
    ["Email"]=>
    string(28) "[email protected]"
    ["CountryCode"]=>
    string(2) "TH"
    ["Budget"]=>
    string(7) "1000000"
    ["Used"]=>
    string(6) "600000"
  }
}


จากตัวอย่างจะเห็น JSON สามารถทำการแปลงค่ากลับไปกลับมาได้ซึ่งจะได้ค่าตัวแปรเหมือนเดิม สำหรับหลายคนที่ยังไม่เข้าใจว่าทำไมจะต้องแปลงค่าไปเป็น JSON ก็เพราะ เมื่อเราเขียนใช้งานร่วมกับ Ajax นั้น เราจะไม่สามารถส่งค่าที่เป็นรูปแบบ Array ของตัวแปรได้จาก JavaScript ไปยัง PHP หรือ PHP ไปยัง JavaScript ได้ ซึ่งค่าตัวแปรเหล่านี้จะต้องทำการแปลงให้อยู่ในรูปแบบของ JSON ก่อนทำการรับส่งค่า และเมื่อเราใช้ jQuery ใน jQuery เองก็มี function สำหรับอ่านตัวแปร JSON เช่นเดียวกัน และไม่แต่เฉพาะ PHP ท่านั้น ใน ASP.NET หรือ JSP หรือภาษาอื่น ๆ ก็มี Library สำหรับการ Encode และ Decode รูปแบบ JSON เช่นเดียวกัน จากคำอธิบายจะเห็นว่าเราสามารถทำการเขียนโปรแกรมสื่อสารกันได้หลายภาษา และ หลายรุปแบบ การรับส่งข้อมูลในรูปแบบของ Server และ Client


ตัวอย่าง 1 การใช้ parseJSON ของ jQuery อ่าน JSON จาก php แบบ array มิติเดียว

Code PHP
<?php
$str = '{ "name":"Weerachai Nukitram", "email":"[email protected]"} ';
?>

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<script type="text/javascript">
	$(document).ready(function(){
			var obj = jQuery.parseJSON('<?php echo $str;?>');
			  $.each(obj, function(key, val) {
				   $("#div1").append(key +' = '+ val +'<br />');
			  });

	});
</script>

<body>
<span id="div1"></span>
</body>
</html>


Output
name = Weerachai Nukitram
email = [email protected]


ตัวอย่างการใช้ parseJSON ของ jQuery เพื่ออ่านตัวแปร JSON ที่มาจาก PHP

หรือสามารถใช้ obj.name และ obj.email เพื่ออ้างถึง key ของ array

<script type="text/javascript">
	$(document).ready(function(){
			var obj = jQuery.parseJSON('<?php echo $str;?>');
			    $("#div1").append(obj.name + '<br />');
			    $("#div1").append(obj.email + '<br />');
	});
</script>



ตัวอย่าง 2 การใช้ parseJSON ของ jQuery อ่าน JSON จาก php ในรูปแบบของตัวแปร array 2 มิติ

Code PHP
<?php
$str = '[ {"CustomerID":"C001", "Name":"Weerachai Nukitram", "Email":"[email protected]", "CountryCode":"TH", "Budget":"1000000", "Used":"600000"} ] ';
?>

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<script type="text/javascript">
	$(document).ready(function(){
			var obj = jQuery.parseJSON('<?php echo $str;?>');
			  $.each(obj, function(key, val) {
				   $("#div1").append('[' + key + '] ' + 'CustomerID=' + val["CustomerID"] +'<br />');
				   $("#div1").append('[' + key + '] ' + 'Name=' + val["Name"] +'<br />');
				   $("#div1").append('[' + key + '] ' + 'Email=' + val["Email"] +'<br />');
				   $("#div1").append('[' + key + '] ' + 'CountryCode=' + val["CountryCode"] +'<br />');
				   $("#div1").append('[' + key + '] ' + 'Budget=' + val["Budget"] +'<br />');
				   $("#div1").append('[' + key + '] ' + 'Used=' + val["Used"] +'<br />');
			  });

	});
</script>

<body>
<span id="div1"></span>
</body>
</html>


Output
[0] CustomerID=C001
[0] Name=Weerachai Nukitram
[0] [email protected]
[0] CountryCode=TH
[0] Budget=1000000
[0] Used=600000


จากตัวอย่างจะเห็นว่าสามารถใช้ parseJSON ของ jQuery อ่านค่าตัวแปร JSON ที่ส่งมาจาก PHP (กรณีที่ใช้ parseJSON กับ jQuery ตัวแปร JSON จะต้องยาวติดกันบรรทัดเดียว ห้าม Enter และกรณีที่ JSON มีครอบด้วย [ ] แสดงว่า string นั้นถูกจัดเก็บในรูปแบบ Array หลายมิติ)


ตัวอย่าง 3 การใช้ parseJSON ของ jQuery อ่าน JSON จากแหล่งอื่น ๆ

json.js
{
	"CustomerID":"C001",
	"Name":"Weerachai Nukitram",
	"Email":"[email protected]",
	"CountryCode":"TH",
	"Budget":"1000000",
	"Used":"600000"
}


สร้างไฟล์ที่มีรูปแบบ JSON (หรือจะสามารถเรียกจากแหล่งอื่น ๆ หรือ URL จากที่อื่นก็ได้เช่นเดียวกัน)

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<script type="text/javascript">

	$(document).ready(function(){
		   $.getJSON('json.js',function(result){
			  $.each(result, function(key, val) {
				   $("#result").append( key + '=' + val + '<br />');
			  });
			});
	});
</script>

<body>
<span id="result"></span>
</body>
</html>


Output
CustomerID=C001
Name=Weerachai Nukitram
[email protected]
CountryCode=TH
Budget=1000000
Used=600000


จากตัวอย่างนี้จะเห็นว่าใช้ getJSON เพื่ออ่านข้อมูลที่อยู่ในรูปแบบ JSON จากไฟล์ json.js หรือจะทำการอ่านข้อมูลจาก URL จากแหล่งอื่นก็ได้เช่นเดียวกัน


ตัวอย่าง 4 การใช้ parseJSON และการอ้างถึง Key ในตัวค่าของ JSON

json.js
 {
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }


<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>

<script type="text/javascript">

	$(document).ready(function(){
		   $.getJSON('json.js',function(result){
				   $("#div1").append('firstName = ' + result["firstName"] + '<br />');
				   $("#div1").append('lastName = ' + result["lastName"] + '<br />');
				   $("#div1").append('<b>address</b> <br />');
				    $("#div1").append('streetAddress = ' + result["address"]["streetAddress"] + '<br />');
				    $("#div1").append('city = ' + result["address"]["city"] + '<br />');
				    $("#div1").append('state = ' + result["address"]["state"] + '<br />');
				    $("#div1").append('postalCode = ' + result["address"]["postalCode"] + '<br />');
				   $("#div1").append('phoneNumbers = ' + result["phoneNumbers"] + '<br />');
			});
	});
</script>

<body>
<span id="div1"></span>
</body>
</html>


Output
firstName = John
lastName = Smith
address
streetAddress = 21 2nd Street
city = New York
state = NY
postalCode = 10021
phoneNumbers = 212 555-1234,646 555-4567


ตัวอย่างการอ้าง key ที่เป็น sub key ของ array ที่ถูกส่งมาจาก JSON Code












ตัวอย่างการใช้ JSON ร่วมกับ Ajax jQuery + MySQL

ตัวอย่างที่ 1 เขียน jQuery ค้นหาข้อมูลผ่าน Ajax (PHP กับ MySQL) และ return ค่า JSON กลับมายัง Client

Table : customer
CREATE TABLE `customer` (
  `CustomerID` varchar(4) NOT NULL,
  `Name` varchar(50) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `CountryCode` varchar(2) NOT NULL,
  `Budget` double NOT NULL,
  `Used` double NOT NULL,
  PRIMARY KEY  (`CustomerID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

-- 
-- Dumping data for table `customer`
-- 

INSERT INTO `customer` VALUES ('C001', 'Win Weerachai', '[email protected]', 'TH', 1000000, 600000);
INSERT INTO `customer` VALUES ('C002', 'John  Smith', '[email protected]', 'EN', 2000000, 800000);
INSERT INTO `customer` VALUES ('C003', 'Jame Born', '[email protected]', 'US', 3000000, 600000);
INSERT INTO `customer` VALUES ('C004', 'Chalee Angel', '[email protected]', 'US', 4000000, 100000);


นำ SQL นี้ไปสร้าง table ผ่าน phpMyAdmin

Ajax jQuery and JSON (Web Service)

เมื่อสร้างเสร็จจะได้โครงสร้างและข้อมูลเหมือนในรูป

ajaxJSON.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){

	$("#btn1").click(function(){
			$.ajax({ 
				url: "resultMySQL.php" ,
				type: "POST",
				data: 'keyword=' +$("#txtCountryCode").val()
			})
			.success(function(result) { 

					$("#div1").empty();

				var obj = jQuery.parseJSON(result);
				  $.each(obj, function(key, val) {

					   $("#div1").append('<hr />');
					   $("#div1").append('[' + key + '] ' + 'CustomerID=' + val["CustomerID"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Name=' + val["Name"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Email=' + val["Email"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'CountryCode=' + val["CountryCode"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Budget=' + val["Budget"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Used=' + val["Used"] +'<br />');

				  });

			});

		});
	});
</script>
</head>
<body>
Search Customer (CountryCode)
<input type="text" id="txtCountryCode">
<input type="button" id="btn1" value="Search">
<div id="div1"></div>

</body>
</html>


resultMySQL.php
<?php
	$objConnect = mysql_connect("localhost","root","root") or die(mysql_error());
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "SELECT * FROM customer WHERE 1 AND CountryCode = '".$_POST["keyword"]."' ";
	$objQuery = mysql_query($strSQL) or die (mysql_error());
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	while($obResult = mysql_fetch_array($objQuery))
	{
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++)
		{
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}
	
	mysql_close($objConnect);
	
	echo json_encode($resultArray);
?>


Screenshot

Ajax jQuery and JSON (Web Service)

จากตัวอย่างเมื่อรันไฟล์ ajaxJSON.php และมีการค้นหาข้อมูล จะมีการ request ข้อมูลผ่าน Ajax ไปยังไฟล์ resultMySQL.php และเมื่อค้นหาข้อมูลพบจะมีการ return ค่ากลับไปในรูปแบบของอาเรย์ 2 มิติ

มุมมองในตัวแปรอาเรย์ 2 มิติของ php ที่ส่งจาก mysql result
Array
(
    [0] => Array
        (
            [CustomerID] => C003
            [Name] => Jame Born
            [Email] => [email protected]
            [CountryCode] => US
            [Budget] => 3000000
            [Used] => 600000
        )

    [1] => Array
        (
            [CustomerID] => C004
            [Name] => Chalee Angel
            [Email] => [email protected]
            [CountryCode] => US
            [Budget] => 4000000
            [Used] => 100000
        )

)


มุมมองในตัวแปร JSON
[{"CustomerID":"C003","Name":"Jame Born","Email":"[email protected]","CountryCode":"US","Budget":"3000000","Used":"600000"},{"CustomerID":"C004","Name":"Chalee Angel","Email":"[email protected]","CountryCode":"US","Budget":"4000000","Used":"100000"}]




ตัวอย่างที่ 2 Client ส่งข้อมูลในรูปแบบของ JSON จาก jQuery ไปยัง Ajax เพื่อ Insert ลงในฐานข้อมูล MySQL

ajaxInsert.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){

	$("#btn1").click(function(){
			$.ajax({ 
				url: "saveData.php" ,
				type: "POST",
				datatype: "json",
				data: 'keyword={ "CustomerID":"'+$("#txtCustomerID").val()+'" ,"Name":"'+$("#txtName").val()+'" ,"Email":"'+$("#txtEmail").val()+'" ,"CountryCode":"'+$("#txtCountryCode").val()+'" ,"Budget":"'+$("#txtBudget").val()+'" ,"Used":"'+$("#txtUsed").val()+'"}'
			})
			.success(function(result) { 
				var obj = jQuery.parseJSON(result);
				if(obj.status == true)
				{
					alert('Chaiyo !!! ' + obj.msg);
				}
				else
				{
					alert('Sadddddd !!! ' + obj.msg);
				}

			});

		});
	});
</script>
</head>
<body>
Insert New Customer :
<table width="302" border="1">
  <tr>
    <td width="104">CustomerID</td>
    <td width="153"><input type="text" id="txtCustomerID"></td>
  </tr>
  <tr>
    <td>Name</td>
    <td><input type="text" id="txtName"></td>
  </tr>
  <tr>
    <td>Email</td>
    <td><input type="text" id="txtEmail"></td>
  </tr>
  <tr>
    <td>CountryCode</td>
    <td><input type="text" id="txtCountryCode"></td>
  </tr>
  <tr>
    <td>Budget</td>
    <td><input type="text" id="txtBudget"></td>
  </tr>
  <tr>
    <td>Used</td>
    <td><input type="text" id="txtUsed"></td>
  </tr>
</table>
<input type="button" id="btn1" value="Save">

</body>
</html>


คำอธิบาย
เมื่อรันที่ไฟล์ ajaxInsert.php และกรอกข้อมูลผ่าน Form ซึ่งทำหน้าที่ส่งข้อมูลไปยังบันทึกที่ Server ด้วย jQuery กับ Ajax

{ "CustomerID":"C005" ,"Name":"Weerachai Nukitram" ,"Email":"[email protected]" ,"CountryCode":"TH" ,"Budget":"1000000" ,"Used":"0"}


โดยข้อมูลที่ส่งไป ได้มีการส่งไปเป็นแบบ JSON Code และถูกส่งไปยังไฟล์ saveData.php

saveData.php
<?php
	$strRecive = stripslashes($_POST["keyword"]);

	//echo '<pre>';
	//var_dump(json_decode($strRecive));
	//echo '</pre>';

	$arrData = json_decode($strRecive,true);

	$arrReturn = array();
	// $arrReturn[status]  return status true/false
	// $arrReturn[msg]  return message


	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "INSERT INTO customer ";
	$strSQL .="(CustomerID,Name,Email,CountryCode,Budget,Used) ";
	$strSQL .="VALUES ";
	$strSQL .="('".$arrData["CustomerID"]."','".$arrData["Name"]."','".$arrData["Email"]."' ";
	$strSQL .=",'".$arrData["CountryCode"]."','".$arrData["Budget"]."','".$arrData["Used"]."') ";

	$objQuery = mysql_query($strSQL);
	if($objQuery)
	{
		 $arrReturn[status]  = true;
		 $arrReturn[msg]  = "Insert Successful!";
	}
	else
	{
		 $arrReturn[status]  = false;
		 $arrReturn[msg]  = "Insert Error!! error = ".mysql_error();
	}
	mysql_close($objConnect);

	echo json_encode($arrReturn);
?>


คำอธิบาย
ในไฟล์ saveData.php ได้มีการรับค่าจาก Ajax ที่มี string อยู่ในรูปแบบของ JSON Code จากนั้นใช้ json_decode เพื่อแปลงข้อความให้อยู่ในรูปแบบ Array และนำ array ทีได้ไป Insert ลงใน MySQL อีกที เมื่อ Insert ผ่านก็จะส่งข้อความที่อยู่ในรูปแบบของ JSON Code กลับไป

สถานะInsert ผ่าน

Ajax jQuery and JSON (Web Service)

{"status":true,"msg":"Insert Successful!"}


เป็นการส่ง JSON Code กลับมายัง Client และฝั่งของ Client ก็ใช้ jQuery และฟังก์ชั่น parseJSON เพื่ออ่านแปลงข้อความ JSON ที่ถูกส่งกลับมา


สถานะInsert ไม่ผ่าน

Ajax jQuery and JSON (Web Service)

{"status":false,"msg":"Insert Error!! error = Duplicate entry '' for key 1"}


ทำเช่นเดียวกันกับกรณีที่ของ Insert ผ่าน โดยถ้าผ่าจะมี status = true และไม่ผ่าน status = false

Ajax jQuery and JSON (Web Service)

เมื่อกลับไปยัง Server เปิด phpMyAdmin ก็จะพบกับข้อมูลที่ถูกส่งไป Insert ในรูปแบบของ Ajax jQuery กับ JSON







jQuery Ajax กับการรับส่งข้อมูลจาก Web Service ในรูปแบบของ JSON

jQuery เองการที่จะเรียก URL จาก Web Service ได้โดยตรงนั้นค่อนข้างจะเป็นเรื่องที่ยาก ฉะนั้นเราจึงจะต้องสร้างไฟล์ที่ Client ขึ้นมาเพื่อรับส่งค่าจาก Web Service ซะก่อน จากนั้นค่อยใช้ jQuery กับ Ajax เรียกข้อมูลที่ถูกส่งมาจาก Web Service ผ่าน Client อีกที และในตัวอย่างนี้จะสร้างไฟล์ Client ด้วย PHP เรียกไปยัง Web Service ของ PHP ที่อยู่อีกที

อ่านเพิ่มเติม PHP และ JSON กับ Web Service


Web Service ฝั่ง Server ใช้ Database เช่นเดียวกับตัวอย่างข้างบน

WebServiceServer.php
<?php
ob_start();
		require_once("lib/nusoap.php");
		 
		//Create a new soap server
		$server = new soap_server();
		 
		//Define our namespace
		$namespace = "http://localhost/nusoap/index.php";
		$server->wsdl->schemaTargetNamespace = $namespace;
		 
		//Configure our WSDL
		$server->configureWSDL("getCustomer");
		 
		// Register our method and argument parameters
        $varname = array(
                   'strCountry' => "xsd:string"
        );
		$server->register('resultCustomer',$varname, array('return' => 'xsd:string'));
		 
		function resultCustomer($strCountry)
		{
				$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
				$objDB = mysql_select_db("mydatabase");
				$strSQL = "SELECT * FROM customer WHERE 1 AND CountryCode like '%".$strCountry."%' ";
				$objQuery = mysql_query($strSQL) or die (mysql_error());
				$intNumField = mysql_num_fields($objQuery);
				$resultArray = array();
				while($obResult = mysql_fetch_array($objQuery))
				{
					$arrCol = array();
					for($i=0;$i<$intNumField;$i++)
					{
						$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
					}
					array_push($resultArray,$arrCol);
				}
				header('Content-type: application/json');
				return json_encode($resultArray);
		}
		 
		// Get our posted data if the service is being consumed
		// otherwise leave this data blank.
		$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
		 
		// pass our posted data (or nothing) to the soap service
		$server->service($POST_DATA);
		exit(); 
?>




Web Service ฝั่ง Client

WebServiceClient.php
<?php
			if($_POST["keyword"] != "")
			{
					include("lib/nusoap.php");
					$client = new nusoap_client("http://localhost/nusoap/WebServiceServer.php?wsdl",true); 
					$params = array(
							   'strCountry' => $_POST["keyword"]
					);
					$data = $client->call('resultCustomer', $params);

					echo $data;
			}
?>


ไฟล์ WebServiceClient.php เป็นไฟล์ที่อยู่ใน Server ของ Client อย่างที่บอกครับไว้ตั้งแต่แรก คือจะต้องสร้าง Client ไว้รับส่งค่าจาก Web Service อีกที เพราะจะใช้ jQuery กับ Ajax เรียก Web Service โดยตรงนั้นอาจจะเป็นเรื่องจาก แต่ในอนาคตคง jQuery คงจะสามารถทำให้ได้ง่ายขึ้น


jQueryCallWebService.html
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){

	$("#btn1").click(function(){
			$.ajax({ 
				url: "WebServiceClient.php" ,
				type: "POST",
				data: 'keyword=' +$("#txtCountryCode").val()
			})
			.success(function(result) { 

					$("#div1").empty();

				var obj = jQuery.parseJSON(result);
				  $.each(obj, function(key, val) {

					   $("#div1").append('<hr />');
					   $("#div1").append('[' + key + '] ' + 'CustomerID=' + val["CustomerID"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Name=' + val["Name"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Email=' + val["Email"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'CountryCode=' + val["CountryCode"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Budget=' + val["Budget"] +'<br />');
					   $("#div1").append('[' + key + '] ' + 'Used=' + val["Used"] +'<br />');

				  });

			});

		});
	});
</script>
</head>
<body>
Search Customer (CountryCode)
<input type="text" id="txtCountryCode">
<input type="button" id="btn1" value="Search">
<div id="div1"></div>

</body>
</html>


ไฟล์ jQueryCallWebService.html เป็น jQuery กับ Ajax ที่เรียกไฟล์ WebServiceClient.php อีกทีหนึ่ง

Ajax jQuery and JSON (Web Service)




บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : jQuery.parseJSON - Utilities , jQuery
Go to : jQuery.getJSON() - Ajax , jQuery
Go to : jQuery Ajax : jQuery and Ajax คำสั่งพื้นฐาน การเรียกใช้งาน jQuery กับ Ajax Framework
Go to : jQuery Ajax : jQuery and Ajax


   
Share
Bookmark.   

  By : TC Admin
  Article : บทความเป็นการเขียนโดยสมาชิก หากมีปัญหาเรื่องลิขสิทธิ์ กรุณาแจ้งให้ทาง webmaster ทราบด้วยครับ
  Score Rating :
  Create Date : 2012-05-24
  Download : No files
Sponsored Links
ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่