Reputation: 2292
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
Reputation: 944556
\
sdata: { keyName: $('input[name=Username]').val() }
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
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
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