I have a scenario where on page load, a div is on display: none; and when i press button-A it toggles the div. This div acts as a search div window where end users can do search against database. But since the div is on display: none; when i submit a form on the search div window, it reloads the page and goes back to default where search div window is on display: none;
So, the data call actually executes and returns the rows i need. But I need to press the button-A again just to show the div that contains the results.
is there a workaround for this? i've read a little about ajax but i haven't really found a working solution for my case.
i have something like this. (sorry for not knowing good format on posting. its my first time to post here.)
<button id="hideshow" class="hideshow" type="submit">search</button>
<div class="search_div_wrapper" style="display: none;">
<form action="" method="POST">
<input type="text" name="search_field">
<button name="search" id="submit">search</button>
</form>
<?php
// some codes are here to query and display rows from search_field input
?>
</div>
<script>
jQuery(document).ready(function(){
jQuery('.hideshow').on('click', function(event) {
jQuery('#search_div_window').toggle('show');
});
});
</script>
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
<div class="form-group">
<input type="text" placeholder="search by name" name="search_text" class="form-control search" id="search_text"></div>
<div id="result"></div>
<!-- search.php--->
<?php
$conn = mysqli_connect("localhost", "root", "", "insert");
$output = "";
$sql = "SELECT * FROM inserdata WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
$output .= '<h4 align="center">Search Result</h4>';
$output .= '<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Address</th>
<th>Gender</th>
<th>Desc</th>
</tr>';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["email"].'</td>
<td>'.$row["phn"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["gender"].'</td>
<td>'.$row["desc"].'</td>
</tr>
';
}
echo $output;
}
else {
echo "data not found";
}
?>
you can check if there is any result after loading. and show the search_div_wrapper if there is any
var $ = jQuery;
$(window).load(function(){
if($('.result_div_wrapper').html().trim().length > 0) {
console.log($('.result_div_wrapper').html().trim().length)
$('.result_div_wrapper').toggleClass('active');
}
});
and add this to your css
.active{
display: block !important;
}
.result_div_wrapper{
display: none;
}
Related
Single Hardware Modification
Mulitple Hardware Modifications
I am trying to set up an equipment log using MySQL, PHP, and JavaScript. I have been trying to teach myself over the past 3 months. A lot of what I have is from code I have found here or on other forums.
I have a page dedicated to inputting hardware changes on our equipment. The Subsystem and Component dropdowns are set to pull the subsystem list from the database, and the component list is populated based off subsystem selection. I have not gotten that far into JavaScript, so I do not fully understand some of what this code means.
I have the page set up to input one modification, then after submitting, there is a link to return to the page to add another modification. This option is working as expected. My dropdowns work and my data is input into my database as expected.
I am trying to set up a page so that if there are multiple modifications, they can be added on one page. All of my text input fields on the form work as expected. I am able to create the first dropdown for the subsystem and populate it with my table data, but the component dropdown does not populate. I have been following this tutorial from webslesson.com. In it he uses 1 table. I have been trying to adapt it for the 2 tables that I am using, but I am getting some of the functions wrong.
Would anyone be able to point me in the right direction of where I can learn where my code is going off track? I am trying to learn, but at this point I am not exactly sure how to phrase what I am looking for.
I appreciate you taking a look at this. Please do not be too harsh on my poor code. I am working to make it better as I learn.
Above are links to my CodePen.io and repl.it for the 2 versions of my page. I had to
This is my table setup:
lu_subsystem
|id|subsystem_name|
|--|--------------|
lu_component
|component_id|subsystem_id|component_name|
|------------|------------|--------------|
<?php
//index.php
include('database_connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</h3>
<br />
<h4 align="center">Enter Item Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-responsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<thead>
<tr>
<th>Enter Item Name</th>
<th>Subsystem</th>
<th>Component</th>
<th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><select name="subsystem_id[]" class="form-control subsystem_id" data-subsystem_id="'+count+'"><option value="">Select Subsystem</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_component_id[]" class="form-control item_component_id" id="item_component_id'+count+'"><option value="">Select Component</option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.subsystem_id', function(){
var id = $(this).val();
var component_id = $(this).data('component_id');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{subsystem_id:subsystem_id},
success:function(data)
{
var html = '<option value="">Select Component</option>';
html += data;
$('#item_component_id'+component_id).html(html);
}
})
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Enter Item name at '+count+' Row</p>';
return false;
}
count = count + 1;
});
$('.item_category').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_component_id').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost; dbname=bunker_logs;", "root", "");
function fill_select_box($connect, $id)
{
$query = "
SELECT * FROM lu_subsystem
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["id"].'">'.$row["subsystem_name"].'</option>';
}
return $output;
}
function fill_component_box($connect, $component_id)
{
$query = "
SELECT * FROM lu_component
WHERE component_id ='".$id."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["component_id"].'">'.$row["component_name"].'</option>';
}
return $output;
}
?>
<?php
//fill_component.php
include('database_connection.php');
echo fill_component_box($connect, $_POST["subsystem_id"]);
?>
I have been looking into your code, and to be honest, I haven't done much in jQuery. However, I still want to give you an example on how you can implement the information on your page from my experience:
You can either pull the information directly from the database with PHP without using JavaScript. If you use PDO for this, you get a muldimension array.
You can then "walk" through the array with a foreach loop
$select ='<select id='yourChoice'>';
foreach($array as $component){
$name = component['name'];
$select.="<option value='$name'> $name </option>;
};
$select.='</select>';
In this case the $array is the full printout from the database, and goes through each row ( $component)
It then selects the column name, and fills it in.
If you want to do the same thing with JavaScript, you can do it with JSON, walking through that array.
Unfortunately, I don't have an example ready for that one at the moment.
I got a small problem.
I want to look up the name by entering the website. Now, all records are displayed. What I want is that he shows it after something has been entered in the input. I don't want him to show everything immediately.
Here some code to know how it looks like.
FETCH.PHP
Get everything from database
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM tbl_customer
WHERE website LIKE '%".$search."%'
OR naam LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM test ORDER BY id
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="table-responsive">
<table class="table table bordered">
<tr>
<th>Website</th>
<th>Naam</th>
</tr>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<tr>
<td>'.$row["website"].'</td>
<td>'.$row["naam"].'</td>
</tr>
';
}
echo $output;
}
INDEX.PHP
<div class="container">
<br />
<h2 align="center">Ajax Live Data Search using Jquery PHP MySql</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Zoek door website" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
why do u call function load_data(); on load.
this might be the issue
also remove it from else condition
I have a live search where it pulls all the relevant information from the database and displays it in the table relevant to the search using Ajax so it doesn't refresh the page, I have it so after each search it resets back to nothing until it receives another input but I want it to display what it normally does (all the information).
Before input is received: http://prntscr.com/hnmui8
After input is received: http://prntscr.com/hnmv0r
After input is removed: http://prntscr.com/hnmv53
What is want it to look like after inputs removed: http://prntscr.com/hnmvhr
index.php
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Autocomplete Textbox using Bootstrap Typehead with Ajax PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Ajax live data search using Jquery PHP MySql</h2>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<br />
<div id="result">
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>Customer name</th>
<th>Address</th>
<th>City</th>
<th>Potal code</th>
<th>Country</th>
</tr>
<?php
include('db.php');
$customers = DB::query('SELECT * FROM live');
foreach($customers as $p){
echo '<tr>
<td>'.$p["name"].'</td>
<td>'.$p["address"].'</td>
<td>'.$p["city"].'</td>
<td>'.$p["postCode"].'</td>
<td>'.$p["country"].'</td>
</tr>';
}
?>
</div>
</div>
</body>
</html>
<script>
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$.ajax({
url: "fetch.php",
method: "POST",
data:{search:txt},
dataType: "text",
success:function(data){
$('#result').html(data);
}
});
}else{
$('#result').html('');
});
</script>
fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "", "ajax");
$output = '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$output .= "<h4 align='center'>Search result</h4>";
$output .= "<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>Customer name</th>
<th>Address</th>
<th>City</th>
<th>Potal code</th>
<th>Country</th>
</tr>";
while($row = mysqli_fetch_array($result)){
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["address"].'</td>
<td>'.$row["city"].'</td>
<td>'.$row["postCode"].'</td>
<td>'.$row["country"].'</td>
</tr>
';
}
echo $output;
}else{
echo "There are no customers.";
}
?>
Thanks,
Ethan
You could save your original dataset into a variable and if the input is '', than instead of setting the html content to '', you could restore the content from the variable like so:
var originalData = $('#result').html();
$('#search_text').keyup(function(){
var txt = $(this).val();
if(txt != ''){
$.ajax({
url: "fetch.php",
method: "POST",
data:{search:txt},
dataType: "text",
success:function(data){
$('#result').html(data);
}
});
} else {
$('#result').html(originalData);
}
});
Last Update: I (lately) realized that your JS code already have an empty string check (thanks to #Taplar). #dferenc already posted correct answer for your case. But still if you want to be sure that your list is "fresh" you can follow my solution.
When you send an empty string to the server as a value of the parameter, it may be ommited. So, you should add a conditional check for that.
Use
$queryWord = isset($_POST['search']) ? $_POST['search'] : '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";
or (after PHP7, you can use null coalescing operator)
$queryWord = $_POST['search'] ?? '';
$sql = "SELECT * FROM live WHERE name LIKE '%".$queryWord."%'";
instead of
$sql = "SELECT * FROM live WHERE name LIKE '%".$_POST['search']."%'";
Important Note: Beware of SQL Injections always! Protect your code against injections. You may start from
here.
Important Note 2: I suggest you to use "Developer Console" feature of browsers. All commonly-used browsers have inline-tool for
developers to debug, trace network requests and do some
magic.
I have to display the all the records on the screen which are inserted into the database without refreshing the page. I have 3 columns called as Firstname, Lastname, Email and after clicking on the submit button data are inserting in the database using ajax Which is working.
Now I am fetching the records on the same screen without refresh the page but it is not working when I am refreshing the page then it is displaying the last record which is inserted.
Please check below link. You will get an idea what I am asking. Inserted data and display data at the same time.
http://prntscr.com/g953bs
Index.php
<?php
ob_start();
session_start();
include('../../db/connection.php');
$sql = "SELECT * FROM test1";
$result = $conn->query($sql);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form method="post" id="register" autocomplete="off">
<input type="text" name="fname" id="fname" placeholder="Firstname">
<input type="text" name="lname" id="lname" placeholder="Lastname">
<input type="email" name="email" id="email" placeholder="Email">
<input type="submit" name="submit" value="submit" >
</form>
<table border="1" style="margin-top: 25px;">
<tr>
<th>Id</th>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row['id']."</td>
<td>".$row['fname']."</td>
<td>".$row['lname']."</td>
<td>".$row['email']."</td>
</tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#register').submit(function(e){
e.preventDefault(); // Prevent Default Submission
var fname = $("#fname").val();
var lname = $("#lname").val();
var email = $("#email").val();
var dataString = 'fname='+ fname + '&lname='+ lname + '&email='+ email;
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
// $("#table-container").html(data);
$("#register")[0].reset();
},
});
});
</script>
</body>
</html>
Process.php
$firstname=$_POST['fname'];
$lastname=$_POST['lname'];
$email=$_POST['email'];
$sql = "INSERT INTO test1 (fname, lname, email) VALUES ('$firstname', '$lastname', '$email')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
$conn->close();
$('#IdTable tr:last').after('<tr><td>id<td>fname<td>lname<td>email</tr>');
Define id to the table
<table border="1" style="margin-top: 25px;" id="myTable">
Changes in ajax call
$.ajax(
{
url:'process.php',
type:'POST',
data:dataString,
success:function(data)
{
$('#myTable tr:last').after('<tr><td>' +fname +'</td><td>'+lname+'</td><td>'+email+'</td></tr>');
$("#register")[0].reset();
},
});
Note: Also you should handle the case if eror while inserting in your code as currently you are only taking positive case.
I hope this will help
First of all I'd like to suggest taking a look at binding parameters with mysqli to make your query saver.
Then in order to add the date without refreshing you could return the data on successful insert. Then append this data to the table.
Example Process.php
if (mysqli_query($conn, $sql)) {
echo "<tr>
<td>".mysqli_insert_id($conn)."</td>
<td>".$firstname."</td>
<td>".$lastname."</td>
<td>".$email."</td>
</tr>";
} else {
As you have only one table then use below code.
$('table tr:last').after('<tr>...</tr><tr>...</tr>');
If you have any class or id then you can modify below syntax as $('selector tr:last')
Use it in success of ajax call
I am using two div(s). In the first div, all the WordPress users are shown on a page, with "ADD" Button Option. By adding Users, they get added to the second div using Ajax. But I want to cache the result shown in the second div. The code for users template are as follows-
<?php
/*
Template Name: Users
*/
?>
<style>
.container{
width: 800px;
}
.left{
float:left;
width: 300px;
background: ##66CDAA;
border-right: thick-solid #fff;
}
.right{
overflow: hidden;
width: 300px;
background: powderblue;
}
</style>
<?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="container">
<div class="left" id="xyz">
<table>
<tr>
<th>Name</th>
<th>Gravatar Image</th>
<th>Add to Div</th>
</tr>
<?php
$sql ="SELECT * FROM wp_users";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ){ ?>
<tr>
<td id="<?php echo $result->ID; ?>">
<?php echo $result->display_name; ?>
</td>
<td>
<php echo get_avatar( $result->user_email, 42); ?>
</td>
<td>
<input type="button" class="submit" data-id="<?php echo $result->ID; ?>" data-name="<?php echo $result->display_name; ?>" data_image="<?php echo get_avatar_url($result->user_email, 42); ?>" value="ADD"><p style="display:none;">Added</p>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="right">
<p>Added Users</p>
<table>
<tr>
<th>Name<th>
<th>Image</th>
</tr>
</table>
</div>
</div>
</main>
</div>
<?php get_footer(); ?>
Now, in ajax.js I have the following code:
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e){
e.preventDefault();
$(this).css("display", "none");
$(this).closest("td").find("p").css("display", "block");
var id = $(this).data('id');
var name = $(this).data('name);
var image = $(this).data('image');
$.ajax({
url: ajax_url,
method: 'post',
data: { action: 'work', id:id, name: name, image:image},
success: function(response){
var test = jQuery.parseJSON(response);
name1 = test.myname;
url1: test.url;
id: test.id;
$('.table').append('<tr id=" ' + id1+ ' "><td>' + name1 + '</td><br><td><img src=" ' + url1 + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
$('.cancel').on("click", function(e){
e.preventDefault();
var id2 =$(this).closest.("tr").attr('id');
$('td[id=' + id2 + ']').closest('tr').find('p').css('display', 'none');
$('td[id=' + id2 + ']').closest('tr').find('input').css('display', 'block');
$(this).closest("tr").hide();
})
}
})
})
})
})(jQuery);
Now, In ajax.php, I have the function which is as follow:
function work() {
$id = $_POST['id'];
$name = $_POST['name'];
$image_url = $_POST['image'];
$myObj->myname = $name;
$myObj->url = $image_url;
$myObj->id = $id;
$myJSON = json_encode($myObj);
echo $myJSON;
wp_die();
}
I want to add users to the second div using Ajax and also want to cache the result for some time. Also, suggest if there is a better way of hiding Add button or can I apply a condition to check whether a particular user has been added should not be added twice. But my primary question is that how can I cache ajax result.
This may help you, go through the below code snippet
// ask the browser to cache this response
$expires = 60 * 15; // 15 minutes
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');