Home > Jquery > How to PHP return data array to jquery ajax

How to PHP return data array to jquery ajax

Ví dụ: có một bài tập yêu cầu PHP trả về một mảng dữ liệu cho jquery ajx

1. Khai báo jquery:
// jquery code


var product_id = 123;

$.ajax({ type: "POST", 

url: http://myweb.com/test.php,
async: false,
data: 'product_id='+product_id,
dataType: "json",
success: function(text){ 
  product_name = text.product_name; //lẫy tên sản phẩm
  alert(product_name);
},
error: function (text) { return false; }
});

2. Khai báo tại trang test.php

// php code


<?php

$model = new instants... //các bạn tự khai báo class model - tùy theo ứng dụng hoặc framework

$product_id = $_GET['product_id'];
$item = $model->productDetail("product_id='{$product_id}'");

// $item = array('product_id'=123, 'product_name'=>Ten san pham, 'product_qty'=>10 ...);
echo json_encode($item);

?>

tại trang javascript code, nếu các bạn lấy dữ liệu như sau:

text.product_name // lấy tên sản phẩm
text.product-qty // lấy số lượng sản phẩm
text. …etc // …

Lưu ý:

jquery gọi dataType=”json”, php trả về data type là json_encode(array or object)

 

nhantam
PHP Developer

  1. No comments yet.
  1. No trackbacks yet.

Leave a comment