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>';
?>
Related
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>";
}
?>
I am trying to refresh my table when the user clicks the button. This is because when the user clicks the button that row will be moved to the next table. (Not in this code example to make it simpler). How the tables are created are with the php code which executes in index code.php. Indexcode.php creates the variable $waiting which is then fetched in index.php and used to populate the table. When the button is clicked a request is sent to indexcode.php which updates the mysql tables. This is why I want to refresh the tables to display the new updated information. I have tried quite a few ways but to no avail.
index.php
<html>
<style>
<?php include 'table.css'; ?>
</style>
<?php include 'indexcode.php'; ?>
<script src="js/jquery.js"></script>
<script>
function orderPacked(val) {
$.ajax({
type: "POST",
url: 'indexcode.php',
data: "packed=" + val,
success: function(){
var container = document.getElementById("yourDiv");
var content = container.innerHTML;
container.innerHTML= content;
}
});
}
</script>
<h1> <center> Warehouse </center></h1>
<p><center>This is for warehouse use</center></p>
<body>
<h2 class="text-waiting">These orders need to be packed</h2>
<body>
<table id="wtable" class="waiting-table" cellpadding="11"><tr>.
<th>Order ID</th><th>Customer</th><th>Vendor</th><th>Address</th>.
<th>Cart_ID</th><th>Cart</th><th>Checked</th></tr>
<?php while($row = mysqli_fetch_row($waiting)){
?>
<tr>
<?php
echo '<td>',$row[0],'</td>';
echo '<td>',$row[1],'</td>';
echo '<td>',$row[3],'</td>';
echo '<td>',$row[7],'</td>';
echo '<td>',$row[2],'</td>';
echo '<td>',"items",'</td>';
?>
<td>
<button onclick="orderPacked('<?php echo $row[0]; ?>')" id="button"
name="packed" >Packed</button>
</td>
</tr>
<?php } ?>
</table>
</body>
</html>
indexcode.php
...
$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state =
'waiting'");
$stmt->execute();
$waiting = $stmt->get_result();
$stmt = $conn->prepare("SELECT * FROM sale WHERE wh_state = 'packed'");
$stmt->execute();
$packed = $stmt->get_result();
$stmt->close();
// define variables and set to empty values
$orderErr = "";
$order = "";
if (empty($_POST["packed"])) {
$orderErr = "Error";
else {
$orderp = test_input($_POST["packed"]);
// update the state of the sale
$stmt = $conn->prepare("UPDATE sale SET wh_state = 'packed' WHERE id = '{$orderp}'");
$stmt->execute();
$waiting = $stmt->get_result();
$stmt->close();
}
}
...
when creating table in php.make a id for every row.
get the result from ajax response(update row).so you can update the row dynamically with the id with updated data with javascript.
`
<?php
echo "<tr id='id_".$row[0]."'>";
echo '<td>',$row[0],'</td>';
echo '<td>',$row[1],'</td>';
echo '<td>',$row[3],'</td>';
echo '<td>',$row[7],'</td>';
echo '<td>',$row[2],'</td>';
echo '<td>',"items",'</td>';
?>
<td>
<button onclick="orderPacked('<?php echo $row[0]; ?>')" id="button_<?php
echo $row[0]; ?> "
name="packed" >Packed</button>
</td>
</tr>
<?php } ?>`
and also make sure to use unique id's for html elements.
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.
How Delete row in table html using ajax and php,
I need delete row in html table select row and click button delete make delete using ajax Currentally can make delete without ajax but I need delete row and stay on page without make submit on other page
code javaScript
function getDelete()
{
$.ajax({
type:"post",
//dataType:"json",
data:"id="+id,
url:"delete_address.php?id=$id", // url of php page where you are writing the query
success:function(json)
{
},
error:function(){
}
});
}
code html and php
<?php
$resualt=mssql_query("SELECT * FROM Address where user_id='$UserId' ") ;
echo "<table border='1' class='imagetable' id='imagetable'
width='400px' >\n";
echo '<thead>'.'<tr>';
echo '<th>Street</th>'.'<th>Quarter</th>'.
'<th>From</th>'.'<th>To</th>'.'<th>Notes</th>';
echo '</tr>'.'</thead>';
echo '<tbody>';
while ($row = mssql_fetch_assoc($resualt)) {
$fromDate=$row['from_date'];
$toDate=$row['to_date'];
echo " <tr onClick='myPopup($row[id])'".
( $_GET['id'] == $row['id'] ?
"style='background-color: green;'":"").">\n"."<td >
{$row['street']} </td>\n".
"<td>{$row['quarter']}</td>\n"."<td>$fdate2</td>\n".
"<td>$tdate2</td>\n"."<td>{$row['other_info']}</td>\n";
}
echo '</tbody>';
echo "</table>\n";
?>
<?php
echo"<a class='button-link' onClick='getDelete()'>delete</a>";
?>
code sql query
<?php
$idEmploye=$_GET['id'];
$userId=$_GET['user_id'];
$db_host = 'MOHAMMAD-PC\SQL2005';
$db_username = 'sa';
$db_password = '123321';
$db_name = 'db_test';
mssql_connect($db_host, $db_username, $db_password);
mssql_select_db($db_name);
mssql_query("DELETE FROM Address
WHERE id='$idEmploye' ; ") or die(mssql_error()) ;
echo '<script language="javascript">';
echo 'alert("successfully deleted ")';
echo '</script>';
echo "<script>setTimeout(\"location.href ='address.php';\",10); </script>";
?>
Any Help Very Thanks
Try this solution
HTML:
<table>
<tr>
<td>Username</td>
<td>Email</td>
<td>Action</td>
</tr>
<tr>
<td>TheHalfheart</td>
<td>TheHalfheart#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="1" value="Delete"/>
</td>
</tr>
<tr>
<td>freetuts.net</td>
<td>freetuts.net#gmail.com</td>
<td>
<input type="button" class="delete-btn" data-id="2" value="Delete"/>
</td>
</tr>
</table>
We have two button's properties call data-id and class delete-btn
AJAX jQuery:
<script language="javascript">
$(document).ready(function(){
$('.delete-btn').click(function(){
// Confirm
if ( ! confirm('Are you sure want to delete this row?')){
return false;
}
// id need to delete
var id = $(this).attr('data-id');
// Current button
var obj = this;
// Delete by ajax request
$.ajax({
type : "post",
dataType : "text",
data : {
id : id
},
success : function(result){
result = $.trim(result);
if (result == 'OK'){
// Remove HTML row
$(obj).parent().parent().remove();
}
else{
alert('request fails');
}
}
});
});
});
</script>
In PHP:
Get the ID and delete
Reponse OK if success
Sorry i'm learning English, please fix if its bad
I am using PHP & MySQL along with AJAX & jQuery to show contents from my database table.
PHP: serverside language as usual.
jQuery: to convert UTC time to local time based on user location. Thanks to jQuery localtime plugin :)
AJAX: to show contents of page2 into page1 on selecting a value from a drop down menu
Total no of pages: 2
Page1.php
I have an HTML table to which I show contents of all users. One of the values fetched from database is a UTC datetime variable.
To convert it into user's local time, I simply used a jQuery plugin. All that I had to do was add
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
the above given files & then add a span <span class="localtime"> </span> in my table & echo the datetime variable into it. Viola! UTC time is now converted into user's local time.
In that same page, I have a dropdown menu showing list of all users from my database table. ANd on the onchange property of the drop down menu, I have called an AJAX function. This function will pass the username to page2.php & database opertaions are done in page2.php & results corresponding to that user is calculated & shown into an HTML table similar like to the HTML table I have in page1.php.
But in this table, UTC remains as such even though I tried adding the jQuery files in that page also. Why the jQuery localtime plugin didn't convert UTC time in page2 to localtime when it did the same in page1???
Here are two screen shots.
Page 1 before AJAX content loaded
Page1 after AJAX content loaded
Page1:
<html>
<head>
<title>Converting UTC time to Local time</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
function value_pass_func(uname)
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()//callback fn
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showtable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","page2.php?variable="+uname,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT distinct(user) FROM pagination ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
</br>
</br>
</br>
<select id="ddl" name="ddl list" onchange="value_pass_func(this.value);">
<option selected value="">select any</option>
<?php
if($count>0)
{
while($row=mysqli_fetch_array($res))
{
$now=$row['user'];
?>
<option value="<?php echo $now; ?>"><?php echo $now; ?></option>
<?php
}
}
?>
</select>
</br>
</br>
<?php
$query1="SELECT * FROM pagination ORDER BY id ASC";
$res1 = mysqli_query($connection,$query1);
$count1 = mysqli_num_rows($res1);
if($count1>0)
{
?>
<div id="showtable">
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row1=mysqli_fetch_array($res1))
{
$idd=$row1['id'];
$post=$row1['post'];
$username=$row1['user'];
$datetime=$row1['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<?php } ?>
</body>
</html>
Page2:
<?php
$un=$_GET["variable"];
$connection = mysqli_connect('localhost','root','','dummydb') or die(mysqli_error($connection));
$query="SELECT * FROM pagination where user='".$un."' ORDER BY id ASC";
$res = mysqli_query($connection,$query);
$count = mysqli_num_rows($res);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script type="text/javascript">$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");</script>
<table class="table table-bordered table-responsive table-striped" border="1">
<thead>
<tr >
<th>id</th>
<th>post</th>
<th>user</th>
<th>now</th>
</tr>
</thead>
<tbody>
<?php
while($row=mysqli_fetch_array($res))
{
$idd=$row['id'];
$post=$row['post'];
$username=$row['user'];
$datetime=$row['now'];
?>
<tr>
<td><?php echo $idd; ?></td>
<td><?php echo $post; ?></td>
<td><?php echo $username; ?></td>
<td><span class="localtime"> <?php echo $datetime; ?></span></td>
</tr>
<?php
}
?>
</tbody>
</table>
You're loading jquery.. so I advise you to use it
The most simple answer to your question is to run this after your innerHTML replacement:
$.localtime.format(".localtime");
This will evaluate all of the elements again.
I suggest you do the following:
Use jquery's AJAX (link) to GET your table data.
Deliver your table data using JSON (link).
Personally I prefer to use Moment.js (link) to format my dates.
A basic jquery example..
Scripts on page1:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/jquery.localtime-0.5.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script>
$.localtime.setFormat("yyyy-MM-dd HH:mm:ss");
function value_pass_func(uname)
{
$.ajax({
type: "GET",
url: "page2.php",
data: { variable: uname },
dataType: html
}).done(function(data) {
$("#showtable").innerHTML = data;
$.localtime.format(".localtime");
});
}
</script>
And drop those script tags in page2.
I haven't tested that localtime script but it probably does it's thing when fired