Archive for the ‘jQuery’ Category

Use synchronous request in jQuery.ajax

Saturday, October 31st, 2009

Đã bao giờ bạn sử dụng AJAX (jQuery) để check username tồn tại như sau chưa?

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function checkUser(u) {
    var isExist = false;
    $.post(
        'index.php',
        {'username': u},
        function(ret) {
            isExist = ret;
        }
    );
 
    return isExist;
}
 
if( checkUser('donamkhanh') ) {
    alert('donamkhanh already exist');
}
else {
    alert('donamkhanh does not exist');
}

Theo bạn, nếu chạy đoạn mã trên thì sẽ ra kết quả nào (giả sử rằng server script hoàn toàn chạy chính xác, trả về giá trị true/false hay 1/0 gì đó & username donamkhanh đã tồn tại)?

Do mặc định trong jQuery tất cả các request đều được sent asynchronous nên trong quá trình send request thì hàm checkUser đã return luôn giá trị lúc khởi tạo biến isExist = 0 rồi. Vậy nên kết quả luôn thông báo là username donamkhanh chưa tồn tại :)

Cách fix rất đơn giản, sử dụng thuộc tính async của $.ajax. Các hàm $.post hay $.get không có thuộc tính này vì

This is jQuery’s low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks).

Code ở trên sẽ sửa lại như sau:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function checkUser(u) {
    var isExist = false;
    $.ajax({
        async: false,
        type: "POST",
	url: "ajax.php",
	data: "username=" + u,
	success: function(msg){
	     isExist = msg;
	}
    });
 
    return isExist;
}

Nếu set async = false, jQuery sẽ sử dụng synchronous cho các request. Ở ví dụ này bạn có thể thấy nó chưa thực sự cần thiết (vì có thể nhét đoạn check vào luôn trong callback function của $.post, $.get hay bất cứ ajax method nào của jQuery), tuy nhiên nếu bạn phải viết nhiều hàm (ajax) và các hàm này lấy kết quả của nhau để tính toán thì việc set synchronous là bắt buộc. Nếu không thì sẽ xảy ra tình trạng nhiều biến nhiều hàm lon ton cầm đèn dầu chạy trước ô tô ^^

Parse single Javascript object in Jquery by $.ajax method

Tuesday, September 8th, 2009

Chưa thử test với Jquery phiên bản mới nhất, mới chạy trên bản 1.2.1 (dự án hiện tại đang dùng :( ). Khi sử dụng $.ajax như bên dưới thì phát sinh lỗi:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$.ajax({
	type: "POST",
	url: document.location.href,
	data: "card_type=" + cardType + "&card_number=" + cardNumber,
	dataType: 'JSON',
	cache: false,
	success: function(responses){
	    if(!responses.has_error)
	    {
	 	alert("Please enter valid Card Number.");
	 	return false;
	    }
       }
});

thì bị lỗi. Mặc dù response là {‘has_error’: false;} nhưng lại không nhảy vào khối lệnh IF.
Cách khắc phục rất đơn giản:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
...
success: function(responses){
    var obj = eval('('+responses+')');
    if(!obj .has_error)
    {
	alert("Please enter valid Card Number.");
	return false;
    }
}

Lưu ý: Chỉ xảy ra lỗi này nếu response là single object, nếu nó là mảng các object thì cứ $.each rồi get theo key, val thì lại ko sao :(

Accept only positive number using Jquery

Saturday, December 20th, 2008

Có thể sử dụng Event Handling hoặc Event Helper. Tất nhiên là sử dụng Event Helper thì ngắn hơn rồi :)

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
//when key is pressed in the textbox
$("#quantity").keypress(function (e)
{
  //if the letter is not digit then display error and don't type anything
  if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57))
  {
    //display error message
    $("#errmsg").html("Digits Only").show().fadeOut("slow");
    return false;
  }
});

Mình quen viết thế này hơn:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
//when key is pressed in the textbox
$("#quantity").keypress
(
    function (e) {
        //if the letter is not digit then display error and don't type anything
        if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
            return false;
        }
    }
);

Nguồn: http://roshanbh.com.np/2008/04/textbox-accept-only-numbers-digits.html

Upgrade whois domain to v3.1

Thursday, August 28th, 2008

Lý do phải nâng cấp:
- Matbao.net đã thay đổi lại cấu trúc site của họ (thay đổi giao diện) nên phần parse data của mình sẽ không chính xác nữa.
- Dùng nsloop-up chỉ có thể check domain đó có hoạt động hay không, chứ không check được đã được mua hay chưa. Có thể chủ sở hữu đã mua nhưng chưa active domain :)

Những thay đổi:
Không có nhiều thay đổi trong phiên bản nâng cấp này ngoài:
- Get xml content thay cho html content.
- Chuẩn hóa các function theo camelCase.
- Bỏ php short tag, chuyển về <?php echo …;?> nếu có.

Todo:
Mặc dù kết quả nhận được từ matbao.net là dạng XML nhưng vẫn gặp khó khăn trong khâu parse XML. Dùng các libs có sẵn trong PHP như simpleXML, XMLparse… đều bị lỗi do syntax của file XML này không chuẩn cho lắm. Tạm thời tôi dùng preg_match để parse XML. Khi nào có điều kiện sẽ nghiên cứu cách parse XML mà không biết trước cấu trúc :D Có bác nào tốt bụng thì phát triển thêm hộ tôi với :p

Hướng dẫn nâng cấp:
- Download bản upgrade tại http://donamkhanh.com/download/whoisv3.1.php.txt http://donamkhanh.com/download/whoisv3.2.php.txt
- Sau khi download, rename file whoisv3.1.php.txt whoisv3.2.php.txt thành index.php, rồi ghi đè file index.php trong thư mục whoisv3 (nếu chưa có phiên bản 3.0 thì có thể download tại http://donamkhanh.com/download/whoisv3.tar.bz2)

Yêu cầu:
- Chmod quyền hợp lý (cho đọc ghi đối với file checked_domain.txt)
- Thông số allow_url_fopen trên host phải thiết lập bằng On.

How to select the first option in a combo box?

Tuesday, May 13th, 2008

Simply in jQuery (a Javascript framework – Write less, do more):

?View Code JAVASCRIPT
1
$("#div_id option:first).attr("selected","selected"); 

Example: 

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
$('#myCombo').load(
                              'my_combo.php?foo=bar',
                               function() {
                                     $('#myCombo option:first).attr("selected","selected");
                               }
                      );
html:
<select id="myCombo"></select>