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);
?>
Related
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 . '"');
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.
(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
am want to create a text box like google search text box...
What i have tried is When entered a character, using AJAX the words starting with that word will be displayed in a div its working fine but i want that it should work exactly like google search box.. Now the arrow keys are not working only by clicking the text will be selected
MY CODE
<style>
#resultDiv {
width:154px;
position:absolute;
left:121px;
top:30px;
}
p {
padding:0px;
margin:0px;
}
#resultDiv p:hover {
background-color:#999;
}
</style>
<script type="text/javascript">
$(document).ready(function(e) {
$('#resultDiv p').live('click',function(){
var value = $(this).text();
$('#word').val(value);
});
});
</script>
</head>
<body>
<form action="" method="post">
<label>Enter Your Word </label><input type="text" id="word"/>
<div id="resultDiv"></div>
</form>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
$('#word').keyup(function(e) {
$.ajax({
type: "POST",
url: "googleDropSearch.php",
data: "word="+this.value,
success: function(msg){
$('#resultDiv').html(msg);
$('#resultDiv').css('border-left','1px solid #ccc').css('border-right','1px solid #ccc').css('border-bottom','1px solid #ccc');
}
});
});
});
</script>
</body>
</html>
ACTION PAGE
<?php
$connection = mysql_connect('localhost','root','') or die("ERROR".mysql_error());
$connection = mysql_select_db('ajax',$connection) or die("ERROR".mysql_error());
if(!empty($_POST)):
if(isset($_POST['word']) && $_POST['word'] != ''):
/****************
Sanitize the data
***************/
$key =$_POST['word'];
$query = mysql_query("SELECT county FROM fl_counties WHERE county LIKE '$key%';");
$rows = mysql_num_rows($query);
if($rows != 0):
while($result = mysql_fetch_array($query)):
echo "<p>".$result[0]."</p>";
endwhile;
endif;//rows > 0
endif;//county not sent
endif;
?>
There is one useful plugin available in jquery.
Jquery Autocomplete
There is simple demo available you just have to pass an array to it.
Hope this would work for you.
I have an array that looks like that in a PHP page:
$page["1"] = array("element1","element2","element3","element4");
$page["2"] = array("element1","element2","element3","element4");
$page["3"] = array("element1","element2","element3","element4");
I need to retrieve some data from this array in a JAVASCRIPT file (JQUERY).
How can I import for example the elements4 $page[1][3],$page[2][3],$page[3][3] ?
I have seen many examples here with JSON but not like this one...
May be this can help you(Filename: getdata.php):
<?
if($_GET['ajax']==1){
$page = array(
array("element1","element2","element3","element4"),
array("element1","element2","element3","element4"),
array("element1","element2","element3","element4"),
);
echo json_encode($page);
}else{
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<button class="getdata" >Get Data</button><div class="jsdata"></div>
</body>
<script>
$('.getdata').click(function(){
$.ajax({
type:"POST",
url:"getdata.php?ajax=1",
success:function(data){
var res = eval("("+data+")");
$('.jsdata').html("$page[1][3],$page[2][3],$page[3][3] respectively:"+res[0][3]+","+res[1][3]+","+res[2][3]);
}
})
});
</script>
</html>
<? } ?>