basic usage of AJAX with php for Database update and retrieval - php

(Just a heads up, its a Lengthy question but im sure its very basic question for a ajax-php coder)
Im trying to 'update db on some drag n drop event on one page' and 'reflect that change in other page without reload'. I have already written pretty much all the code, need your help in figuring out what is wrong. Here is the Html that I have written,
First_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="coconuts" style="float:left">
<div class="coconut1" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag1" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
<div class="coconut2" ondragover="allowDrop(event)" ondrop="drop(event)">
<img id="drag2" ondragstart="drag(event)" draggable="true" src="coconut.png">
</div>
</div>
<div class="gunnybag" style="float:right">
<div id="place1" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
<div id="place2" ondragover="allowDrop(event)" ondrop="drop(event)"></div>
</div>
</body>
so there are 2 drag-able coconuts and there are 2 placeholders(place1 & place2). What I want to do is when the coconuts are dragged and placed on one of the placeholders, database's values should be updated. (say when a coconut is placed in 1st placeholder, place_id 1 - true, place_id 2 - false)
For this, I'm making ajax call to a php file from JS's drop function like this..
JS_file:
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("coconut");
ev.target.appendChild(document.getElementById(data));
var state = true;
var id = ev.target.id;
$.ajax({
url: "db_update.php", //calling db update file.
type: "POST",
data: { id: id, state: state }, //2 variables place_id and its state(True/False)
cache: false,
success: function (response) { //I dont know what to do on success. Can this be left blank like, success: ?
$('#text').html(response);
}
});
}
This is my db_update,
db_update:
<?php
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
function begin()
{
mysql_query("BEGIN");
}
function commit()
{
mysql_query("COMMIT");
}
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
mysql_select_db("my_db", $con) or die(mysql_error());
$query = "UPDATE gunnybag SET state = '{$state}' where id='{$id}'"; //will this work? or am I doing something wrong here??
begin();
$result = mysql_query($query);
if($result)
{
commit();
echo "successful";
}
?>
On the receiving side I want to update the coconuts in the gunnybag without reloading the page, so I have written this ajax which uses db_fetch.php
ajx.js file:
window.onLoad = doAjax;
function doAjax(){
$.ajax({
url: "db_fetch.php",
dataType: "json",
success: function(json){
var dataArray = JSON.decode(json);
dataArray.each(function(entry){
var i=1;
if(entry.valueName==true){
$q('place'+i).css( "display","block" );
}
else{
$q('place'+i).css( "display","none" );
}
i=i++;
})
}
}).complete(function(){
setTimeout(function(){doAjax();}, 10000);
});
}
here is the db_fetch.php:
<?php
try{
$con=mysql_connect("sqlservername","myuname", "mypass") or die(mysql_error());
}
catch(Exception $e){
echo $e;
}
mysql_select_db("my_db", $con) or die(mysql_error());
$q = mysql_query("SELECT 'state' FROM 'gunnybag' "); //fetching all STATE from db
$query = mysql_query($q, $con);
$results = mysql_fetch_assoc($query);
echo json_encode($results); //making it JSON obj
?>
Finally my other page where this ajax is being called from.
Second_html_file:
<head>
<title>Coconuts into Gunnybags</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="ajx.js"></script>
//if i simply include the ajax script here will it be called
//automatically? i want this script to keep up with the changes in db.
</head>
<body>
<div class="gunnybag" style="float:right">
<div id="place1" style="display: ;"><img id="drag1" draggable="true" src="coconut.png"></div>
<div id="place2" style="display: ;"><img id="drag2" draggable="true" src="coconut.png"></div>
</div>
</body>
MAP:
First_html_file->JS_file->db_update :: Second_html_file->ajx.js->db_fetch.
Please point out what is wrong in this code, also respond to the //comments which are put along code.
Your response is much appreciated. Thanks! #help me get this right#
For ref I have hosted the files here, http://www.nagendra.0fees.net/admin.html & http://www.nagendra.0fees.net/cng.html

First thing I see is:
You say:
var id = event.target.id;
but you decalare ev in drop(ev)
so change that:
var id = event.target.id;
to:
var id = ev.target.id;
for starters.
Then you should use mysqli since mysql is deprecated:
Your code is also open for SQL-injections, so change:
$state = $_POST['state']; //getting my variables state 'n ID
$id = $_POST['id'];
to:
$state = ($_POST['state']) ? true : false;
$id = intval($_POST['id']); //make sure an integer

