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

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 . '"');

Related

How can I not open a link in jQuery UI

I use jquery-ui (v1.12.1).
https://jqueryui.com/tabs/#ajax (TABS LOAD AJAX)
$( function() {
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();
}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
I want to not open the tabs "herf" in the form of a link.
<div class="part" id="tabs">
<ul>
<li>Apple</li>
<li>Samsung</li>
<li>Sony</li>
<li>HTC</li>
</ul>
</div>
What's wrong with the code?
I modified this code.
I have extracted the following code from this site:
http://demo.webslesson.info/jquery-ui-tooltip-with-ajax-php/
But I want to write as the tab of Ajax.
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM tbl_student ORDER BY student_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="part" id="tabs">
<ul>
<?php
foreach($result as $row)
{
echo '<li><a id="'.$row["student_id"].'" href="#">'.$row["student_name"].'</a></li>';
}
?>
</ul>
</div>
<script>
$(document).ready(function(){
$("#tabs").tabs({
beforeLoad: function (event, ui) {
$('#preloader').show();
$.post('fetch.php', { id:$(this).attr('id') }, function(data){ result(data); });
if (ui.tab.data("loaded")) {
event.preventDefault();
$('#preloader').hide();
return;
}
ui.ajaxSettings.cache = false,
ui.panel.html('<img src="assets/ajax-loader.gif"> Loading...'),
ui.jqXHR.success(function() {ui.tab.data( "loaded", true ); $('#preloader').hide();}),
ui.jqXHR.error(function () {ui.panel.html("Couldn't load Data. Plz Reload Page or Try Again Later."); });
}
});
});
</script>
fetch.php
<?php
if(isset($_POST["id"]))
{
$query = "SELECT * FROM tbl_student WHERE student_id = '".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '
<img src="images/'.$row["image"].'" class="img-thumbnail" />
<h4>Name - '.$row["student_name"].'</h4>
<h4>Phone No. - '.$row["student_phone"].'</h4>
';
}
echo $output;
}
?>
When I click that tab, That text doesn't show.
Is jQueryUI code loaded incorrectly?

location.reload() make a difference with my DB

I realized a code for a rate system but when I select a vote, nothing change, when I reselect again a vote, it's ok ! BUT when I see my DB on phpmyadmin, the counter of vote has 1 clic in more than the counter of vote that I "echoed" on my page... why this difference of 1?
my note.js
$(function(){
$('.star').on('mouseover', function(){
var indice = $('.star').index(this);
$('.star').removeClass('full');
for(var i = 0; i<= indice; i++){
$('.star:eq('+i+')').addClass('full');
}
});
$('.star').on('mouseout', function(){
$('.star').removeClass('full');
});
var average = $('.average').attr('data-average');
function avaliacao(average){
average = (Number(average)*20);
$('.barra .bg').css('width', 0);
$('.barra .bg').animate({width: average+'%'}, 500);
}
avaliacao(average);
$('.star').on('click', function(){
var artigoId = $('.artigoDados').attr('data-id');
var ponto = $(this).attr('id');
location.reload();
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
avaliacao(retorno.average);
$('p.votos span').html(retorno.votos);
}, 'jSON');
});
});
My html code:
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
?>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/note.js"></script>
</head>
<body>
<?php
$artigoId = (int)$_GET['artigo'];
$artigos = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$artigos->execute(array($artigoId));
while($row = $artigos->fetchObject()){
echo '<h1>'.$row->titre_recette.'</h1>';
$calculo = ($row->pontos == 0) ? 0 : round(($row->pontos/$row->votos), 1);
echo '<span class="average" data-average="'.$calculo.'"></span>';
echo '<span class="artigoDados" data-id="'.$row->id_recette.'"></span>';
?>
<div class="barra">
<span class="bg"></span>
<div class="estrelas">
<?php for($i=1; $i<=5; $i++): ?>
<span class ="star" id="<?php echo $i;?>">
<span class="starAbsolute"></span>
</span>
<?php endfor;?>
</div>
</div>
<p class="votos"><span><?php echo $row->votos;?></span>votes</p>
<?php }?>
</body>
</html>
votar.php
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$artigo = (int)$_POST['artigo'];
$pontos = $_POST['ponto'];
$pegaArtigo = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$pegaArtigo->execute(array($artigo));
while($row = $pegaArtigo->fetchObject()){
$votosUpd = $row->votos+1;
$pontosUpd = $row->pontos+$pontos;
$average = round(($pontosUpd/$votosUpd), 1);
$update = $bdd->prepare('UPDATE sys_note SET votos = ?, pontos = ? WHERE id_recette = ?');
if($update->execute(array($votosUpd, $pontosUpd, $artigo))){
die(json_encode(array('average' => $average, 'votos' => $votosUpd)));
}
}
}
?>
You need to do location.reload(); after you the post, not before.
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
location.reload();
}, 'jSON');
There is no point to do the extra work inside the callback since you are reloading the page anyway.
Although, I would recommend you change the elements on the page via ajax instead of the crude location.reload();

