Mbrouwer88
Mbrouwer88

Reputation: 2292

Jquery post single variable to PHP

I have "create user" form which has to check if the username already exists. For that, I made an onclick function on a button starting this script:

$.ajax({
type: \"POST\",
dataType: \"json\",
url: \"test.php\",
data: $('input[name=Username]').val(),
contentType: \"application/json; charset=utf-8\",
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});

However, nothing happens, even not the alert stating succes! Please help me out how to post that single variable and how to get the result from the PHP page checking the existance of the username.

Upvotes: 0

Views: 1303

Answers (3)

Quentin
Quentin

Reputation: 944556

  1. Don't escape random bits of JS. Get rid of the \s
  2. It is much easier to deal with submitted data if you format using a standard form mime type rather then just sending a single raw string. data: { keyName: $('input[name=Username]').val() }
  3. You aren't sending a JSON text. Get rid of contentType: etc etc. (Leaving it in may cause PHP to go "This isn't form data, I can't populate $_POST with it"). Let jQuery determine the content-type it sends.

Then you can access $_POST['keyName'] in your PHP.

Upvotes: 2

PlantTheIdea
PlantTheIdea

Reputation: 16369

you need to assign the variable to an item that can be referenced in the $_POST call:

$.ajax({
    type: "POST",
    url: "test.php",
    data: {user:$('input[name=Username]').val()},
    success: function(data){
        alert('Items added');
    },
    error: function(e){
        console.log(e.message);
    }
});

Then in test.php, just retrieve $_POST['user'].

Edit - I removed contentType (thanks Rocket). I also removed the dataType, because you don't need to do that if you properly set the header on test.php:

header('Content-type: application/json');

Upvotes: 1

Daniel B.
Daniel B.

Reputation: 1680

Your data key needs a value which is an object, like so:

data: {username: $('input[name=Username]').val())},

This way, the POST value username will be created.

Upvotes: 2

Related Questions