jquery - How can I retrive data from db with ajax and php?
I'm trying to check if a field is just present into db before submit a form.
So I add the keyup event to that field to get data fromdb
withajax
.
So where I have the form I add this code:
$(document).ready(function (){
$("#matricola").keyup(function () {
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
error: function(){
console.log("KO");
}
});
});
});
And this is mygetMatricolaAjax.php
:
<script src='js/jquery-2.1.4.js' type="text/javascript"></script>
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
if($_GET['type'] == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$_GET['matricola'].'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$_GET['matricola'].'"';
}
echo $queryMatricolaMatch;
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
It works for half, beacause inresult
I obtain allhtml
code fromgetMatricolaAjax.php
..
Why??
How can I get onlymatricola
??
Answer
Solution:
Comment or remove
dataType: "text"
and try again.or else you can use json_encode() in PHP to get data as JSON object array.
Answer
Solution:
You should use POST to check for value in database before submitting a form.
And the php file
This should work, but I have no idea what dbQueryGetResult is supposed to do so you should post it too. Note:If you use PDO edit remove 'real_escape_string' function and use other methods of sanitization