Submit Search query & get Search result without refresh - php

I want to submit search query form & get search result without redirecting/reloading/refreshing on the same page.
My content is dynamic so can not use those "submit contact form without refreshing page which replies back on success".

In order to submit a form, collect the results from the database and present them to the user without a page refresh, redirect or reloading, you need to:
Use Ajax to Post the data from your form to a php file;
That file in background will query the database and obtain the results for the data that he as received;
With the query result, you will need to inject it inside an html element in your page that is ready to present the results to the user;
At last, you need to set some controlling stuff to let styles and document workflow run smoothly.
So, having said that, here's an working example:
We have a table "persons" with a field "age" and a field "name" and we are going to search for persons with an age of 32. Next we will present their names and age inside a div with a table with pink background and a very large text.
To properly test this, we will have an header, body and footer with gray colors!
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="pt" dir="ltr">
<head>
<title>Search And Show Without Refresh</title>
<meta HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<!-- JQUERY FROM GOOGLE API -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#lets_search").bind('submit',function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
</script>
</head>
<body style="margin:0;padding:0px;width:100%;height:100%;background-color:#FFFFFF;">
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
HEADER
</div>
<div style="width:1024px;margin:0 auto;height:568px;background-color:#f0f0f0;text-align:center;">
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:<input type="text" name="str" id="str">
<input type="submit" value="send" name="send" id="send">
</form>
<div id="search_results"></div>
</div>
<div style="width:1024px;margin:0 auto;height:100px;background-color:#f0f0f0;text-align:center;">
FOOTER
</div>
</body>
</html>
db_query.php
<?php
define("HOST", "localhost");
// Database user
define("DBUSER", "username");
// Database password
define("PASS", "password");
// Database name
define("DB", "database_name");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM persons
WHERE age='".$_POST['value']."'
");
echo '<table>';
while ($data = mysql_fetch_array($query)) {
echo '
<tr style="background-color:pink;">
<td style="font-size:18px;">'.$data["name"].'</td>
<td style="font-size:18px;">'.$data["age"].'</td>
</tr>';
}
echo '</table>';
?>
The controlling stuff depends from what you want, but use that code, place those two files in the same directory, and you should be fine!
Any problems or a more explicative code, please let us know ;)

You'll probably want to start with any of the thousands of "AJAX for beginners" tutorials you can find on the net. A Google search with that term should get you going.
Try this for starters:
http://www.destraynor.com/serendipity/index.php?/archives/29-AJAX-for-the-beginner.html
After you've read through that, keep in mind that you really don't need to be writing any XHR handling code. As pointed out by Jamie, jQuery or any of the other multitudes of Javascript libraries out there, can greatly simplify your client-side AJAX code.

