Skip navigation.

Log in | Sign up

My little corner on MyOpera

Simple life :)

Posts tagged with "jQuery"

Use synchronous request in jQuery.ajax

,

Đã bao giờ bạn sử dụng AJAX (jQuery) để check username tồn tại như sau chưa?
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 :smile:

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:
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ô ^^

Source: http://donamkhanh.com/2009/10/31/use-synchronous-request-in-jquery-ajax.html

Parse single Javascript object in Jquery by $.ajax method

, , , ...

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 :frown:). Khi sử dụng $.ajax như bên dưới thì phát sinh lỗi:
$.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:
...
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 :frown:

Xem bản có định dạng code tại đây

Accept only positive number using Jquery

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 :smile:
//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:
//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

How to select the first option in a combo box?

Simply in jQuery (a Javascript framework - Write less, do more):
$("#div_id option:first).attr("selected","selected"); 

Example:
$('#myCombo').load(
                              'my_combo.php?foo=bar',                              
                               function() {                                 
                                     $('#myCombo option:first).attr("selected","selected");                               
                               }                      
                      );
html:
<select id="myCombo"></select>

Pre start

, , , ...

http://hoangthuylinh.info

Chuẩn bị...

Khởi động...

:D
Download Opera, the fastest and most secure browser
December 2009
M T W T F S S
November 2009January 2010
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31