I have a question about loading multiple fields from the database and use them in javascript.
This is my table "deaths" with fields:
- district
- year_1999
- year_2000
- year_2001
- year_2002
- year_2003
- year_2004
- year_2005
- year_2006
- year_2007
- year_2008
- year_2009
Now I want to load the fields year_.... when district = 'districtname'
This is what I have: (PHP)
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "testdatabase";
$tableName = "deaths";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT year_1999,year_2000,year_2001,year_2002,year_2003,year_2004,year_2005,year_2006,year_2007,year_2008,year_2009 FROM $tableName WHERE district = 'Binnenstad'"); //query
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
Javascript:
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: './api4.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
for (var i in rows)
{
var row = rows[i];
var data = row[0];
$('#districts ul').append("<li>" + data + "</li>")
.append();
}
}
});
});
But this only shows the first column data (year_1999).
How can I fix this?
Instead for (var i in rows) ... try :
UPDATE. Looking your php closer try something like this to draw each year:
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
$('#districts ul').append("<li>" + year + "</li>")
});
});
Related
I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.
at first I apologise for creating this topic. I did try to search the answer but I couldnt find the right solution.
I am reading data from mysql with ajax and everything is working with one div. The thing I can't get working is to load each variable into separate div.
I use this api.php for fetching the data from mysql.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "skuska";
$tableName = "hodnoty";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query('SELECT t.hodnota FROM hodnoty t ORDER BY t.id DESC LIMIT 1') or die('Invalid query: ' . mysql_error()); //query
while ($row = mysql_fetch_assoc($result)) {
echo $row['hodnota'];
}
?>
This is the ajax script for updating the data.
$(document).ready(function() {
$("#gettable").load("api.php");
var refreshId = setInterval(function() {
$("#gettable").load('api.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
Then in html I am using div for showing the data
<div id="gettable"></div>
I would like to use this but with more variables like data1, data2, data3
and then used div for each data so I could use more divs.
For example:
<div id="data1"></div>
<div id="data2"></div>
I understand html, a little bit of php but I am totally new in java.
Thank you for your help.
do this
take as many variables as you have div and store content in variables inside loops
/******* a short example **************/
$div1cnt="";
$div2cnt="";
while($SRC=mysqlii_fetch_object($link)){
$divid=$SRC->id;
if($divid==1){
$div1cnt.="add more stuff that you want here";
}
else if($divid==2){
$div2cnt.="add stuff to second div";
}
echo "<div id=\"div1\">{$div1cnt}</div>";
/************and so on ******************/
There is no JS requirement means it is mobile friendly and no double connection required to load second page.
Here is how you can solve the problem in Javascript ( watch out, not JAVA :) )
$(document).ready(function() {
var i = 1;
$.get("api.php", function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
var refreshId = setInterval(function() {
$.get("api.php?randval="+ Math.random(), function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
}, 9000);
$.ajaxSetup({ cache: false });
});
I have to retrieve many rows from MySQL and send by encoding with ajax and I done this. but the problem is I am not able to handle the output array data in ajax. can anyone help me please?
1>one.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "elearning";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST)){
$exam_id=$_POST['exam_id'];
$sql="select * from exam_to_question where exam_id=$exam_id";
$result = mysql_query($sql);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
?>
2> and ajax code is:
$.ajax({
type: 'POST',
url: '../functions/one.php',
data: "exam_id="+exam_id,
dataType: 'json',
success: function(data){
//alert(data[0]['question_id']);
// i have to handle data here
},
error:function(){
alert("AJAX failure");
}
});
If that is an array then you have to use .each() method of jQuery:
$.each(data, function(i, resp){
console.log(resp);
});
You will get jquery object with ajax response. So, you can process it with any of these functions:
http://api.jquery.com/each/
http://api.jquery.com/jQuery.each/
if you have used dataType: json then you can dirctly use
//if it is not a multidimensional array then you can dirctly
data.keyName
//if it is multidimensional array
$(data).each(function(index,element){
console.log(element);
})
I want to get searched data from mysql database using JSON and show in my php page. I was write this code but it not retrieve any data.please help me
Client page
$(function () {
var roll = document.getElementById("roll").value;
$.ajax({
type: "POST",
url: 'api.php',
data: "roll=" + roll,
dataType: 'json',
success: function (data) {
var id = data[0];
var vname = data[1];`$` ('#output').html("id: " + id + " name: " + vname);
}
});
});
api.php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ajax";
$tableName = "stud";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST['roll'])){
$data = $_POST['roll'];
$result = mysql_query("SELECT * FROM $tableName WHERE roll = '".$data."'");
$array = mysql_fetch_row($result);
}
echo json_encode($array);
log this value before sending,
var roll = document.getElementById("roll").value;
console.log(roll);
Use object to send the params in ajax call like this data: {'roll':roll} for best practice
use firebug to check if the value 'roll' passed properly
In your php dump the post variable print_r($_POST) and check the firebug response console whether you got what you sent.
If you got it in $_POST then probably you have some issue with sql connection/query
I am trying to get several sections of data in json in one go like
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "world";
$tableName = "city";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName limit 15"); //query
//fetch result
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
//first section
echo '<section id="stuff">';
echo json_encode($jsonData);
echo '</section>';
//section two ....
?>
I return json wrapped in html5 section tag
<section id="stuff">[["1","Kabul","AFG","Kabol","1780000"],["2","Qandahar","AFG","Qandahar","237500"],["3","Herat","AFG","Herat","186800"],["4","Mazar-e-Sharif","AFG","Balkh","127800"],["5","Amsterdam","NLD","Noord-Holland","731200"],["6","Rotterdam","NLD","Zuid-Holland","593321"],["7","Haag","NLD","Zuid-Holland","440900"],["8","Utrecht","NLD","Utrecht","234323"],["9","Eindhoven","NLD","Noord-Brabant","201843"],["10","Tilburg","NLD","Noord-Brabant","193238"],["11","Groningen","NLD","Groningen","172701"],["12","Breda","NLD","Noord-Brabant","160398"],["13","Apeldoorn","NLD","Gelderland","153491"],["14","Nijmegen","NLD","Gelderland","152463"],["15","Enschede","NLD","Overijssel","149544"]]</section>
This is my jquery
$.ajax({
url: 'getdata.php',
data: "",
dataType: 'html',
success: function(data)
{
//console.log(data);
var thedata = $(data).filter($("#stuff"));
console.log(thedata);
}
});
This does not work.How can i select only the data inside the section tag?.
To get the inner of an element use .html()
$(data).filter('#stuff').html();
To get back the json
$.ajax({
url: 'getdata.php',
data: "",
dataType: 'html',
success: function(data)
{
var thedata = $(data).filter('#stuff').html();
var jobject = JSON.parse(thedata);
for(var i = 0; i < jobject.length; i++) {
var item = jobject[i];
console.log(item[0] + ':' + item[1] + ':' + item[2] + ':' + item[3] + ':' + item[4] );
}}
});