Database Driven Page Content - javascript

I am trying to make a facebook style wall on my website. The goal is to insert form data, validate all forms as required, and store this data into a database. Simultaneously and separately I want all data stored in this database to be posted into a div that acts as the facebook wall.
I seem to have accomplished storing the data from the form. I can also retrieve all data in the database except it only does it when I submit the form. Which means no page content unless the user submits a post.
How can I populate my page with rows from my database when a user opens the page or before?
Please help!
Here is my php which stores and prints data when the html form is submitted.
<?php
// Create connection
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO test (school, confession)
VALUES
('$_POST[school]','$_POST[confession]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
// print $_POST['college']."-<br />".$_POST['confession'];
$result = mysqli_query($con,"SELECT * FROM test");
while($row = mysqli_fetch_array($result))
{
echo "#" . $row['ID'] . " " . $row['confession'];
echo "<br>" . "#" .$row['school'];
echo "<br>" . "<br>";
}
mysqli_close($con);
?>
Here is my JS which posts to a div called content.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#content').html(data);
});
}
});
});

Another approach is to load data on mouse scroll like:
//approx this
$(document).ready(function () {
var flg='1';
$(window).scroll(function () {
console.log($(document).scrollTop());
if ($(document).scrollTop() >299){
if(flg=='1')
{
$.post( 'link to server side code', function( data ) {
$('#morefrom').html(data.htmls);
},'json');
flg='0';
}
}
});});
This way you can load data on a specific mouse scroll value(like if a user gets on the bottom of the page you load new rows)
scrollTop docs

You can use a JavaScript Timer which will ticks after certain interval and load your Data, plus you must have to write a function that will just fetch the Data in your test.php file
function dataLoader()
{
//load Data with GET Request $.get(. . . );
}
dataLoader();
setInterval(dataLoader, 1000);
or the Second option will to be use jquery Timer Library to achieve performance

Thanks for the replies I solved the problem. I just called the php on load.
$(document).ready(function(){
$("#subform").validate({
submitHandler: function(form) {
// do other stuff for a valid form
$.post('test.php', $("#subform").serialize(), function(data) {
$('#subform').html(data);
});
}
});
});

Related

Alert when value in PHP table changes

I have two sheets. The control displays a list of job details that also contains a column that echos the notes on the active job, and the other sheet is where the operator can attach a note.
What I need to do is alert the user on the control page that the note for a job has been changed, which would happen after the operator submits the note.
Currently, I have a cell that highlights red when there is a note present, but want to actively send an alert when there is a new note.
I've tried an onChange() function but it wouldn't alert until I made an input field and changed it myself on the control page. I also tried the .change function but that didn't work either.
The query sent from the operator page to the SQL database is:
UPDATE operations
SET notes=$notes
WHERE jobID=$jobID
AND operation=$operation"
The code to echo the red cell on the control page is this PHP:
$conN = mysqli_connect(DB_HOST, DB_USER);
if (!$conN) {
die('Could not connect: ' . mysqli_error($conN));
} // Check Connection
mysqli_select_db($conN,"jms");
$jid = $row['jobID'];
$opn = $row['operation'];
$highlight = mysqli_query($conN,
"SELECT notes FROM operations WHERE jobID=$jid AND operation=$opn"
);
while ($data = mysqli_fetch_array($highlight))
if (isset($data['notes']) && $data['notes'] != "") {
echo "<td id='notes' style='background-color:red;width:1%;'>" .
"<input class='target' type='text' value='" .
$data["notes"]. "' >" . "</td>";
} else {
echo "<td style='background-color:white;width:1%;'>" . "</td>";
}
echo "</tr>"; // End the row
$index++;
While the cell that is being echo'd as red has an if (isset()) function to display red if there is a note in the database for the specific job and operation.
EDIT:
Here is the Javascript I've been trying to call with the onChange function:
function newNote() {
var jobID = "X";
var operation = "Y";
alert("New note added to Job No. "+jobID+" at Operation No. "+operation);
}
As you can see, its a very simple piece of script, so I ended up just simplifying the process and using a simple alert of text as a test.
you can do it by JQuery or JavaScript , what you need is to immediately detect any change of DB records by sending request and then receiving response .
use ajax function by either jQuery or java script and make the post target your mentioned control page , and alert the response.
one example by jquery :
$(document).ready(function(){
$.ajax({
type: "POST",
url: "yourcontrolpage",
data: { jid: jid ,opn:opn},
success: function(html) {
alert(html);
}
}); });
for example , you can retrieve the number of records or the latest record , so in the next request you can determine whether there is a change so alert will be executed or there is no change so nothing will be happened

