views:

864

answers:

2

When i use blur function on textbox to check duplicate name using jquery ajax working fine.

Here is code:

function duplicate(data){
    //alert(data); //successfully gives the value from the text input
    $.post("test.php", {name: data}, function (data){
        if(data){
            alert('duplicate name');
        }
    });
}

$(function() {
    $("#name").blur(function(){
        var data = $("#name").val();
        duplicate(data);
    });
});

The problem is it show alert message, in some case we submit with duplicate name itself so there is no use of checking duplication.

Let me know the solution to check duplicate name using onsubmit function ( jquery ajax or javascript ).

+3  A: 

Your question is confusing because you're using the same variable name, data, outside of your request as well as in the request callback.

I'm not sure if you're asking to check for duplication based on data that has already been submitted and is back on the page, data that exists on the server, or if the data's simply "yes".

Based on the code you provided, it would appear that data is considered to be duplicated if the server returns yes once the POST completes.

Either way, maybe this will help:

$(function() {
  $('#name').blur(function() {
    duplicate($('#name').val());
  });
});

function duplicate(sData) {

  var sDuplicateValue = ...; // assign this whatever constitutes a duplicate value
  if(isDataDuplicate(sData, sDuplicateValue)) {
     // you have duplicate data
  }

  $.post('test.php', { name: sData }, function(sResposeData) {

    /* because of question ambiguity, i don't know if you want to compare
     * sData and sResponseData, or sResponseData and "yes." if it's the latter,
     * just do isDataDuplicate(sResponseData, "yes"); otherwise, do this:
     */

    if(isDataDuplicate(sData, sResponseData) {
      // it's the same..
    }
  });

}

function isDataDuplicate(sData, sDuplicateValue) {
  if(sDuplicateValue === null) {
    return sData === 'yes';
  } else {
    return sData === sDuplicateValue;
  }
}
Tom
+1  A: 

I'll do something like this:

$(function() {
    $("#name").blur(function(){
        var value = $("#name").val();
        $.post(
            "checkDuplicates.php",
            { name: value}, 
            function (data){
                if( data.response === 'yes'){
                    $("#name").css({
                        'border': '1px red solid'
                    }).parent().append('This name already exists');
                } else {
                    return false;
                }
            },
            'json'
        );
    });
});
Elzo Valugi