0

I currently have the following function in my functions.php which checks if a username exists in the DB.

function check_username() {
       $username = $_POST['user'];
       if ( username_exists( $username ) ) {
           $return['user_exists'] = true; 
       }
       else {
           $return['user_exists'] = false;
       }
       echo json_encode($return);
       die();
}
add_action('wp_ajax_check_username', 'check_username');

I'm using Ajax to call that function with an appropriate username:

$.ajax({
    url : "http://examle.com/wp-admin/admin-ajax.php",
    type : "GET",
    dataType : "json",
    cache : false,
    data : {
        action : 'check_username',
        user: 'test'
    },
    success : function (json) {
        if (json.user_exists) {
            alert(json.user_exists);
        }
    }
});

The problem is that $username returns null instead of test. I've been trying for several hours now different combinations yet they've all returned null.

Assigning this makes the above php function work $username = 'test'; so I'm pretty sure this isn't an issue with the php code.

So my question is, how do I get the variable $username to listen and fetch the correct parameter instead of null?

3

Please change the type

type : "GET",

to

type : "POST",

2

While Chinmoy's answer is correct I recommand you to use wp_send_json. When doing ajax this is really useful. It hanldes every essential part of the process including security.

In real life you can use it like that :

wp_send_json_success( $data);//successful requests
wp_send_json_error( $data );// errors

They return an array with $data encoded in json and set some boolean to make your life easier with the jQuery part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.