Ajax request to the same PHP page gives no errors but doesn't work

I am making a product displaying page of an ecommerce website. The products are to be filtered by brands on the basis of brands that are checked by the customer. For this I have used an ajax request everytime a brand is checked. The problem is that the page cannot receive the get variables that i am sending to the same page. The ajax request is not giving any errors and also the chrome debugger side is also not showing any error at all. This is the page:
snapshot of the products page
And this is the code of the page:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<?php
session_start();
include('includes/pdo_connect.php');
include('includes/pdo_functions.php');
$logged_in;
$user_first_name;
if(isset($_SESSION['user'])){ //Determining if the user is logged in or not.
if($_SESSION['user']=='user'){
$user_id = $_SESSION['user_id'];
global $logged_in;
$logged_in = true;
global $user_first_name;
$user_first_name = $_SESSION['user_first_name'];
}
} else {
$_SESSION['user'] = 'guest';
$user_id = $_SERVER['REMOTE_ADDR'];
}
$cat;
if(isset($_GET['cat'])){
global $cat;
$cat = $_GET['cat'];
}
include('includes/logged_in.php');
if(isset($_GET['brand_list'])){
$brand_list = $_GET['brand_list'];
} else {
echo "<script>alert('value not received');</script>";
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="styles/list_style.css?<?php echo time(); ?>">
<link rel="stylesheet" type="text/css" href="styles/thickbox.css" media="screen">
<script type="text/javascript" src="js/jquery-3.1.1.js"></script>
<script type="text/javascript" src="js/thickbox.js"></script>
<?php
$where = array();
if(!empty($brand_list)){
echo "ajax working";
if(strpos($brand_list, ',')!==false){
$brand_choices = explode(',', $brand_list);
$barray = array();
foreach($brand_choices as $value) {
$barray[] = "brand_id = $value";
}
$where[] = '('.implode(' OR ', $barray).')';
} else {
$where[] = '(brand_id= '.$brand_list.')';
}
} else {
//echo "ajax not working ";
}
$w = implode(' AND ', $where);
$w = "where product_cat=$cat ".$w;
$filter_query = "select * from products $w ";
echo "filter query: ".$filter_query;
$first_load = 'filter';
function show_filtered(){
//echo "<script>alert('filter query working');</script>";
global $filter_query;
global $con;
global $brand_name;
try{
$stmt = $con->prepare($filter_query);
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $data) {
$product_id = $data['product_id'];
$product_cat = $data['product_cat'];
$product_brand = $data['product_brand'];
$product_title = $data['product_title'];
$product_price = $data['product_price'];
$product_desc = $data['product_desc'];
$product_image = $data['product_image'];
echo "
<div class='product_container $brand_name'>
<a href='details.php?pid=".$product_id."' alt='".$product_title."'>
<div class='img_div'>
<img src='admin/product_images/".$product_image."?".time()."' alt='".$product_title."'/>
</div>
<div class='index_product_desc'>".$product_title."</div>
<div class='index_product_price'>₹".$product_price."</div>
</a>
</div>
";
}
} catch(PDOException $e){
echo "Error in show_list(): ".$e->getMessage();
}
}
function show_brands(){
global $con;
global $cat;
global $brand_name;
try{
$query = "select * from cat_brand where cat_id = $cat";
$stmt = $con->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
//$brand = array();
foreach ($result as $data) {
$brand_id = $data['brand_id'];
//echo "<script>alert('$brand_id');</script>";
$query1 = "select * from brands where brand_id = $brand_id";
$stmt1 = $con->prepare($query1);
$stmt1->execute();
$result1 = $stmt1->fetchAll();
echo "<ul>";
foreach ($result1 as $data1) {
$brand_name = $data1['brand_title'];
echo "<li><input type='checkbox' value='$brand_id' id='$brand_name' class='brand_check' name='brandchoice'> $brand_name</li>";
}
echo "</ul>";
}
} catch(PDOException $e){
echo "Error in show_brands: ".$e->getMessage();
}
}
function show_price(){
}
?>
</head>
<body>
<div class="wrapper">
<header>
<div class="home_logo">
<a href="index.php">
<img src="images/skyshop_sumopaint.png" alt="Site Home">
</a>
</div>
<div class="login">
<?php user();?> |
<?php login_status(); ?>
</div>
<div class="form">
<form method="get" target="" name="searchbar_form">
<input type="text" name="searchbar" id="searchbar">
<input type="submit" id="search_button" value="Search">
</form>
</div>
</header>
<div class="menubar">
<div class="dropdown">
<button onclick="dropdownToggle()" class="dropdown-button">Shop By Category</button>
<ul class="dropdown-content" id="dropdownContent">
Categories
<?php getcats(); ?>
</ul>
</div>
<div class="menubar-div">
<ul class="menu-items">
<?php getcats(); ?>
</ul>
</div>
<div class="cart">
Cart (0)
</div>
</div>
<div class="content">
<div class="nav">
</div>
<div class="list_wrapper">
<!--/////////////////////////////////////////////// Filter div /////////////////////////////////////////////////////-->
<div class="filter">
<span class="filter_heading">Select Brands</span>
<a href="" class="clear" id="clear_brands">Clear<a>
<div class="brand_div">
<?php
show_brands();
?>
</div>
<div class="price_div">
</div>
</div>
<!--/////////////////////////////////////////////// List div ///////////////////////////////////////////////////////-->
<div class="list">
<div class="loading">
<img src="images/loadingAnimation.gif">
</div>
<?php
show_filtered();
?>
</div>
</div>
<div class="footer">
FOOTER
</div>
</div>
</div>
<?php
?>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
</script>
</body>
</html>
I am using alert() in the beforeSend in the ajax request and it returns the correct data as expected. But the PHP section of the page does not received the values. There are no errors on the PHP side or the browser debug window.
I checked your code line by line. and figure out that you have code for ajax inside the function named "filter" function filter().
Now you are calling this filter function on by onclick event of the element with id clear_brands
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
and by this code i came to know that at the end your ajax call is not being made because you click event was not triggered,
So either you should trigger this event on your document get ready or you have to do it by clicking on that element.
Just think about the flow once.
i was testing your script in my local and
with some modification i have made it working.
did some changes like
at the end of the script i just putted this code below.
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
And ajax call was executed..
check out my entire HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<a href="" class="clear" id="clear_brands">Clear<a>
<script type="text/javascript">
$(window).on('load', function(){
function filter(){
//alert("filter called");
$('.filter .list').css('opacity', 0.5);
$('.loading').css('visibility', 'visible');
var brandchoice = new Array();
$('input[name="brandchoice"]:checked').each(function(){
brandchoice.push($(this).val());
$('#clear_brands').css('visibility', 'visible');
});
if(brandchoice==""){
$('#clear_brands').css('visibility', 'hidden');
}
var brand_list = '&brand_list='+brandchoice;
var data = brand_list.substring(1, brand_list.length);
//alert(data);
$.ajax({
url: "list.php",
type: "GET",
data: data,
cache: false,
success: function(result){
$(".filter .list").css("opacity", 1);
$(".loading").css("visibility", "hidden");
},
error: function(jqxhr, exception){
console.log(jqxhr);
},
beforeSend: function(){
console.log("before send: "+data); //This is showing "brand_list=1" which is correct.
}
});
}
$('input[type="checkbox"]').on('change', filter);
$('#clear_brands').on('click', function(){
$('.brand_check').removeAttr('checked');
filter();
$('#clear_brands').css('visibility', 'hidden');
});
}); //end of jquery
$(document).ready(function(){
$('#clear_brands').trigger("click");
});
</script>
</body>
</html>
In Chrome do Ctrl+Shift+I to open Developer Tools and check Console for errors and Network tab to see if the data is passed in request.

basic usage of AJAX with php for Database update and retrieval

(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

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