-1

I am struck in a wierd AJAX issue. My requirement is to validate username from DB whether it is already exists or not. I am using onblur function to validate. Below is my Jquery

function check_username (){
//Variable Declaration
var username    = $('#username').val();
var folderPath  = window.location.pathname.replace(/[^\\\/]*$/, '');
var ajxUrl      = folderPath+"helpers/ajaxChk.php";
var ajxData     = {
    action   : 'chkUsername',
    username : username 
};

//Check minimum length
if(username.length < 8){
    $('#Err_User_Name').text('Username should be minimum 8 characters');
    return false;
}else{
    $('#Err_User_Name').text('');
}
console.log(ajxData);
// Check username in database
$.ajax({
  type:         "POST",
  url:          ajxUrl,
  data:         ajxData,
  contentType:  "json",
  success: function (result) {
       //do somthing here
       alert(result);
  }
});

}

Below my php function

if (is_ajax()) {    
  print_r($_POST);

  //Checks if action value exists
  if (isset($_POST["action"]) && !empty($_POST["action"])) { 
    $action = $_POST["action"];
    echo $action; die;
    //Switch case for value of action
    switch($action) { 
      case "chkUsername": chkUsername(); break;
    }

  }
}

//Function to check if the request is an AJAX request
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

I am getting Empty Alert through SUCCESS FUNCTION. Actually i need to get post values. Please let me know what is the issue here.

dee flor
  • 69
  • 1
  • 9

1 Answers1

0

FINALLY I GOT THE ISSUE. It was never a issue with PHP. I found that my ajxData is a JAVASCRIPT Object it has to be converted to JSON before sending it in AJAX - What helped me was Basic W3 school link.

I changed

var ajxDataObj  = {action:"chkUsername", ajxusrname:username};
var ajxData     = JSON.stringify(ajxDataObj);
dee flor
  • 69
  • 1
  • 9