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?
My Answer:
The issue you are facing is because when you submit the form with the action attribute set to "search_form.php", the browser will redirect to the "search_form.php" page and display the JSON response directly.
To prevent the browser from redirecting and displaying the JSON response directly, you need to prevent the default form submission behavior by returning false in the onsubmit event handler of the form.
In your code, you have already added "return false" in the onsubmit event handler of the form. However, you also need to prevent the default form submission behavior in the showSearchResults() function by adding "event.preventDefault();" at the beginning of the function.
Here is the updated showSearchResults() function:
javascript
function showSearchResults(event) {
event.preventDefault(); // prevent default form submission behavior
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 +='Que. ' +jcontent1[i].que + '
Ans. ' + jcontent1[i].ans1 +'
Ans. ' + jcontent1[i].ans2+''+jcontent1[i].section+'
';
}else{
search_output.innerHTML += 'Que. ' +jcontent1[i].que + '
Ans. ' + jcontent1[i].ans1+' '+jcontent1[i].section+'
';
}
}
console.log(jcontent1+" response parsed text search_form");
}
}
}
With this change, the form will not be submitted and the JSON response will be displayed in the search_output div as intended.
Rate this post
3 of 5 based on 6851 votesComments