0

When I run my search_form.php attached in action with form tag, it runs correctly and gives filtered database response in json form. Like this (which I want in my web page but I'm unable to get this):

[   
    {
        "id": "6",
        "section": "Science",
        "que": "What is DTG stands for?",
        "ans1": "It is dynamically Tuned Gyroscope designed to orient any of the two axis in space.",
        "ans2": "Dynamically Tuned Gyroscope. Answer to the point."   
    } 
]

My form tag and div tag is as follows in my mainWebPage.php file:

<form id="search_bar" action="search_form.php" method="post" onsubmit="return showSearchResults()">  <!-- /* MARK-1 */ -->
    Search: <input type="text" name="term" /><br> 
    <input type="submit" value="Submit" class="btn btn-outline-success " style="width: 100%; margin-top: 5px;" /> 
</form> 
<div class="container">
    <div id="search_output" style="width: 80%;">Nothing Searched yet</div>
</div>

My script is as follows in my mainWebPage.php file:

function showSearchResults() {
    console.log('This is search result.');
    var obj = $('#search_bar').serializeJSON();
    var json_string = JSON.stringify(obj);
    alert("Json string: "+json_string);
    var url = "search_form.php";
    var xhttp1 = new XMLHttpRequest();
    console.log(xhttp1.responseText+" after onload of search");
    xhttp1.open("POST", url, true);
    xhttp1.setRequestHeader("content-type", "application/json");
    xhttp1.send(json_string);
    var search_output = document.getElementById('search_output');
    console.log(xhttp1.responseText+" here is ajaxhttp1 search_form");
    search_output.innerHTML = "Loading search results....";
    xhttp1.onreadystatechange = function () {
        search_output.innerHTML = "";
        console.log(xhttp1.responseText+" here is ajaxhttp2 search_form");
        if (xhttp1.readyState == 4 && xhttp1.status == 200) {
            console.log(xhttp1);
            var jcontent1 = JSON.parse(xhttp1.responseText);
            for (var i = 0; i < jcontent1.length; i++) {
                console.log(i+"---S");
                if(jcontent1[i].ans2 != ""){
                    search_output.innerHTML +=''+ '<ul style="background:#bbd5d5" onmouseover="this.style.background=\'#ffeee5\'"; onmouseout="this.style.background=\'#bbd5d5\';">Que. <a id="clickable_que'+i+'" onclick="showThisQue('+i+')">' +jcontent1[i].que + '<br> Ans. ' + jcontent1[i].ans1 +'<br> Ans. ' + jcontent1[i].ans2+'</a><span style="width: 400px;float:right;">'+jcontent1[i].section+'</span><br></ul>';
                }else{
                    search_output.innerHTML += ''+ '<ul style="background:#bbd5d5" onmouseover="this.style.background=\'#ffeee5\'"; onmouseout="this.style.background=\'#bbd5d5\';">Que. <a id="clickable_que'+i+'" onclick="showThisQue('+i+')">' +jcontent1[i].que + '<br> Ans. ' + jcontent1[i].ans1+' </a><span style="width: 400px;float:right;">'+jcontent1[i].section+'</span><br></ul>';
                }
            }
            console.log(jcontent1+" response parsed text search_form");
        }
    }
            
    //return false; /* MARK-2 */
}

But when I changed MARK-1 & Mark-2 to this:

<form id="search_bar" action="search_form.php" method="post" onsubmit="return false">  <!-- /* MARK-1 CHANGED (made return output false here) */ -->
return false; /* MARK-2 CHANGED (made uncommented) */

And ran the mainWebPage.php and do the search, it gives my whole database result in my webpage like this:

Que. What is star sensor accuracy?
Ans. Its bore-sight accuracy is 40-arcsec and cross section accuracy is 10-arcsec. Science Concept

Que. What is dynamic observer mode?
Ans. ES+DTG mode of the spacecraft is called as dynamic observer mode. It is chosen when primary sensors failed to work. Like, Star sensor.
Ans. Earth sensor and another sensor which gives yaw information combining these two sensors called the DOM.Science Concept

Que. This is a test q?
Ans. This test answer science

Que. What is DTG stands for?
Ans. It is dynamically Tuned Gyroscope designed to orient any of the two axis in space.
Ans. Dynamically Tuned Gyroscope. Answer to the point.Science

Que. What is the role of SLE team on JPL passes?
Ans. Science Concept

Que. What is RCP configuration?
Ans. science concept

Que. What is NPA?
Ans.
Ans. NPA is nothing but Non-Performing Assets. Its a loss for any financial institution.Banking

Que. What is Loop Stress in antenna?
Ans. Science

which I dont want. I wanted the searched response which I got earlier in my search_form.php file. My search_form.php file content is this:

<?php
$conn = mysqli_connect("localhost","root","","qnaforum") or die ("Error ".mysqli_error($conn));
$term = $_POST['term'];  
    
$sql = "SELECT * FROM qna WHERE que LIKE '%".$term."%'";
$r_query = mysqli_query($conn, $sql);
$myArray = array();
if(mysqli_num_rows($r_query) > 0){
    while ($row = mysqli_fetch_assoc($r_query)){ 
        $myArray[] = $row;
    } 
} else{
    $myArray['que'] = "No records matching your query were found.";
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>

Please help and tell me what am I doing wrong?

XCosmo Exp
  • 23
  • 3
  • 1
    Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Jun 02 '21 at 10:53
  • 1
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Jun 02 '21 at 10:53
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. – ADyson Jun 02 '21 at 10:53
  • And never configure your web app to login to the database as root. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Jun 02 '21 at 10:55
  • Also not sure why you repeatedly try to log the value of xhttp1.responseText outside the readystatechange callback - that's never going to work. You can't read a value before it has been returned! – ADyson Jun 02 '21 at 10:56
  • Remove `or die ("Error ".mysqli_error($conn))`. It's not a valid code – Dharman Jun 02 '21 at 10:57
  • Also `ajaxhttp1` seems to be undefined in the JavaScript. – ADyson Jun 02 '21 at 10:58

1 Answers1

1

You're trying to send the search value in the AJAX as JSON, but your PHP is not set up to read JSON. (And it makes no sense to use JSON anyway, just to send a single value).

Just send the form data in form-url-encoded format, as it would be if you submitted the form without AJAX. jQuery can help you with this - e.g.

xhttp1.send($('#search_bar').serialize());

You also need to remove this line:

xhttp1.setRequestHeader("content-type", "application/json");

P.S. As an aside, if you're already using jQuery, its $.ajax function is a lot easier to use than the ancient XMLlHttpRequest.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thank you ADyson! I changed it to form-urlencoded format after serializing it and sending it and it worked. Thanks a lot! And yes, I'll work on vulnerable to SQL Injection attacks here. – XCosmo Exp Jun 02 '21 at 12:31