This is what AJAX is for.
In jQuery (apologies if you're looking for a different library)
$("form#search").bind('submit',function() {
$.post("search.php",this.serialize(),function(data) {
// Put the code to deal with the response data here
});
return false;
});

It's good if you can get some basics of Ajax before straight away going to the code.
Ajax , is the exact solution for your problem. It asynchronously makes a request to the server, get the result and the data in the page can be modified with the result . It's all done in JavaScript.
Suppose you have an html like this:
<html>
<body>
<div id="myDiv"> your content area</div>
<button type="button" onclick="loadByAjax()">Change Content</button>
</body>
</html>
Now, your javascipr code will be like this:
<script type="text/javascript">
function loadByAjax()
{
$.ajax({
type: "POST",
url: "yourserverpage.php",
data: "searchkey=data_from_user_input",
success: function(response_data){
$('myDiv').html(response_data)
}
});
}
</script>
so, basically upon click of the button, the JavaScript will be executed. It wil call the php serverside script, pass the parameters it got from user input and retrieve the response data and place it inside the div.
So your page is updated without full refresh.
Also, please understand that, i used jquery library here for the Ajax function.

Related

How to change a text value by requesting a PHP file thanks to AJAX? (Without refreshing the page)

I'm learning AJAX and want to create a really simple web app to use my knowledge in the "real world".
I'm trying to calculte different percentages of a user input value, and make it appears on the webpage, without refreshing, thanks to AJAX.
Here is my HTML form:
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button type="submit">Calculate</button>
</form>
<div id="#output">This is where I want the result to be shown with AJAX</div>
Here is some of my PHP code, for you to get the idea:
# Get the user input (work load in kgs)
if (isset($_POST['userWorkLoad'])) {
$workload = $_POST['userWorkLoad'];
# Avoid JS hacking
$workload = htmlspecialchars($workload);
}
# CALCULATION #
# Calculate 55% of the work load (1st warm up set)
$FirstWarmupSet = ($workload * 0.55);
# Calculate 70% of the work load (2nd warm up set)
$SecondWarmupSet = ($workload * 0.7);
# First Warmup set #
echo "<li>Do 8 reps with " . $FirstWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
# Second Warmup set #
echo "<li>Do 5 reps with " . $SecondWarmupSet . " kgs, then take 1 minute rest.</li>";
echo "<br>";
// etc etc...
I'd like the different variables values from PHP to be shown in my "#output" div when the user click on the submit button.
I've tried a lot of different things (AJAX without jQuery, AJAX with jQuery), but didn't manage to get what I want.
I'm sure I'm doing something wrong, but I don't know what. I'm sure my PHP script is working, since I used it without AJAX without any problem.
I would be very grateful if someone could help me on that.
As mentioned above, the easiest way to make an AJAX request for you is probably to try jQuery:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- Add jQuery on your HTML page -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!-- Add some custom JavaScript file -->
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form id="warmupForm" class="form">
<label for="userWorkLoad">Work load (in kgs)</label><br>
<input type="text" name="userWorkLoad" id="userWorkLoad">
<button id="btn" type="submit">Calculate</button>
</form>
<div id="output">This is where I want the result to be shown with AJAX</div>
</body>
</html>
The script.js content:
$(function() {
// Process a button click
$("#btn").click(function() {
event.preventDefault();
// Get input field
var userWorkLoadInput = $("#userWorkLoad");
// Build some request parameters
var params = {
userWorkLoad: userWorkLoadInput.val()
};
// Let's name your PHP script file as "server.php"
// And send POST request with those parameters
$.post("server.php", params, function(response) {
// Response text we're going to put into the `output`
$("#output").html(response);
});
});
});
You can simply do it using Jquery instead of using Ajax (using PHP you should add method="POST" to the form).
Here's an example:
$(document).ready(function(){
$("#send").click(function(){
// your calculates
$("#output").html(...);
});
});
...
<button type="submit" id="send">Calculate</button>

PHP - display query search results in Bootstrap modal window

I have code below for a search bar that, upon clicking 'Search', loads a new page with the query results. How do I change it so instead of loading a new page, the query results open in a modal popup within the same page?
index.php
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form method="POST" action="search.php">
<input type="text" name="q" placeholder="Enter query"/>
<input type="submit" name="search" value="Search" />
</form>
</body>
search.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
include_once('db.php'); //Connect to database
if(isset($_POST['q'])){
$q = $_POST['q'];
//get required columns
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%$q%' OR `yupikWord` LIKE '%$q%'") or die(mysqli_error($conn)); //check for query error
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= "<a href='audio/$audio_name'>$audio_name</a> ";
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>
You need to use JavaScript on your page to executed an AJAX call to search.php. That PHP file preferable returns JSON data, or complete HTML that can be added to the modal window.
Conceptually:
Use JavaScript to executed AJAX POST to search.php
Have search.php return the data in JSON format.
Have JavaScript catch the returned data, iterate through it and create HTML elements.
Use JavaScript to open a new modal window.
Use JavaScript to add the HTML elements to the modal's body.
You don't necessarily need to use JavaScript to create the modal window. You can create it in plain HTML and fill it and open it using JavaScript.
Welcome to stackoverflow. Here's my solution for that, so first, you have to capture the form submission, the technique is doing GET request using jQuery which I assume you already using jQuery since you are using bootstrap and bootstrap uses jQuery
$('form').submit(function(e){
e.preventDefault() // do not submit form
// do get request
$.get( 'search.php', { q : },function(e){
// then show the modal first
$('#mymodal').modal('show');
// then put the results there
$('#mymodal:visible .modal-container .modal-body').html(e);
});
});

Taking values from form, pulling results from MySQL, and using AJAX for results

I am having a bit of trouble figuring out how exactly to make a certain connection. It's a project I thought might be simple enough for me to do on my own without help, but I've hit a wall unfortunately. It's an 'exercise generator' that basically asks a few basic questions, and based on your answers, it outputs a recommended workout routine. I've constructed the MySQL database with plenty of exercises, have successfully connected the database, and have made the form.
What I am having trouble though, however, is storing those form results into variables, and based on those variables (if workout days is 3, for example, there would only be 3 groups of workouts printed instead of 5) output a routine into the same div as the form, effectively replacing it with the answer instead of placing it underneath the submitted form.
Index.php
<!DOCTYPE html>
<html>
<?php $page_title = "Workout Generator"; ?>
<link rel="stylesheet" type="text/css" href="style.css">
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script>
</head>
<body>
<?php include("header.php"); ?>
<?php include("connect.php"); ?>
<div id="appWindow">
<h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3>
<form id="homeForm" method="post" >
<label for="name">Name: </label>
<input type="text" name="name"><br>
<label for="age">Age: </label>
<input type="number" name="age"><br>
<label for="workoutdays">How many days a week can you workout?</label>
<select name="workoutdays">>
<option value="1">3</option>
<option value="2">5</option>
</select><br>
<label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label>
<select name="workoutstyle">>
<option value="1">Gym</option>
<option value="2">Bodyweight</option>
</select><br>
<button type="submit" name="submit">Submit</button>
<button type="reset" name="reset">Reset</button>
<div class="form_result"></div>
</form>
<?php
$age = $_POST['age'];
$workoutdays = $_POST['workoutdays'];
$workoutstyle = $_POST['workoutstyle'];
?>
</div>
<br><br><br>
<?php include("footer.php"); ?>
</body>
</html>
I don't necessarily want an answer giving me the exact code to enter, but would appreciate being pointed in the right direction to get that form pulling data from MySQL, and using AJAX to print in the same window without refreshing.
THANK YOU
First of all, you need to post your request. With $.ajax this
//Do this thing on page load
$(function() {
//handle submit
$("#homeForm").submit(function(e) {
//customize your submit
e.preventDefault();
$.ajax({
type: "POST",
url: youURL, //maybe an url pointing to index.php
data: yourData, //attach everything you want to pass
success: function(response) {
$("#appWindow").html(response);
}
});
});
});
code should help. You need to make sure you pass the necessary elements and you provide the correct url. On server side, generate the desired html and send back as response.
In the script file
$(document).ready(function(){
$(document).on('click','#submit_btn',function(){
var url = '/xyz.php'; //full path of the function where you have written the db queries.
var data = '';//any data that you would like to send to the function.
$.post(url,{data: data}, function(result){
var arr = JSON.parse(result);
});
});
});
in your php file once your database query has been executed and you get the result. for example
$result = //result of your mysql query.
echo json_encode($result);
exit;

Why doesn't a form returned by a jquery AJAX call to PhP into a DIV not work?

I am trying to write an interactive web page and learn newer (10 years or less) web technologies along the way. So PhP, jquery and AJAX all fall into that category. I've pared down the code to just the essentials to ask this question.
I want my jquery to call a PhP program that will load two separate DIVs. One is a data display area and the other is used to display the next form in the process chain. The trouble I'm having is that the form I'm returning isn't functional, even though it displays properly.
This is the main page (demo.php):
<?php
echo <<<_END
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<script>
//
$(document).ready(function(){
$("#btnDemo").click(function() {
$("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
$("#PageContent").load("nextpage.php");
});
});
</script>
</head>
<title>The Title</title>
</head>
<body>
<div id="PageHdr">
<H4>Heading</h4>
</div>
<div id="PageForm">
<form action="" id="Login">
<br/>
To show this form again enter Y otherwise enter N : <input type="text" name="paramYN" id="paramYN" size=1>
<input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
</div>
<div id="PageContent">
<P>Put response here</p>
</div>
</body>
</html>
_END;
?>
Here's the PhP program "thetest.php" which decides what to return into the PageForm DIV:
<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{
echo <<<_EOF
<form action="" id="Login">
<br/>This is the redisplay. Look for the date to change if it works after you click the test it button
<br/>To show this form again enter Y otherwise enter N : <input type="text" name="ParamYN" id="paramYN" size=1>
<input type="button" name="btnDemo" id="btnDemo" value="test it" /></form>
_EOF;
$thetime = time();
echo $thetime;
exit();
}
else
{
echo "<html><head><title>PDO login</title></head><body>";
echo "<h1>Congrats!</h1>";
echo "</body></html>";
exit();
}
?>
I only included the nextpage.php program because the full version of my program needs to update both DIV's. For the purpose of this demo it's as simple as this:
<?php //.php
echo "<h1>This is the new text for this place</h1>";
?>
So what is my problem here? Is it something in the way that I'm loading the DIV? Or is this something that is not doable?
When your page first loads you use jQuery and "bind" a click event to your button "btnDemo".
The user then clicks the button "btnDemo" and triggers the load events. However, by doing this you are overriding your previously loaded button with the established jQuery events with a NEW button "btnDemo". This NEW button does NOT have the same bound click events.
You will need to re-apply the click events to the newly loaded button after it loads by adding the jQuery to the loading page "thetest.php".
echo <<<_EOF
<script>
$(document).ready(function(){
//this will bind the click event to the newly loaded button
$("#btnDemo").click(function() {
$("#PageForm").load("thetest.php", { paramYN: $("#paramYN").val() })
$("#PageContent").load("nextpage.php");
});
});
</script>
<form> (the rest of your form here...)
_EOF;
You have:
<?php //thetest.php
paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{
Try:
<?php //thetest.php
$paramYN = $_POST["paramYN"];
if ($paramYN == "Y")
{

Undefined index when passing variable from jquery to php

I'm trying to pass a variable from an html file, using jquery and ajax to a php file, where I want to process it. I have two test files:
ajax.html
<html>
<head>
<title>ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<link href="ajax.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#call_back").click(function () {
$.post(
"ajax.php", {
value: $("#input_text").val()
},
function (data) {
$("#response_text").val(data);
}
);
});
});
</script>
</head>
<body>
<div id="wrapper">
<h3>Ajax</h3>
<div class="entry-wrapper">
<h4>Data to send to the server</h4>
<input type="text" size="50" id="input_text" />
<input type="button" value="Ajax Callback" id="call_back" />
</div>
<div id="response_wrapper">
<textarea id="response_text"></textarea>
</div>
</div>
</body>
</html>
and ajax.php
<?php
$value = $_POST['value'];
echo "Returned from the server: $value";
?>
The html works fine. If I enter a value in the text field, it's passed to the php file, processed and sent back to be displayed in the textarea.
I've looked in firebug and the post tag in the console shows the values that I enter.
The problem is that I want to be able to use the variable in the php file, for arithmetic operations or running an sql query with it, but it shows up as undefined index when I open the php file.
I've looked through multiple threads on passing variables from jquery to php but still found no answer. I have no idea what the problem is. Suggestions are much appreciated. Thanks.
If I understand you question correctly, you need to define the variable in your url.
Example:
http://yoursite.com/ajax.php?value=yourdata
This way when you open the file you are defining the value which is all you are doing with your ajax request. If this is not what you are trying to accomplish, try to rephrase your question.
Revised after 1st comment:
<?php
if(isset($_POST['value'])){
//do whatever in here
dowhatever();
}
function dowhatever() {
$value = $_POST['value'];
echo "Returned from the server: $value";
if(value == 'data') {
//run query
}//end if
}
?>
I assume that when you say you can confirm it's working, but when you directly open the .php file, it has undefined index, then I would say that makes perfect sense. If you are browsing directly to the .php file, then no POST data is being sent. But if you are able to type in some text, fire off the submit, and get text back as planned, then it's working.

Categories