I'd like to get an interactive block in my page that onchange of one of the 3 search fields only reloads the div 'mydata' and reruns the query with a new filter. I know it probably can be done with ajax but i'm stuck in finding the right piece of code.
Here's my testcode
Main php file users2.php:
<head>
<title>Test</title>
<script src="../jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="../jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script>
$.ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?id=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<?PHP
include '../conf/config.inc.php';
include 'users_functions2.php';
?>
</body>
And here the include file users_functions2.php:
<?php
echo "<div id='mydata'>";
echo "<table><tr><th>ID</th><th>Name</th><th>City</th></tr>";
echo "<tr>";
echo "<td><input type=text placeholder='search' name=search_id</td>";
echo "<td><input type=text placeholder='search' name=search_name</td>";
echo "<td><input type=text placeholder='search' name=search_city</td>";
echo "</tr>";
$sql="select id, name, city from users;";
if (isset($_GET['search_name'])) { $sql .= "WHERE vo_name LIKE \"%".$_GET['search_name']."%\""; }
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
echo "<tr><td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['city']."</td></tr>";
}
echo "</table>";
echo "</div>";
?>
Hope Chris is ok with this, i'd like my question being answered with a working example:
File 1:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js" integrity="sha256-eGE6blurk5sHj+rmkfsGYeKyZx3M4bG+ZlFyA7Kns7E=" crossorigin="anonymous"></script>
<script>
$(document).ready(function() {
// create the on change event
$('#search_name').on('change', function() {
// get the new information from the server
$.ajax({
url: 'users_functions2.php?search_name=' + $('#search_name').val(),
success: function(data){
// this code is run when you get the reply;
$('#mydata').html(data);
}
});
});
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th><th>Name</th><th>City</th>
</tr>
<tr>
<th><input type=text placeholder='search' name=search_id></th>
<th><input type=text placeholder='search' id='search_name' name=search_name></th>
<th><input type=text placeholder='search' name=search_city></th>
</tr>
</thead>
<tbody id="mydata">
<?PHP
include 'users_functions2.php';
?>
</tbody>
</table>
</div>
</body>
File 2:
<?php
include '../conf/config.inc.php';
$sql="SELECT id, `name`, city FROM users";
$search_name = filter_input(INPUT_GET, 'search_name');
if ($search_name) {
$sql .= " WHERE vo_name LIKE \"%$search_name%\"";
}
$res = my_query($sql);
while($row = mysqli_fetch_array($res)) {
extract($row);
echo "<tr><td>$id</td><td>$name</td><td>$city</td></tr>";
}
?>
Related
I am trying to make an AJAX call to my PHP Script. I can echo the results from my data. php just fine. My question is how do I make the call from index.html to pull the table results in data.php.
<?php
$pullData = file_get_contents('https://api.rentcafe.com/rentcafeapi.aspx?requestType=apartmentavailability&APIToken=OTI4MjI%3D-eiBNyIvyQA8%3D&propertyCode=p0494361');
$results = json_decode($pullData);
//Table columns
echo '<table>
<tr>
<th>Apartment Name </th>
<th>Beds</th>
<th>Baths</th>
<th>Floor Plan Name</th>
<th>Minumum Rent</th>
<th>Maximum Rent</th>
</tr>';
//Iterate throught the API data and return only required columns
foreach($results as $formatted_results){
echo '<tr>';
echo '<td>'.$formatted_results->ApartmentName.'</td>';
echo '<td>'.$formatted_results->Beds.'</td>';
echo '<td>'.$formatted_results->Baths.'</td>';
echo '<td>'.$formatted_results->FloorplanName.'</td>';
echo '<td>'.$formatted_results->MinimumRent.'</td>';
echo '<td>'.$formatted_results->MaximumRent.'</td>';
echo '</tr>';
}
echo '</table>';
?>
a simple get will do it.
$.get("data.php", function(data){ // GET data from page "data.php"
$("#result").html(data); // display data in a div with id "result"
});
Consider if your index.html contains below code then you can call ajax call in your script of html file. Here it is working code (consider index.html and date.php both are at the same place)
index.html
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="result">
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$.get( "data.php", function( data ) {
$( ".result" ).html( data );
});
});
</script>
And data.php file contain code as given by you
data.php
<?php
$pullData = file_get_contents('https://api.rentcafe.com/rentcafeapi.aspx?requestType=apartmentavailability&APIToken=OTI4MjI%3D-eiBNyIvyQA8%3D&propertyCode=p0494361');
$results = json_decode($pullData);
//Table columns
echo '<table>
<tr>
<th>Apartment Name </th>
<th>Beds</th>
<th>Baths</th>
<th>Floor Plan Name</th>
<th>Minumum Rent</th>
<th>Maximum Rent</th>
</tr>';
//Iterate throught the API data and return only required columns
foreach($results as $formatted_results){
echo '<tr>';
echo '<td>'.$formatted_results->ApartmentName.'</td>';
echo '<td>'.$formatted_results->Beds.'</td>';
echo '<td>'.$formatted_results->Baths.'</td>';
echo '<td>'.$formatted_results->FloorplanName.'</td>';
echo '<td>'.$formatted_results->MinimumRent.'</td>';
echo '<td>'.$formatted_results->MaximumRent.'</td>';
echo '</tr>';
}
echo '</table>';
?>
In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
I am new to ajax, I am trying to view, add, edit and delete data of mysql database without refreshing the tab or in other words using ajax on this table:
I have done the view part, *edited but I can not figure out how to edit or delete *. I know it is a very long task, but I have found no solution on the internet.. Thanks in advance
HTML Code:
<html>
<head>
<title>View Data Without refresh</title>
<script language="javascript" type="text/javascript" src="script/jquery-git.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
(function() {
$.ajax({
type: "POST",
url: "display.php",
dataType: "html",
success: function(response){
$("#responsecontainer").html(response);
}
});
});
});
</script>
</head>
<body>
<fieldset><br>
<legend>Manage Student Details</legend>
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Class</th>
<th>Section</th>
<th>Status</th>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
</fieldset>
<input type="button" id="display" value="Add New"/>
</body>
</html>
PHP Display Code:
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
echo "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
echo "<tr>";
echo "<td width='13.5%'>$data[0]</td>";
echo "<td width='21%'>$data[1]</td>";
echo "<td width='19.5%'>$data[2]</td>";
echo "<td width='24%'>$data[3]</td>";
echo "<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
echo "</tr>";
}
echo "</table>";
?>
If your connection, sql query and php response is ok and
I want it to be automatically done
means you want run ajax on page loading. Then, Output of php should be at last instead in each iteration.
<?php
include("connection.php");
$sql = "select * from tbl_demo";
$result=mysqli_query($db,$sql);
$output = "<table class='myTable'>";
while($data = mysqli_fetch_row($result))
{
$output .="<tr>";
$output .="<td width='13.5%'>$data[0]</td>";
$output .="<td width='21%'>$data[1]</td>";
$output .="<td width='19.5%'>$data[2]</td>";
$output .="<td width='24%'>$data[3]</td>";
$output .="<td><span class='edit'>Edit</span> | <span
class='delete'>Delete</span></td>";
$output .="</tr>";
}
$output .="</table>";
echo $output;
?>
To make edit/delete you need to pass or redirect page with action to other page named controller. After making changes again you need to redirect index/view data page or use ajax if you don't want to refresh/redirect page.
My script fetchs and insert some data from db and displays to the user then I decied to slightly change my code and add some functionality.For example what if any of textbox is empty so that I have added a java script file that controls this sitituation.Bu I cant get the value of textboxes values from index .php file
this is index.php file
<?php
$records = array();
$db = new mysqli("localhost", "root", "", "app");
if (!empty($_POST)) {
$first = $_POST["first"];
$last = $_POST["last"];
$bio = $_POST["bio"];
$insert = $db->prepare("Insert into people (first,last,bio,created) values(?,?,?,NOW())");
$insert->bind_param("sss", $first, $last, $bio);
if ($insert->execute()) {
header("location: index.php");
}
}
if ($result = $db->query("select * from people")) {
if ($result->num_rows) {
while ($row = $result->fetch_object()) {
$records[] = $row;
}
$result->free();
}
} else {
$db->error;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="sites.js"></script>
<title>Title</title>
</head>
<body>
<?php
if (!count($records)) {
echo "no";
} else {
?>
<table>
<tr>
<td>First</td>
<td>Last</td>
<td>Bio</td>
<td>Created</td>
</tr>
<?php
foreach ($records as $r) {
?>
<tr>
<td><?php echo $r->first; ?></td>
<td><?php echo $r->last; ?></td>
<td><?php echo $r->bio; ?></td>
<td><?php echo $r->created; ?></td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
and this is the html markup
<form action="" method="post">
First <input type="text" id="first"><br>
last <input type="text" id="last"><br>
Bio <input type="text" id="bio"><br>
<button id="submit" value="click me!!"></button>
</form>
</body>
</html>
I am trying to get inputs values from index file like this below But it doesnt work this way It returns object
$(document).ready(function () {
$('#submit').click(function () {
var name=$('#last');
alert(name);
});
});
thank in advance
When selecting an element with
$('#last')
you are getting the entire element in return. With that, you can use the val() method to retrieve the elements value:
var name = $('#last').val();
This will not return the value of name field:
var name=$('#last');
You can use like:
var name=$('#last').val();
Also note that, you are missing the name attribute in input fields. Without name attribute you can't get the value in $_POST.
You are referring to the object so you will get the object.
var name=$('#last');
If you need the value you have to ask for it:
var name=$('#last').val();
I'm trying to update the two locked textboxes with information that I get from my database. I enter a phone number in the "Telefon" checkbox, and I want it to get the firstname and lasttname for that phone number. Which works by the way, but it's not the way I want it. I want the information to be automatically put into the textboxes without refreshing the page. and for some odd reason my code got split in two here. I've tried to look for a solution for hours. I'm very new to coding, and I would love some help!
<?php
SESSION_START();
$output = NULL;
if(isset($_POST['btn_checkTelefon'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
while($rows = $resultSet->fetch_assoc()) {
$fornavnoutput_Database = $rows['Fornavn'];
$etternavnoutput_Database = $rows['Etternavn'];
}
echo '<script type = "text/javascript">';
echo 'function sayHi() {';
echo 'val1 = document.getElementById("telefon_Input").value;';
echo 'if(val1 == "") {';
echo ' alert("Vennligst skriv inn ditt telefon nummer!");';
echo '}';
echo 'if(val1 !== "") { ';
echo ' document.getElementById("check_Fornavn").value = "<?php echo $fornavnoutput_Database?>";';
echo ' document.getElementById("check_Etternavn").value = "<?php echo $etternavnoutput_Database?>";';
echo '}';
echo '}';
echo '</script>';
} else {
$output = "No results";
}
}
$fornavnoutput_Database2 = "Fornavn";
$etternavnoutput_Database2 = "Etternavn";
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
</script>
<script type = "text/javascript"></script>
<title></title>
</head>
<body>
<?php
include 'connectdb.php';
?>
<form name="form1" action="">
<table id="valgt_skap_tabell" class="bokssvartabell">
<tr>
<td>Valgt skap</td>
</tr>
<tr>
<td>
<input class="bokssvarskjema" type="text" name="Valgt skap" disabled value= <?php
if(isset($_POST["radios"])){
echo $_POST["radios"];
} else {
//header('location: index.php');
} ?>>
</td>
</tr>
</table>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button type="button" name ="btn_checkTelefon" id="sjekkTelefon" onclick = "sayHi()">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
</form>
<?php echo $output; ?>
</body>
You need to use AJAX for this. Example $.ajax() -> shortcuts $.post(), $("id").load("url"), ... Look it up a lot in depth explanation about these on stackoverflow.
Please never mix JavaScript with php.
Use it in separate file.
Edit: So have you fixed it yet?
The easier way to load paged dynamicaly is with load method + actions. $.post is used if you need to do something with returned data from php. I will give you example of load.
I will give a proper example how to code.
Universal function for a link that look at href value and load HTML parts (form in this case) from PHP dynamicaly to your page, you do need to implement actions or just call your ordinary page if you have only one default action there. I use jQuery library here. This script must be in separate file else it will work but you will get a sync warning in your console.
$(function() {
$('a').on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var URL = $(this).attr('href');
$('body').load(URL, 'form');
})
})
php example
prefered showsomethingfunction in separate file like showfunctions.php
function myLinks() {
echo "<a href='index.php?action=showsomething'>showsomething</a>"
}
index.php + included showfunctions.php
<?php
myLinks();
if(isset($_GET["action"]){
// do your ordinary thing like open connection with database.
switch($_GET["action"]))
{
case "showsomething":
//show showsomething() function with html
break;
//further you can add more action instead of showsomething if you have several links
}
//close database.
}
?>
You need to separate your code else it will be a mess if it gets even more complicated. HTML code must be ONLY in showfunctions.php for example in function to call for actions.
Code is not tested but I think it will work. This code will also work without javascript but then it will just reload pages.
You have to use jQuery $.post() for that.
first You have to create php file which will process Your data.
For example lets create file query.php with the following content:
<?php
if(isset($_POST['telefon_Search'])) {
require 'connectdb.php';
$telefon_Search = $connect_DB->real_escape_string($_POST['telefon_Search']);
$sql = "SELECT * FROM elever WHERE Telefon = '$telefon_Search'";
$resultSet = $connect_DB->query($sql);
if($resultSet->num_rows > 0) {
$row = $resultSet->fetch_assoc();
echo json_encode($row);
}
}
next on Your page You have to create function which will send phone number to our query.php file and which will return Name and Surname if they exist.
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
var user = $.parseJSON(data);
$('#check_Fornavn').val(user.Fornavn);
$('#check_Etternavn').val(user.Etternavn);
});
});
and complete html will looks like:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style2.css?<?php echo time(); ?>" />
<title></title>
</head>
<body>
<table id="telefon_tabell" class="bokssvar_tabell">
<tr>
<td>Telefon:</td>
</tr>
<tr>
<td><input type="text" name="telefon_Search" id="telefon_Input" maxlength=8"><br></td>
</tr>
<tr>
<td><button name ="btn_checkTelefon" id="sjekkTelefon">Sjekk</button></td>
</tr>
<div id="d1"></div>
</table>
<table id="opplysninger_tabell" class="bokssvartabell">
<tr>
<td>Fornavn:</td>
<td>Etternavn:</td>
</tr>
<tr>
<td><input type="text" name="Fornavn" disabled id="check_Fornavn"></td>
<td><input type="text" name="Etternavn" disabled id="check_Etternavn"></td>
</tr>
</table>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$('#sjekkTelefon').click(function (){
$.post('query.php', { telefon_Search : $('#telefon_Input').val() }, function (data){
$('#check_Fornavn').val(data.Fornavn);
$('#check_Etternavn').val(data.Etternavn);
});
});
</script>
</body>
</html>