How can i load database content via ajax before a filter keyup is pressed?

I have this codes below. It works when a filter parameter is presssed on keyup. but i need the content of the database to load via ajax as soon as the page is ready even when no filter search is initiated.
here are my codes
jquery
<script type="text/javascript">
$(document).ready(function(){
$('.autosuggest').keyup(function() {
var search_term = $(this).attr('value');
$.post('actionSessionsearch.php', {search_term: search_term}, function(data){
$('.divDisplay').html(data);
});
});
});
</script>
php
<?php
include_once('../includes/dc_conect.php');
if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
echo "hoho";
}
else
{ $search_term=$_POST['search_term'];
$sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
$resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
$dbfieldSession=mysql_fetch_assoc($resultSession);
$countSession=mysql_num_rows($resultSession);
do{
echo $dbfieldSession['session_name'].'<br>';
}while($dbfieldSession=mysql_fetch_assoc($resultSession));
}
?>
it only retireves when i enter a value into the search box. I want to have my database details display even when the filter has not been initiated!
You could do following things:
PHP
if((!isset($_POST['search_term'])==true) and (!isset($_POST['search_term'])!=NULL)){
/* Load data from Database here, something like SELECT * FROM sessions;*/
}
else
{ $search_term=$_POST['search_term'];
$sqlSession = "SELECT * FROM sessions WHERE session_name LIKE '%$search_term%'";
$resultSession=mysql_query($sqlSession, $link) or die (mysql_error());
$dbfieldSession=mysql_fetch_assoc($resultSession);
$countSession=mysql_num_rows($resultSession);
do{
echo $dbfieldSession['session_name'].'<br>';
}while($dbfieldSession=mysql_fetch_assoc($resultSession));
}
JS
Call your AJAX function inside $(document).ready(function(){...}) and use $.get instead of $.post

Passing values from a div containing list from another page

Hi I am trying to pass values using 'post' from three drop down lists to the database using php script where I insert values into the database with values of the three lists
previously I retrieved a list from another page into a div time.php using jquery ajax call
code for which looks like this :-
//This script uses jquery and ajax it is used to set the values in
// the time field whenever a day is selected.
$(document).ready(function(){
$("#day").change(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor,
success:function(data){
$("#time").html(data);
}
});
});
});
code for the html section looks something like this:-
<select id="doctor">some options</select>
<select id="day">some options</select>
<div id="time"> </div>
Now the values from the two lists are going through fine. But the one I retrieved into the div is not going through. Could you point me in the right direction?
Thanks in advance.
//The php script for insertion
<?php
session_start(); //Use this to include session variables
$con=mysqli_connect("localhost","clinic","myclinic","myclinic");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "INSERT INTO appointment(username, doctor, day, time) VALUES('$_SESSION[username]', '$_POST[doctor]', '$_POST[day]', '$_POST[time]')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header("location:login_success.php");
?>
If you want to retrive div content like input, select etc
You have to get it like
var time = $("#time").html();
Your code will be
Add a button to your page
<input type='button' value='Send' id='send'>
Then add
$(document).ready(function(){
$("#send").click(function(){
var day=$("#day").val();
var doctor=$("#doctor").val();
var time = $("#time").find("select").val();
$.ajax({
type:"post",
url:"time.php",
data:"day="+day+"&doctor="+doctor+"&time="+time, //add param
success:function(data){
}
});
});
});

AJAX to call PHP file which removes a row from database?

