I am trying to send the username to php
using ajax
.
Here is my js
.
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: username,
success: function(result){
$("#dbdata").html(result);
}
});
});
And here is php.
$value = $_GET['username'];
I know it is about the ajax
because everything worked fine when the ajax
part was written in pure javascript
.
Send
data
as an object as$_GET
reads associative array of variables passed to the current script via the URL parameters
data: {username:username},
You are using type:"POST"
and trying to retrieve the values in GET Array in the PHP code .Change the method to GET
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "GET",
url: "dbquery.php",
data: username,
success: function(result){
$("#dbdata").html(result);
}
});
});
Use below code
$('#username').blur(function(){
var username = $("#username").val();
var dataString = 'username ='+ encodeURIComponent(username) ;
$.ajax({
type: "POST",
url: "dbquery.php",
data: dataString ,
success: function(result){
$("#dbdata").html(result);
}
});
});
First: You are using POST in ajax. and GET in PHP, which is wrong.
If we use POST then in the PHP file, we use $_POST[”] to get the value. If we use GET then we use $_GET[]
Second: data is passed as an object as data: {username: username}
. This means that if we use $_POST[‘username’]
in the PHP file, we will get the value of the username. Your final code will be
AJAX
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: {username:username},
success: function(result){
$("#dbdata").html(result);
}
});
});
PHP
$value = $_POST['username']
Please pass data as an Object. To access data in PHP you have to use $_POST['username'], $_POST['password'] etc
$('#username').blur(function(){
var data = {
username:$("#username").val(),
password: $("#password").val()
};
$.ajax({
type: "POST",
url: "dbquery.php",
data: data,
success: function(result){
$("#dbdata").html(result);
}
});
})
first of all your ajax type is post but you getting value using GET[] This is mistake here.
try this
$('#username').blur(function(){
var username = $("#username").val();
$.ajax({
type: "POST",
url: "dbquery.php",
data: {'username':username},
success: function(result){
$("#dbdata").html(result);
}
}); });
and you have to use this to get value
$value = $_POST['username'];