Nico Orfi
Nico Orfi

Reputation: 173

Ajax post to php file not working

This is one of my first ajax programs. I don't know why my $usernamevariable is remaining undefined. In the username_availability.php file. This is my Jquery code:

 $(document).on('keyup', "#username", function(e){
        $.ajax({
            type: "POST",
            url: "../database/username_availability.php",
            data: {username:$('#username').val()}
        });
        var url = 'database/username_availability.php';
        $('#username_check').html('loading…').load(url);
        e.preventDefault();
    });

And this is my php file:

include_once "../my_classes/form/connection.php";
$connection = new \mysqli(DB_HOSTNAME,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if (!$connection) die ('Connection failed');
$username = ($_POST['username']);
$username = $connection->real_escape_string($username);
print_r($username);
    $query = "SELECT * FROM users WHERE username='$username'";
$result = $connection->query($query);
    if (!$result) die($connection->error);
foreach ($result as $results=>$i)
echo $results;

I am still getting undefined index on the $username = ($_POST['username']);line.

Upvotes: 1

Views: 68

Answers (4)

Andrey
Andrey

Reputation: 441

Your post data:

 data: {text:$('#username').val()}

As key you send text

On server you can get $_POST['text']

Or

You can change 'text' to 'username'

Upvotes: 1

szymeo
szymeo

Reputation: 431

Try to set value to variable, just like

var username = $('#username').val();
data: { 'username' : username }

And now it looks much better

Upvotes: 2

Matthew Goulart
Matthew Goulart

Reputation: 3065

In your ajax file you are calling the username "text", not "username" but then in the PHP you are looking for the "username" index in the POST array.

This is because in the ajax call you have to NAME the data AND assign it like this:

 data: {username:$('#username').val()}

alternately you could change your php to this:

$username = ($_POST['text']);

Upvotes: 2

Marcos Pérez Gude
Marcos Pérez Gude

Reputation: 22158

Just change in your ajax call:

 data: {text:$('#username').val()}
 -------^^^^

With this

 data: {"username":$('#username').val()}

Upvotes: 4

Related Questions