Alright, so I asked a question yesterday regarding how to save the blog posts that a user makes. I figured out the database side of it, and that works fine. Now, I want to REMOVE a blog post based after clicking an onclick button. Through my hours of digging through the web, I've found calling an jQuery AJAX function is the best way to go about it. I've been tooling around with it, but I can't get this working.
Blog code retrieved from database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error());
$database = mysql_select_db("...") or die(mysql_error());
$query = mysql_query("SELECT * FROM template") or die(mysql_error());
$template = mysql_fetch_array($query);
$loop = mysql_query("SELECT * FROM content ORDER BY content_id DESC") or die (mysql_error());
while ($row = mysql_fetch_array($loop))
{
print $template['Title_Open'];
print $row['title'];
print '<button class="deletePost" onClick="deleteRow(' . $row['content_id'] . ')">Remove Post</button>';
print $template['Title_Close'];
print $template['Body_Open'];
print $row['body'];
print $template['Body_Close'];
}
mysqli_close($connection);
This creates the following HTML on home.php:
<div class="blogtitle" class="post3">Title
<button class="deletePost" onClick="deleteRow(3)">Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
Which should call my remove.js when button is clicked (This is where I start to lose what I'm doing):
$function deleteRow(id){
$.ajax({
url: "remove.php",
type: "POST",
data: {action: id}
});
return false;
};
Calling remove.php (No idea what I'm doing):
$con=mysqli_connect("...","...","...","...");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$id = $_POST['action'];
$query = mysql_query("DELETE FROM content WHERE content_id=$id") or die(mysql_error());
My goal here is to REMOVE the row with the ID from the table which would in turn remove the blog post entirely since it won't see the row when it loops through the database table.
Any ideas?
Thanks for your help,
Kyle
couple of issues in your original code: the functions in Jquery shouldn't use a $ sign at the beginning and since you need to pass a single value I would use the query string rather than the POst, and instead of calling the "die" in php I would use the affected rows to return the callback of whether or not the value was deleted. But this is just my approach, there other ways I'm sure.
Here are little improvements in you code:
//HTML
<div class="blogtitle" class="post3">Title
<button class="deletePost" data-item="3" >Remove Post</button></div>
<div class="blogbody" class="post3">Content</div>
//JQUERY
jQuery(document).ready(function($) {
$('button.deletePost').each(function(){
var $this = $(this);
$this.click(function(){
var deleteItem = $this.attr('data-item');
$.ajax({url:'remove.php?action='+deleteItem}).done(function(data){
//colect data from response or custom code when success
});
return false;
});
});
});
//PHP
<?php
$id = $_REQUEST['action'];
$query = mysql_query('DELETE FROM content WHERE content_id="'.$id.'"');
$confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error';
?>
Hope this sample helps :) happy coding !
i hope this should help you i used this to remove items from my shopping cart project.
$(".deleteitem").each(function(e) {
$(this).click(function(e) {
$.post("library/deletefromcart.php",{pid:$(this).attr('prodid'), ajax:true},function(){
window.location.reload()
})
return false;
});
});

Dynamically delete MySQL data using AJAX and JS

Hi I'm trying dynamically remove database entries using JS and AJAX without refreshing whole page.
Here is my data.php file:
<?php
require_once('db.php');
if (isset($_GET['list'])) {
$query = "SELECT * FROM message";
mysql_query("SET NAMES 'UTF8'");
$qq=mysql_query($query);
$i = 1;
echo '<div id="rezult">';
while($ff = mysql_fetch_array($qq)){
echo '<div id="id'.$ff['id'].'">'.$i++.'. Name: '.$ff['name'].' Message:'.$ff['message'].'</div>';
}
echo '</div>';
}
?>
With this code I'm retrieving a data from mysql table:
index.php
function list() {
$.get('data.php?list=1', function(o) {
$('#list').html(o);
});
}
How to dynamically delete desired entry without refreshing a page?
tried to add this code below as a link to the entry, but it getting cut javascript:$.post( like that.
<a href="javascript:$.post('delete_post.php', { id: '$ff[id]' } );" class='delete_post' title='delete post'>delete post</a>
Thanks for advices
Be careful!, if someone make a call to your php file data.php?list=ANYNUMBER he will be able to delete any row, be sure you are using security tools to avoid that.If you use ajax and Jquery I think it will be easier.
try something like this:
$.ajax({
type: "POST",
url: "list.php",
data: { list: "1", session_id: session_ID }
}).done(function( msg ) {
alert( "Data deleted: " + msg );
});
where session_id is the value of the field (in your example is 1), session_id is when someone go to your page you assign him a SESSION_ID, after he click the delete button, you compare if the session ID that you assign is equal to the the session_id from the server (you avoid people from another site to call your list.php). If session_id from the ajax is equal to session session_id on the server allow to delete take a look to this: PHP Session Security

Categories

Resources