Hi guys its my first time trying out a live ajax search for my site. I am new to php so any help on this matter would be great. I was following some tutorials here and there and trying to make it work, but every time i press search no results come up at all. Any help on this matter would be great.
Code:
<?php
mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
if (isset($_POST['search_term']) == true && empty($_POST['search_term']) == false) {
$search_term = mysql_real_escape_string($_POST['search_term']);
$query = mysql_query("SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'");
while(($row = mysql_fetch_assoc($query)) !== false) {
echo '<li>',$row['ingName'],'</li>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div class="container">
<input type="text" class="searchFunction"> <input type = "submit" value ="Search">
<div class = "dropdown">
<ul class = "result">
</ul>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.searchFunction').keyup(function() {
var search_term = $(this) .attr('value');
$.post('build.php', {search_term:search_term}, function(data) {
$('.result').html(data);
$('.result li').click(function() {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value);
$('.result').html('');
});
});
});
});
</script>
</body>
</html>
Again i am so new to this, so i am just trying to build my knowledge around this area. Any help in solving this big problem out would be great
P.S i know about the sql injections :) but one step at a time for now x
As has been pointed out - the method used so far is at risk of sql injection so before getting committed to using the now deprecated mysql suite of functions you would be wise to read up on and implement mysqli which, when you employ prepared statements will offer significant protection from malevolent sql injection attacks.
As your ajax query is being sent to the same page ( by the looks of code posted ) one important thing to do is exit from the phpafter sending the response - otherwise you end up sending the entire page ( which would also be badly formed as there would be content outside the html tags ) and I suspect this is not your desired goal.
The ajax function looks, to my untrained eye, ok but as I don't use jQuery I might well be wrong and have missed something important.
<?php
/*
as the rest of the page doesn't use a db connection,
only load the db conn if the page is requested via post
*/
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/* assign db connection to a variable */
$conn=mysql_connect("localhost","root","") or die ("could not connect");
mysql_select_db("reg") or die ("could not find db");
/* empty() does an implied `isset` */
if ( !empty( $_POST['search_term'] ) ) {
$search_term = mysql_real_escape_string( $_POST['search_term'] );
/*
You ought to look at using mysqli ( prepared statements )
rather than the now deprecated `mysql_*` functions
*/
$query = mysql_query( "SELECT `ingName` FROM `ing` WHERE `ingName` LIKE '$search_term%'", $conn );
if( $query ){/* only send response if the query succeeds */
while( $row = mysql_fetch_assoc( $query ) ) {
echo '<li>',$row['ingName'],'</li>';
}
}
}
mysql_close( $conn );
/* make sure that the rest of the page is not sent back with the response data */
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Gotta have a title!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
/* I could not get this to work - I don't know what this is doing as I don't use jQuery */
/*var search_term = $(this).attr('value');*/
/* this however does work */
var el=event.target || event.srcElement;
var search_term=el.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 2 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr('value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class="container">
<input type="text" name='search_term' class="searchFunction">
<input type="submit" value="Search">
<div class="dropdown">
<ul class="result"></ul>
</div>
</div>
</body>
</html>
Full, working example
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if ( !empty( $_POST['search_term'] ) ) {
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
/* using lower() helped account for vagueries in spelling */
$sql='select * from `maps` where
lower( `location_name` ) like lower( "%'.$_POST['search_term'].'%" );';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
echo "<li>".$rs->location_name."</li>";
}
}
}
exit();
}
?>
<!doctype html>
<html lang='en'>
<head>
<title>Gotta have a title!</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js'></script>
<script type='text/javascript'>
$( document ).ready( function() {
$('.searchFunction').keyup( function( event ) {
var search_term=this.value;
/* maybe better to search after a few letters have been added? */
if( search_term.length < 5 )return;
/* it appears you are posting to the same page */
$.post( document.location.href, { search_term:search_term }, function( data ) {
$('.result').html( data );
$('.result li').click( function( event ) {
var result_value = $(this).text();
$('.searchFunction').attr( 'value', result_value );
$('.result').html('');
});
});
});
});
</script>
</head>
<body>
<div class='container'>
<input type='text' name='search_term' class='searchFunction'>
<input type='submit' value='Search'>
<div class='dropdown'>
<ul class='result'></ul>
</div>
</div>
</body>
</html>
You can try writing your query without the quotations ie:
$query = mysql_query("SELECT ingName FROM ing WHERE ingName LIKE '$search_term%'");
and you can also loosen your search by using '%$search_term%' instead of '$search_term'.
Another possible issue is the mysql_connect(). I was using that function and it did not work for me so I resolved to the mysqli_connect() function which worked for me.
Some more advise, you do not need the ==true and you can also you can use
!empty($_POST['search_term']).
Once you are through learning that you can also try the PDO function which is far much better than initiating your own connection.
You initiate a PDO connection like this.
$dbh1 = new PDO('mysql:dbname=dbname;host=127.0.0.1', 'username', 'dbpass');
Then you can search like this. - using the initialized connection.
$query = "SELECT ingName from ing WHERE ingName LIKE %$search_term%";
$stmt = $dbh1->prepare($query);
$stmt->execute();
$allRows = count($stmt);
$row = $stmt->fetch(PDO::fetch_assoc);
foreach($row as $one){
echo "<li>".$one['ingName']."</li><br>";
}
Cheers!
Related
I am trying to get certain data from my database on my (1) HTML page and display it on the (2) HTML page.
My codes for (1) html file:
<html>
<head>
<script src="example.js"></script>
</head>
<body>
.
.
.
<button item="' + count + '" onclick="getData(this)">Example</button>
.
.
.
</body>
</html>
And the JS for it:
.
.
.
var currentIndex = 0;
//This function is to display the details of an individual item
function getData(element) {
var request = new XMLHttpRequest();
request.open("GET", "/theroute", true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function () {
var example = JSON.parse(request.responseText);
var item = element.getAttribute("item");
currentIndex = item;
document.getElementById("data1").textContent = example[item].name;
document.getElementById("data2").src = example[item].age;
}
request.send();
}
.
.
.
I want to get these data in my (2) HTML page (for example):
<html>
<head>
<script src="example.js"></script>
</head>
<body>
<h4 id="data1"></h4>
<h4 id="data2"></h4>
</body>
</html>
I saw this Get data from one html file and display it using another html file, but I'm not sure how to use this for my case here.
Sorry, I am new to this, so giving a detailed explanation for your solution would be very helpful. I am using vanilla JS only so please no jQuery. Any help would be appreciated
I hope this might prove of use to you. The button(s) have had the custom item attribute replaced with the dataset equivalent to ensure the html is valid. Normally I'd suggest also using external event handlers rather than adding onclick=getdata() to the elements inline but for brevity here they remain.The function, when invoked by clicking a button, will construct the relevant querystring to send to the endpoint ( for you it would be /theroute?id=X&name=Y&age=Z etc ) which queries the database and sends the response back. The response is used to generate the menu of hyperlinks which take the user to page 2 when clicked. I think this is what you were trying to explain. You could copy the entire code and create a new page to see in action.
<?php
if( $_SERVER['REQUEST_METHOD']=='GET' && !empty( $_GET['item'] ) ){
ob_clean();
/*
emulate "/theroute" and send some data back to the ajax callback.
This data would really be fetched from the database but below is
simply randomly generated data for display/test purposes.
*/
$payload=[];
$item=$_GET['item'];
for( $i=0; $i < 10; $i++ ){
$payload[]=[
'id' => $i,
'name' => 'Geronimo '.uniqid().' '.$item,
'age' => mt_rand(16,80)
];
}
exit( json_encode( $payload ) );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script>
function getData( e ) {
var xhr = new XMLHttpRequest();
var ul=document.getElementById('menu');
/* The above PHP code is to emulate the real endpoint /theroute */
xhr.open( "GET", location.href +'?task=fetch&item='+e.target.dataset.item, true );
xhr.setRequestHeader( "Content-Type", "application/json" );
xhr.onload = function() {
var json = JSON.parse( xhr.response );
json.forEach(obj=>{
var id=obj.id;
var name=obj.name;
var age=obj.age;
var li=document.createElement('li');
li.appendChild( createhyperlink(id,name,age) );
ul.appendChild( li );
});
}
xhr.send();
}
function createhyperlink(id,name,age){
var a=document.createElement('a');
a.href='page2.html?id='+id+'&name='+name+'&age='+age;
a.innerHTML='View '+name;
return a;
}
</script>
</head>
<body>
<ul id='menu'></ul>
<?php
for( $i=1; $i <=10; $i++ ){
echo "<button data-item='{$i}' onclick='getData(event)'>Example #{$i}</button>";
}
?>
</body>
</html>
I tried to implement AJAX live search with AJAX and I did it quite well. Then I tried to add the _.debounce function so it will not overloads the server but it didn't work well..
this is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", _.debounce(function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
}),250);
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</body>
</html>
and this is the php file:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);
if(isset($query)){
// Attempt select query execution
$sql = "SELECT * FROM countries WHERE name LIKE '" . $query . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found for <b>$query</b></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
Thanks!
Your code doesn't include the Underscore library, so _.debounce() won't be available to use. That said, you can achieve what that method does quite easily by using a setTimeout() call:
var timeout;
$('.search-box input[type="text"]').on("keyup input", function() {
var term = $(this).val();
var $resultDropdown = $(this).siblings(".result");
clearTimeout(timeout);
timeout = setTimeout(function() {
if (term.trim().length) {
$.get("backend-search.php", { query: term }).done(function(data) {
$resultDropdown.html(data);
});
} else {
$resultDropdown.empty();
}
}, 250);
});
you can do this by setting a setTimeout to make an ajax call on every change that occurs on input after passing a specific time but don't forget to kill the previous calls. you can use the code below to any function needs denounce.
var debounce;
$('#input').on('input', function (e) {
clearTimeout(debounce);
debounce = setTimeout(
function () {
searchText(e.target.value)
}, 1000
);
});
I am having a hard time by finding this error. I spent around 10 hours searching and testing but google couldn't provide me anything. So you guys are my really last hope.
I have a simple html textfield:
<input type="text" value="" id="keyword" name="zip" placeholder="Please enter ZIP code" required>
and here is my Javascript code(the JQuery files are linked correctly, don't worry):
var MIN_LENGTH = 2;
$( document ).ready(function() {
$("#keyword").keyup(function() {
var keyword = $("#keyword").val();
if (keyword.length >= MIN_LENGTH) {
$.get( "autocomplete", { keyword: keyword } )
.done(function( data ) {
console.log(data);
});
}
});
});
When I type in the textfield the value "sw" I get following result in the console:
["Swaziland\r","Sweden\r","Switzerland\r"]
Which should be correctly. Here's my first question. Are the "\r" normal?
And my second and more important question is: How do I add the query function autocomplete? My goal would be like the following example: https://jqueryui.com/autocomplete/
Please help me, I tested around for so long and I'm unable to find the solution. And I think its a little stupid error.
Here all the files:
autocomplete.php
if (!isset($_GET['keyword'])) {
die();
}
$keyword = $_GET['keyword'];
$data = SQL::searchForKeyword($keyword);
echo json_encode($data);
searchForKeyword function:
static function searchForKeyword($keyword) {
$stmt = self::getInstance()->_conn->prepare("SELECT NameCountry as countries FROM `country` WHERE NameCountry LIKE ? ORDER BY countries");
$keyword = $keyword . '%';
$stmt->bindParam(1, $keyword, PDO::PARAM_STR, 100);
$isQueryOk = $stmt->execute();
$results = array();
if ($isQueryOk) {
$results = $stmt->fetchAll(PDO::FETCH_COLUMN);
} else {
trigger_error('Error executing statement.', E_USER_ERROR);
}
return $results;
}
The thing with jQuery ui documentation, is to find the right page.
What you need is the Remote jsonp datasource example.
I lost a lot of time on the remote datasource example (Wich I have not even been able to run), because I was affraid by the "p"...
So here is my version, a little enhanced, of an example to dynamically load the autocomplete dropdown.
I hope it will help lot of people.
The funny thing is that I didn't use jsonp like jQuery documentation suggests.
It creates a strange unclear error in console:
Error: jQuery112409377035747123055_1476875409950 was not called(…)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Remote datasource</title>
<link rel="icon" type="image/gif" href="https://www.bessetteweb.com/cube-fallback/images/sept.gif">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
<style>
.ui-autocomplete-loading {
background: white url("ajax-loader.gif") right center no-repeat;
}
.ui-widget{
width:500px;
}
.ui-front{
width:10em;
background-color:#bebebe;
}
#log{
height: 200px;
width: 500px;
overflow: auto;
}
#noResult{
display:none;
color:red;
padding-left:1em;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
function log( message ){
$( "<div>" ).text( message ).appendTo( "#log" );
$("#UScities").blur();
}
$( "#UScities" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
data: {keyword:request.term},
dataType: 'json', // DON'T use jsonp !
cache: false,
success: function(data){
console.log(data);
// Even on success, it may have no results...
if(typeof(data[0])!="undefined"){
// Remove the no result error in case it's displayed
$("#noResult").css("display","none");
// For fun, count it!
var count = 0;
while (data[count]) {
console.log(data[count]);
count++;
}
}else{
count = "NO";
// Display the no result error
$("#noResult").css("display","inline");
}
console.log(count+" RESULTS");
// Pass the data to the dropdown!
response(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
},
minLength: 4,
select: function( event, ui ) {
log( ui.item.value );
}
});
// Show results on input focus
$("#UScities").on("focus",function(){
$("#ui-id-1").css("display","block");
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="UScities">USA cities: </label>
<input type="text" id="UScities"><span id="noResult">No Result</span><br>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
<div id="log" class="ui-widget-content"></div>
</div>
</body>
</html>
I've added the result count in console (which could be used to trigger something) and a "NO RESULT" message to user, because it is possible to get no result on a keyword search.
Now, what is lacking terribly in the jQuery documentation, is how to produce a json output.
<?php
if (!isset($_GET['keyword'])) {
// Do nothing if no keyword!
die();
}
// Database connection infos (PDO).
$dsn = 'mysql:dbname=[Database Name];host=localhost';
$user = '[Database User]';
$password = '[UserPassword]';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connexion failed : ' . $e->getMessage();
}
// Getting the keyword and add % to get data that begins with it.
$keyword = $_GET['keyword'] . '%';
// If you want the keyword to be "contained" in the data, use (uncomment it):
//$keyword = '%' . $_GET['keyword'] . '%';
// Query.
$query = "SELECT city FROM SO_USAzipcodes WHERE city LIKE ? GROUP BY city limit 30";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $keyword);
// Executing.
$stmt->execute();
// If SQL error...
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
die();
}
// Fetching.
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_COLUMN);
// This is sending the json to autocomplete.
echo json_encode( $data );
?>
If you have a syntax error in this file...
Or if there is an error due to DB connection or a SQL syntax error...
You will get something like this in console:
SyntaxError: Unexpected token < in JSON at position 0(…)
And nothing happens in the main page, but the rotating .gif that keeps on turning. By the way, I just discovered this loading gif generator that worth seeing. ;)
I need to get data from mysql database without refreshing the page using jquery ajax. I have a php script which is working fine. However, my JS seems to be having some problem. Here is the jquery script.
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.post demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="/" id="searchForm">
<input type="text" name="s" class="s" placeholder="Search...">
<input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="item"></div>
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
url = $form.attr( "action" );
// Send the data using post
var posting = $.post( 'test.php', { s: $(".s").val() } ).done(function( data ) {
alert( "hiiiiiiiiii" + $(".s").val() );
});
// Put the results in a div
});
$.getJSON(
'fetch_data.php',
's='+$('.s').val(),
function(result){
$('#item').empty();
$.each(result.result, function(){
$('#item').append('<p>'+this['s']+'</p>');
});
});
</script>
</body>
</html>
This code is not working. pleas give me solution how it work?
fetch_data.php
<?php
if(!mysql_connect("localhost","root",""))
{
echo "db connection error : ".mysql_error();
exit;
}
else
{
if(!mysql_select_db("test"))
{
header('Content-type: application/json');
echo "db selection error : ".mysql_error();
exit;
}
}
$sql = "select s from test ";
$res = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($res)){
echo $row[0];
array_push($result,
array('s'=>$row[0]));
}
echo json_encode(array('result'=>$result));
?>
I have a table data [Columns: id,question,answer each question have answer]; In frontend/UI i have a textarea while i paste a question to this field which search for exact question in db and show the result.
I want ajax no need to click any search button. I want this to work when I paste question in to the text area.
Code i am using
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS3</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="jumbotron">
<h1>PHP5</h1>
<form class="form-inline">
<div class="form-group">
<input size="100" type="text" id="searchid" class="form-control" rows="10" cols="100" />
</div>
<div id="resultdiv"></div>
</form>
</div>
</div> <!-- /container -->
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
</body>
</html>
jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#searchid').keydown(function (e){ // Event for enter keydown.
if(e.keyCode == 13){
var idvalue = $("#searchid").val(); // Input value.
$.ajax({ //Ajax call.
type: "GET",
url: "search.php",
data: 'id=' + idvalue ,
type: 'json',
success: function(msg){
// Show results in textareas.
msg = JSON.parse( msg ); // Line added
alert (msg);
$('#resultdiv').val(msg.answer);
}
}); // Ajax Call
} //If statement
}); //document.ready
</script>
My Search.php
<?php
if ($_GET['id']):
$dataid = json_decode($_GET['id']);
// Connect to database.
$con = mysqli_connect("localhost","root","");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
$sql = "SELECT answer FROM exam_css3 where question LIKE '$dataid' ";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
?>
This code is not working, can anyone help on this?
There are, among other things, some issues in your PHP.
First of all you search for $dataid, which means an exact match. You need to do
"SELECT answer FROM exam_css3 where question LIKE '%{$dataid}' ";
Then you always save only one answer, and you do not specify quote marks around 'answer', which might cause a PHP warning, which would corrupt the JSON output:
while($row = mysqli_fetch_assoc($result))
{
$answer = $row[answer];
}
$rows = array('answer' => $answer);
echo json_encode($rows);
endif;
So you might want to rewrite that as
<?php
if (array_key_exists('id', $_GET)) {
$dataid = json_decode($_GET['id']);
// Here it would be good to check whether the decoding succeeded.
// I'd also try doing in HTML: data: { id: idvalue }
// Connect to database.
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db ($con,'exam_css3');
// Get the values from the table.
// Only interested in one match.
$sql = "SELECT answer FROM exam_css3 where question LIKE '%{$dataid}%' LIMIT 1";
$result = mysqli_query($con,$sql);
$answer = mysqli_fetch_assoc($result);
if (null === $answer) {
$answer = array('answer' => 'nothing found', 'status' => 'error');
}
// Since we're putting this into HTML...
$answer['answer'] = HTMLspecialChars($answer['answer']);
} else {
$answer = array('answer' => 'no query was supplied', 'status' => 'error');
}
Header ('Content-Type: application/json');
die(json_encode($answer));
In the code above I have added a 'status' variable so that in the jQuery you can do
if (msg.error) {
alert("Error: " + msg.answer);
return;
}
and further differentiate between correct and incorrect answers.
Other issues exist (for example you ought to use PDO and switch to prepared queries; as things stand, if the question contains a quote sign such as
What's a SQL injection?
your SQL search would throw an error. This is not limited to SQL injection. NO QUERY CONTAINING QUOTE MARKS WILL WORK. You need at least to escape the string dataid before placing it in the query.
You are defining twice the type in your ajax. json is the dataType not simple the type. type is get, what you do not need to set, that is the default.
The second problem is, you pass your data as a string, not as a json object, so on your server side, that will be an array, what you can not json_decode.