Related

What I should do to update if the table from the database keeps on changing

I have a task and I am going to explain on what my work should be like.
First of all, I use the $.get method to get the total numbers of rows from the table in the database and show the value to the html file.
After 1 hours or 2 hours or 2 days or longer, the total number of rows from the table change...
What I should do to update the total number of rows in the html file other than refreshing the page or reloading the page?
my code is found below:
calculatetotalattack.php
<?php
include 'config.php';
$con = mysqli_connect ($dbhost, $dbusername, $dbpassword) or die ('Error in connecting: ' . mysqli_error($con));
//Select the particular database and link to the connection
$db_selected = mysqli_select_db($con, $dbname ) or die('Select dbase error '. mysqli_error());
//Make A SQL Query and link to the connection
$totalattackview = mysqli_query($con, 'SELECT * FROM attackview'); // get number of row from attackview
//Calculate the total number of rows from the table
$totalofrowsattack = mysqli_num_rows($totalattackview);
echo $totalofrowsattack;
mysqli_close($con);
?>
HTML
<html>
<head>
<title>Updating the Total Number of the total rows</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="totalattack"></div>
<script type="text/javascript">
function totalAttacks(val) {
$('#totalattack').html(val);
}
$.get({
url: 'calculateTotalAttack.php',
dataType: 'text',
success: totalAttacks
});
</script>
</body>
</html>
Is there ways ?
You can just dynamically add rows or columns to your table in the html file and then display the data.
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
</script>
</body>
</html>
The insertRow() method creates an empty element and adds it to a
table.
Use the setInterval()/ setTimeout() method to continously call the function to make it dynamic.
Also since you don't know when the rows/columns will increase, you can constantly monitor for any change in the no. of rows in table using setInterval() and if there are any changes make the table grow.
U can use a time interval to call totalAttacks() each X time.
Here is the documetation: W3C
You can run $.get function by timer, like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title>Updating the Total Number of the total rows</title>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="totalattack"></div>
<script type="text/javascript">
function totalAttacks(val) {
$('#totalattack').html(val);
}
$(document).ready(function() {
var timer = setInterval(function() {
$.get({
url: 'calculateTotalAttack.php',
dataType: 'text',
success: totalAttacks
});
console.log('requesting changes');
}, 5000);
});
</script>
</body>
</html>
You can use ajax with jquery to upload your data dynamically like
$document.ready(){
$.ajax({
type: "POST",
url: "",
data: {
first_name: $("#namec").val(),
last_name: $("#surnamec").val(),
email: $("#emailc").val(),
mobile: $("#numberc").val(),
password: $("#passwordc").val()
},
success: function(response) {
//dynamically add your data from here like make the new data equal to old one
},
error: function(response) {
console.log(response);
}
});
}

Deleted rows removed from page but not from mysql database (PHP/jQuery)

