I'm trying to make a call to the database and recieve a "toplist" that is limited to 10 in PHP. Here I need to make an array and give it back to the Jquery with $.get().
But it's failing in recieving all the data with this code, How can I make this to be recieved and then do a "for each" in the Jquery for all the data that is being sent back from the PHP?
Jquery:
$.get("core.inc.php?get_toplist=1",
function(data) {
var json = JSON.parse(data);
alert(json['name']);
});
PHP:
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
echo json_encode($arr);
}
You're returning an array, but your Javascript code is treating it as a single element. Try:
alert(json[0].name);
If you want a foreach, you can do:
$.each(json, function(i, el) {
console.log(el.name + " score is " + el.points);
});
Friend your json will be like .
[{"position":1,"name":"name1","points":"points"},{"position":2,"name":"name2","points":"points"}, {"position":3,"name":"name3","points":"points"},....]
so you can not directly access it like ur way.
make a loop then access it.
$.each(data,function(i,val){
alert(val.name);
});
this will work.
your php code is not proper
if ($_GET['get_toplist']) {
$get_top_list = mysql_query("
SELECT * FROM ".$DBprefix."Submissions
WHERE status='1'
ORDER BY points DESC LIMIT 10");
$i = 0;
$arr = array();
while ($top_list = mysql_fetch_array($get_top_list)) {
$arr[] = array(
'position' => $i++,
'name' => $top_list['name'],
'points' => $top_list['points']
);
}
}
echo json_encode($arr);
}
just add '}' before echo json_encode($arr);
also you are getting an array change in alert(json[0]['name']);
Related
How to make this function produce column occLvl_ loop 3 time and using explode to fetch each value from sql CONCAT. So the result will become like this.
[{
"accommodationID": "LA56",
"occLvl_0": "40.00",
"occLvl_1": "70.00",
"occLvl_2": "90.00"
}]
function getOccLevel(){
global $ehorsObj;
$occArray = array();
$sql = "SELECT accommodationID, GROUP_CONCAT(occLevelDesc) AS occLevels
FROM tblSamAccOccLevels
WHERE ACTIVE = 'y'
GROUP BY accommodationID
ORDER BY accommodationID ASC, occLevelDesc ASC ";
$GetResult = $ehorsObj->FetchData($sql, $ehorsObj->DEFAULT_PDO_CONNECTIONS);
while ($row = $GetResult->fetch()){
$occArray[] = array(
'accommodationID' => $row['accommodationID'],
);
//seem the method below is not working
for ($j = 0; $j < 3; $j++) {
$occArray["occLvl_".$j] = explode(",", $row['occLevels'])
}
}
header("Content-type: application/json");
$result = json_encode($occArray);
echo $result;
}
Result of the query
accommodationID occLevels
LA56 40.00, 70.00, 90.00
Making numerically named object properties/variables (occLvl_0 etc.) is generally a bad idea as it makes it difficult to work with them in any regular manner (e.g. using a loop). It is better practice to put the values into an array:
while ($row = $GetResult->fetch()){
$occArray[] = array(
'accommodationID' => $row['accommodationID'],
'occLvl' => explode(",", $row['occLevels'])
);
}
This will give you an output JSON that looks something like:
[
{
"accommodationID": "LA56",
"occLvl": [
40,
70,
90
]
},
{
"accommodationID": "PQ45",
"occLvl": [
30,
60,
100
]
},
...
]
And in your JS you can then iterate over the occLvl array to get the values.
If you need the data in the form you describe, then you need to iterate over the exploded occLevels value to generate the individual values, pushing them with the accommodationID into a new array and then pushing that array to $occArray:
while ($row = $GetResult->fetch()){
$this_occ = array(
'accommodationID' => $row['accommodationID'],
);
foreach (explode(",", $row['occLevels']) as $key => $occLvl) {
$this_occ["occLvl_$key"] = $occLvl;
}
$occArray[] = $this_occ;
}
Explode returns an array. You should explode before the loop and iterate through the result of that explode in the loop
This is my auto complete code. What should my PHP code look like in order
to receive the array that I put in the $.post() function?
var excludeArray = [];
$(".fb25").autocomplete({
source: 'vacation_get25Football.php',
focus: function(event, ui) {
$(this).val(ui.item.label);
return false;
},
select: function(event, ui) {
var exclude;
$(this).val(ui.item.label);
exclude = $(this).next().val(ui.item.value).val();
excludeArray.push(exclude);
// SENDING Exluded values to URL
$.post('vacation_get25Football.php', {'array[]': excludeArray});
// alert looks like (for example) 1,4,5
alert(excludeArray);
return false;
}
});
This is part of vacation_get25Football.php . My idea would be to insert certain values like, '1,3' into the IN() statement in sql. Doing this will subtract whatever values that are in IN() from the query. But For some reason I cannot get the array that I posted in Jquery to come up in PHP. From what I can tell, it's acting like $_POST['array']) isn't even being posted. Can any of you see what's wrong? Thank you.
if (($term = $_GET['term'])) {
if(($excludeArr = $_POST['array'])){
$test = 2;
}else{
/////////THIS IS THE ANSWER NO MATTER WHAT.
$test =1;
}
$objDB = mysqlDB();
$select_query = "SELECT team, ftball_id FROM tbl_football_top25
WHERE team
LIKE '%$term%'
AND NOT
ftball_id IN( $test )
;";
$prop_info = $objDB->getRecords($select_query);
$data = array();
if ($prop_info != "No records") {
FOREACH ($prop_info as $thisprop) {
array_push($data, array('label' => $thisprop['team'], 'value' => $thisprop['ftball_id']));
}
echo(json_encode($data));
}
//close db
$objDB->close();
}
I have a table called 'items' which has 10 rows. This 'items' table contain 2 columns(id, item_name). item_name is where I store the images' names such as item_fdsj43.jpg, item_bdf34.jpg, and so on...
If I want to displayed all these images, I do something like this:
fetching.php:
$query = "SELECT item_name FROM items";
$mysql_query = mysql_query($query);
while($mysql_fetch_assoc = mysql_fetch_assoc($mysql_query)){
$mysql_fetch_assoc_item_name = $mysql_fetch_assoc['item_name'];
echo 'img/'.$mysql_fetch_assoc_item_name;
}
JAVASCRIPT
$('fetching.php', function(data)){
$('#inner_container').append(data);
});
This will display all the data simultaneously and append it on '#inner_container' once the fetching is done. However, this callbacks takes a while and slower compare to search engine of this website (http://www.bedbathstore.com/). Is there any way to boost its speed?
Here i can suggest to you JSON instead of output data using echo below are the sample code
you can modify it for your needs
PHP code
ob_start();
imagepng($my_img);
$imageData = ob_get_contents();
ob_clean();
$results = array(
'price' => $_GET['priceX'],
'image' => base64_encode($imageData)
);
$json = json_encode($results);
echo $json;
Javascript code:
$.getJSON("/ajax-script.php", function(data) {
$("#element").append($("<img />").attr('src', 'data:image/png;charset=utf8;base64,' + data.image));
});
You can use json to retrieve the image paths at once from the server asynchronously and then you can append these images to image container like this,
//fetching.php:
$query = "SELECT item_name FROM items";
$mysql_query = mysql_query($query);
$file_names = array();
while($mysql_fetch_assoc = mysql_fetch_assoc($mysql_query)){
$mysql_fetch_assoc_item_name = $mysql_fetch_assoc['item_name'];
array_push($file_names, 'img/'.$mysql_fetch_assoc_item_name);
}
echo json_encode($file_names);
//JAVASCRIPT
$.getJSON("fetching.php", function(data) {
$.each(data, function() {
$('#inner_container').append($("<img />").attr('src', this);
});
});
I am trying to pull the latest entry of a mysql table through ajax and display it as html content inside a div. I have ajax and php functioning correctly, the only problem I have is that I want to query for new entries and stack the results at a time interval within a loop and I've run into two problems: getting the data to behave like a normal javascript string, and getting the loop to only return unique entries.
update.php file
$con=mysqli_connect("mydbhost.com","username","password","database_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM conversations");
$j = 0;
while($row = mysqli_fetch_array($result))
{
$carray[j] = $row['comment'];
$j++;
}
$comment = (array_pop($carray));
echo $comment;
echo "<br>";
mysqli_close($con);
JQuery Ajax request loop:
$(document).ready(function(e){
var comment;
function commentLoop() {
comment = $('#testdiv').load('update.php');
$('#testdiv').append(comment);
setTimeout(commentLoop, 6000);
}
commentLoop();
$(document).focus();
});
The problem is by doing SELECT * FROM conversations you keep requesting whole table -- although you only take the last one.
Your code need to remember which comment has been loaded, and only get any comment newer than that.
For example, assuming your primary key is incremental, do SELECT * FROM conversations WHERE convid > ?. Replace ? with latest comment that has been loaded. If you're loading for the first time, just do SELECT * FROM conversations
You could pass the last comment id displayed using request parameter into update.php. Also I recomment returning the data in JSON format so you can return a collection of comment and id and parse it easily
This will count the comments in the table and select the last entered comment then pass them to ajax as json data only if the received count is lower than the count of the comments in the table:
PHP:
if(isset($_GET['data']))
{
$con = new mysqli('host', 'user', 'password', 'database');
$init_count = $_GET['data'];
$stmt1 = "SELECT COUNT(*) AS count FROM conversations";
$stmt2 = "SELECT comment FROM conversations ORDER BY date_column DESC LIMIT 1";
$total = $con->prepare($stmt1);
$total->execute();
$total->bind_result($count);
$total->fetch();
$total->close();
if( ($init_count != '') && ($init_count < $count) )
{
$lastComment = $con->prepare($stmt2);
$lastComment->execute();
$result = $lastComment->get_result();
$row = $result->fetch_assoc();
$lastComment->close();
$data = array(
'comment' => $row['comment'],
'count' => $count
);
}
elseif($init_count == '')
{
$data = array(
'comment' => '',
'count' => $count
);
}
$pdo->close();
echo json_encode($data);
}
HTML:
<input type="hidden" id="count" value="" />
JQUERY:
$(document).ready(function(e){
function getComment(){
var count = $('#test').val();
$.ajax({
type: 'get',
url: 'update.php?data=' + count,
dataType: 'json',
success: function(data)
{
$('#count').val(data.count);
if(data.comment) != $('#testdiv').html(data.comment);
}
});
}
getComment();
setInterval(getComment, 6000);
});
SELECT * FROM conversations order by insert_date desc limit 10
insert_date the date time comment is inserted, i hope you will have a field for storing that if not add it now
I am having problems with the retrieval of data from my database using a where clause with a for loop variable. this codes currently can retrieve the data from the database but however the values retrieved from the database stockpiles. at the number 1 in the for loop its still fine. but when it goes to the next one. the data gathered is the combination of 1 and 2. when it finally hit the end of the loop all of the data is displayed.
Which part of the codes must be edited to change the display of data to non-cumulative
<?php
$sectorcount = $row_SectorCount['COUNT(*)'];
//number of rows in database
$spendingname= array();
$spendingpercent= array();
$spendingid= array();
?>
// Add some data to the details pie chart
options_detail_1.series.push({ name: 'Tax Spending Detail', data: [] });
$(document).ready(function() {
chart_main = new Highcharts.Chart(options_main);
chart_detail_1 = new Highcharts.Chart(options_detail_1);
})
function push_pie_detail(sectorid) {
switch(sectorid)
{
<?php
for ($i=1; $i<=$sectorcount; $i++)
{
echo "case 'sector".$i."':" ,
"setTimeout", "(" , '"chart_detail_1.series[0].remove(false)", 1000);' ,
"chart_detail_1.addSeries(options_detail_1, false);" ,
"chart_detail_1.series[1].setData( [";
mysql_select_db($database_conn2, $conn2);
$query_Spending = "SELECT CONCAT(spending.SectorID, spending.ExpenditureID) AS 'SpendingID',
expenditure.ExpenditureName, spending.SpendingPercent, spending.SectorID
FROM spending
INNER JOIN expenditure ON spending.ExpenditureID = expenditure.ExpenditureID
WHERE spending.SectorID = '.$i.'";
$Spending = mysql_query($query_Spending, $conn2) or die(mysql_error());
$totalRows_Spending = mysql_num_rows($Spending);
while($row_Spending = mysql_fetch_assoc($Spending))
{
$spendingname[] = $row_Spending['ExpenditureName'];
$spendingpercent[] = $row_Spending['SpendingPercent'];
$spendingid[]= $row_Spending['SpendingID'];
}
mysql_free_result($Spending);
$a = 0;
foreach ( $spendingid as $sgi => $sgid)
{
if ($a > 0) echo ', '; // add the comma
echo "{
name: '$spendingname[$sgi]',
y: ". $spendingpercent[$sgi] * $tax .",
id: ' $sgid',
}";
$a++;
}
echo "], false);" ,
"chart_detail_1.redraw();",
"break;";
}
?>
default:
break;
}
}
You need to wrap your variable in 'x' single quotes in your where clause, otherwise it will think you mean id = true, which is true for all of them =) I had the same problem recently
EDIT: So instead of saying where spending.SectorID = $i, you should have 'somevalue', just make a new variable $example = "'" . $i . "'", and use that variable in the where clause
I wrote a function that takes text and wraps it in single quotes just for this situation
Move your $spendingname = array(); and other array definitions inside the loop.