Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Please change the type

type : "GET",

to

type : "POST",

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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