I'm a complete beginner and have built a basic To-Do List application using PHP/jQuery. The application allows the user to add and remove tasks from a list (stored in a MySQL database).
I'm having issues with the delete function. When the delete button is clicked, it removes the task from the list but it must be remaining in the database, as it reappears once the page is refreshed.
I have no idea where I'm going wrong! Any help appreciated. See below code:
index.php :
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
<link rel="stylesheet" type="text/css" href="/style.css" media="all" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div class="main">
<div class="list">
<ul>
<?php
require("db_connect.php");
$query = mysql_query("SELECT * FROM tasks ORDER BY date ASC, time ASC");
$numrows = mysql_num_rows($query);
if($numrows>0) {
while ( $row = mysql_fetch_assoc( $query ) ){
$task_id = $row['task_id'];
$task_desc = $row['task_desc'];
echo '<li><span>'.$task_desc.'</span><img id="'.$task_id.'" class="delete" width="10px" src="images/delete.png" /></li>';
}
}
?>
</ul>
</div>
<form class="new" autocomplete="off">
<input type="text" name="new-task" placeholder="Add a new task..." />
</form>
</div>
</body>
<script>
add_task();
delete_task();
function add_task() {
$('.new').submit(function() {
var new_task = $('.new input[name=new-task]').val();
if(new_task !== '') {
$.post('add_task.php', { task: new_task }, function ( data ) {
$('.new input[name=new-task]').val('');
$(data).appendTo('.list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete').click(function() {
var current_element = $(this);
var task_id = $(this).attr('task_id');
$.post('delete_task.php', { task_id: task_id }, function() {
current_element.parent().hide().fadeOut("fast", function() {
$(this).remove();
});
});
});
}
</script>
delete_task.php :
<?php
$task_id = strip_tags( $_POST['task_id'] );
require("db_connect.php");
mysql_query("DELETE FROM tasks WHERE task_id='$task_id'");
?>
You have an error in your delete_task function. There is no such attr as 'task_id'. Try to replace
var task_id = $(this).attr('task_id');
With
var task_id = $(this).attr('id');
Besides #IvanGajic answer is correct, also write your delete query like this:
mysql_query('DELETE FROM tasks WHERE task_id="' . $task_id . '"');

Send argument to dynamic PHP nested inside a PHP page

I have two pages. test1.php and test2.php.
All I want to do is hit submit on test1.php and test2.php be displayed within a div. This is actually working fine, BUT I need to pass an argument to test2.php to limit the results shown from the mySQL database (there'll only ever be one result from a database of 3000 items).
To be honest, I think this is within the javascript, but just not sure how to go about it....
test1.php is
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
// Handler for .ready() called.
$('#SubmitForm').submit(function( event ) {
$.ajax({
url: 'test2.php',
type: 'POST',
dataType: 'html',
data: $('#SubmitForm').serialize(),
success: function(content)
{
$("#DisplayDiv").html(content);
}
});
event.preventDefault();
});
});
</script>
<body>
<div id="page">
<form id="SubmitForm" method="post">
<div id="SubmitDiv" style="background-color:black;">
<button type="submit" class="btnSubmit">Submit</button>
</div>
</form>
<div id="DisplayDiv" style="background-color:red;">
<!-- This is where test2.php should be inserted -->
</div>
</div>
</body>
test2.php is
$pageNum_test1 = 0;
if (isset($_GET['pageNum_test1'])) {
$pageNum_test1 = $_GET['pageNum_test1'];
}
$startRow_test1 = $pageNum_test1 * $maxRows_test1;
mysql_select_db($database_wing, $wing);
$query_test1 = "SELECT * FROM pilots";
$query_limit_test1 = sprintf("%s LIMIT %d, %d", $query_test1, $startRow_test1, $maxRows_test1);
$test1 = mysql_query($query_limit_test1, $wing) or die(mysql_error());
$row_test1 = mysql_fetch_assoc($test1);
if (isset($_GET['totalRows_test1'])) {
$totalRows_test1 = $_GET['totalRows_test1'];
} else {
$all_test1 = mysql_query($query_test1);
$totalRows_test1 = mysql_num_rows($all_test1);
}
$totalPages_test1 = ceil($totalRows_test1/$maxRows_test1)-1;
?>
<div id="page" style="background-color:yellow;">
<?php do { ?>
<?php
echo "Hello World.";
echo $row_test1['firstname']
?>
<?php } while ($row_test1 = mysql_fetch_assoc($test1)); ?>
</div>
<?php
mysql_free_result($test1);
?>
url: 'test2.php?pageNum_test1=' + num,
I think that's what you want.

Retrieve data from selected list element in Jquery

I'm new to the whole coding thing and have been learning a lot with yer help lately so I hope it may continue with the next problem I am having!
I have a Jquery list which is rendering perfectly and what it does is display some dummy info I've inputted that comes from a local MYSQL database. What I've done so far is that when the user clicks on one of the listed links it will bring them to the next page and say "You have selected link #" and the # tag in this instance represents the dealid number of the users selected list link.
What I'm trying to find out what to do is this:
With the information I've gained from the users selection (i.e. the selected dealid number) how can I then pass this back onto the database so I can find and retrieve the particular entry with that dealid number.
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/test/json3.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"'><h1>"+dat.name+"</h1><p>"+dat.dname+"</p></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
listObject.itemID = $(this).attr('id');
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
$('#index2 [data-role="content"]').html('You have selected Link' + listObject.itemID);
// var url="http://localhost/test/json9.php";
// $.getJSON(url, function(json){
});
var listObject = {
itemID : null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<a data-role="button" href="#page1" data-icon="star" data-iconpos="left">Get Deal </a>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
The PHP/Json file that is being referenced to create the original list (Json3.php) is as follows:
<?php
$link = mysql_pconnect("localhost", "root", "") or die ("Could not Connect to DB");
mysql_select_db("findadeal") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT r.restaurantid, r.name, r.image, d.dealid, d.dname, d.restaurantid
FROM restaurant r, deal d
WHERE r.restaurantid = d.restaurantid;");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"deals":'.json_encode($arr).'}';
?>
I'm running at a loss here as I've been looking for information on this for a while and cant seem to find what I'm looking for. I appreciate anyones help, I really mean it! Thanks in advance!! :)
you can simplify your javascript like this:
$(document).on('click', '#'+dat.dealid, function(event){
listObject.itemID = $(this).attr('id');
$.mobile.changePage( "#index2", { transition: "slide"} );
event.stopPropagation();
});
If you want to load the data of your item without reloading the page then you need to do an ajax request. If you don't mind reloading the page, redirect to http://domain.com/uri/whatever?id=<the_selected_id> then in your PHP script you can get the item using the get parameter $_GET['id'] and perform a query to get the data for this id.
UPDATE
You need a PHP script to retrieve the data from the database. This script is called like this: http://www.domain.com/foo/bar/my_script.php?id=<the_id_from_the_selection>
And your script should looks like this:
<?php
// Default value to return
$data = array('error' => 'No deal found');
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// Using PDO for the database connection, it's much better and avoid SQL injection
// Make sure the PDO extension is enable in your php.ini
$pdo = new \PDO('mysql:host=localhost;dbname=<SOMEDB>', '<USERNAME>', 'PASSWORD');
$sql = "SELECT * FROM deal WHERE id = :id";
$statement = $pdo->prepare($sql);
$statement->execute(array('id' => $_GET['id']));
$data = $statement->fetch(\PDO:FETCH_ASSOC);
}
echo json_encode($data);
// You don't need the closing PHP tag. Actually it's easier to debug if you don't use it.
Your ajax request (called when user select something, this is javascript) should look like this:
var dealId; // the selected deal id
$.ajax({
url : 'foo/bar/my_script.php',
data: {id: dealId},
type: "GET",
async: true,
onSuccess: function(response){
console.log(response); // look into the console to check the object structure
// Display your data here using dom selector and jquery
}
});

Inserting json data into html page in list

I'm trying to get information from mysql and post the information into an html page. Here's what I've got so far:This is my tenantlistmob.php
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tenanttemp");
while ($row = mysql_fetch_assoc($result))
{
$array[] = array($row['TenantFirstName']);
}
echo json_encode($array);
?>
When i call tenantlistmob from browser directly it shows [["Humayun"],["Sahjahan"],["Bayezid"],["Bayezid"],["Asaduzzaman"],["Mouri"]] where firstnames are comming. I like to use this name in html page. my html page is
<!DOCTYPE HTML>
<html>
<link rel="stylesheet" href="styles/main.css" />
<script type="text/javascript" src="jquery.js"></script>
<body>
<div id="output">this element will be accessed by jquery and this text replaced</div>
<script id="source" type="text/javascript">
$(function ()
{
$.ajax({
url: 'tenantlistmob.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data;
//var vname = data[1]; //get name
$.each(id, function (val)
{
$('#output').html(""+id);
});
}
});
});
</script>
<form id="formset">
<fieldset id="fieldset">
<h3 align="center">Tenant List</h3><hr/>
name1<br /><hr/>
name2 <br /><hr/>
</fieldset>
</form>
<a id="box-link1" class="myButtonLink" href="category1.php"></a>
</div>
</body>
</html>
My output(main.css) is like this
#output
{
color:#ffffff;
font-size : 20px;
margin : 0;
letter-spacing:1px;
width:480px;
}
I am getting the first name asHumayun,Sahjahan,Bayezid,Bayezid,Asaduzzaman,Mouri in top-left corner. But i like to get the name as list(name1,name2) with link. when i click on a name(name1,name2) it will show details of the name. How can I do this?
Thank in advance
It looks like your looking to iterate the JSON using JavaScript. Since you're using jQuery, you simply need to "iterate" the JSON result. Technically 0 comes before 1 in JavaScript.
var _result = $data[0];
$.each(_result, function (val)
{
console.log(val);
});
http://api.jquery.com/jQuery.each/
Try this:
<?php
include('connection.php');
$result = mysql_query("SELECT * FROM tenanttemp");
$array = array();
while ($row = mysql_fetch_assoc($result))
{
$array[] = $row['TenantFirstName'];
}
echo json_encode($array);
?>

Categories