Create a list in PHP from a DB call - php

I need to create this list (in javascript):
var videoList = ['GACS1.mp4','GACS4.mp4'];
From a call to the DB. So within the DB I have a field that I am calling to to get those mp4's back.
Here is the function.php, it is really just an Ajax page that processes the request.
function assignedvideos()
{
global $db_name, $path;
$uid = $_GET['uid'];
$selectedvideos = ORM::for_table('movies1')->raw_query('SELECT B.ID AS bid, B.*, LX.* FROM movies1 LX JOIN movies B ON LX.movieid = B.id JOIN locations L ON LX.locationid = L.id JOIN tablets T ON LX.locationid = T.tabletlocation WHERE T.uniqueid =".uid." ORDER BY LX.order ASC')->find_many();
if($selectedvideos)
{
foreach ($selectedvideos as $row)
{
$row['movielocation'] = stripslashes($row['movielocation']);
$row['moviename'] = stripslashes($row['moviename']);
}
}
die();
}
And ofcourse here is the call to the ajax page to retrieve the function.php page to retrieve the values.
$something = $_GET['uid'];
jQuery.ajax({
url: 'function.php',
type: "POST",
data: 'action=assignedvideos&uid='+$something,
success: function (response) {
},
error: function (response) {
}
});
The question is does this get built in the AJAX and sent back as a string and if so how?
Or does the AJAX return the list of variables and I build the list within the success response of the AJAX call? If so, then how?

To make it easy on yourself, put whatever values you want to send back to the client into a variable, and then call
echo json_encode($somevar);
in your case, there is an additional problem,
foreach ($selectedvideos as $row)
{
$row['movielocation'] = stripslashes($row['movielocation']);
$row['moviename'] = stripslashes($row['moviename']);
}
$row is replaced on each iteration of the loop with new data from the next row in $slectedvideos, so your operation basically does nothing, after the foreach $row will contain the last row of data from $selectedvideos. (also, $row will not modify $selectedvideos). if you wanted to modify $selectedvideos, there's a number of ways to do that, but without changing your code too much, you could do
foreach ($selectedvideos as $key => $row)
{
$selectedvideos[$key]['movielocation'] = stripslashes($row['movielocation']);
$selectedvideos[$key]['moviename'] = stripslashes($row['moviename']);
}
and then
echo json_encode($selectedvideos);
which you can then convert to a javascript object in the success call using JSON.parse()
Note that in this case, the javascript object won't look exactly how you want your data to look, instead it will be an array of objects such that array[0].movielocation will be (if I'm not mistaken) the file location of the first movie etc.
If you want it to be exactly an array of file paths, the foreach loop could look like this:
$output = array();
foreach ($selectedvideos as $row)
{
$output[] = stripslashes($row['movielocation']);
}
echo json_encode($output);
Note also that using stripslashes on the file location will force you to either put all the videos in the same folder on the server or use mod_rewrite in some shape or form.

Related

Function reports back to a page after a foreach loop (in PHP)

I am writing a foreach loop which will parse directories/subdirectories/files and search and replace values in the files based on a huge array.
This will take some time....probably around 10 minutes...And i was wondering if there is a way with PHP, AJAX maybe, that when i go to the page that it will show me this (for example):
There are X number of values left.
and that number will decrease on every loop the foreach finishes.
So basically i have:
foreach ($array as $key => $value) {
$contents = file_get_contents($file);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
{do stuff here}
}
$param--; // to report back to the page
}
Depends how you want to do it really. You could store it in the database, and simply have the section of the page show you the number you are after. You'd have to add the query to change the number in the foreach as well. So say you do it like this:
<?php
$now = date("Y-m-d");
$getnum = $db->query("SELECT Num FROM mytable WHERE Jobtime = '$now'");
$result = $getnum->fetch();
$whatyouwant = $result['Num'];
if($whatyouwant > 0) { ?>
<p class="whatyouwant" id="whatyouwant"> <?php echo $whatyouwant;?> </p>
<?php } ?>
And change your foreach to do something like:
foreach ($array as $key => $value) {
$contents = file_get_contents($file);
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
{do stuff here}
}
$updatestuff = $db->query("UPDATE mytable SET Num = '$param' WHERE Jobtime = '$now'");
}
The downside to this is you have to reload the page to get the info. To bypass this, you can have the first part of my answer ran in AJAX. So you would do:
var reloadFunction = function () {
$.get("getnum.php", function (result) {
$('#holdingwhatyouwant').html(result);
});
};
$(document).ready(function () {
reloadFunction();
setInterval(reloadFunction, 10000);
});
If you do this, you need to mark the place for it on your page, such as:
<div id="holdingwhatyouwant"></div>
Why? Due to limitations. If you use the first method, and put that code on the page, you need to reload the page to see the update. If you use ajax only (similar to what I wrote here), you need to keep the page open for it to work, as well as have a handler (ajax needs to send data to php to be able to know the progress etc, so ajax has to trigger you function). Using them combined, it's all good. If you reload the page you get information instantly, if you don't, you'll get it every 10 seconds. Mind the 10000 interval expressed in milliseconds. Mind that you don't need the if part of the php, as it will return and empty paragraph.

retrieve json formatted data using xmlhttp request

I was using jQuery and this was done easily but I want to change it to regular javascript because I will be using it with phonegap and I don't want to loop through js frameworks every time I make a request to the server. Maybe it's a bad reason to go away from jQuery but seems like it would make everything faster. So I need some help with this code:
<body onload="init();">
<div id="daily"></div>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
var a = JSON.parse(xmlhttp.responseText);
document.getElementById('daily').innerHTML = a.items;
}
};
xmlhttp.open("GET", serviceURL +"getmainnews.php" , true);
xmlhttp.send();
}
</script>
getmainnews.php
//mysqli query
$daily = array();
while ($r = mysql_fetch_assoc($day)){
$daily[] = $r;
}
echo json_encode(array("items" => $daily, "allitems" => $mainnews,...));
In the Chrome DT, I can see the encoded data which is returned but I can't display the first item into my first div with id="daily". With the code I provided, all I get is [object, Object]. What am I doing wrong?
EDIT:
So my query selects the entire row from my database and it's in an array:
{"items":[{"id":"1","pic":"","topic":"daily","article":" \t\t\t\t\t \t\t\t\t\t\u0417...","link":"http://www....","text_cont":..."}]}
How can I display just the pic and the article without all the other junk? Do I have to modify my php file?
EDIT 2:
$day = mysql_query("SELECT pic, article, link FROM table WHERE topic='daily' ORDER BY id DESC LIMIT 1");
$daily = array();
while ($r = mysql_fetch_assoc($day)){
$daily[] = $r;
}
$exc = mysql_query("SELECT pic, article, link FROM table WHERE topic='exclusive' ORDER BY id DESC LIMIT 1");
$excl = array();
while ($e = mysql_fetch_assoc($exc)){
$excl[] = $e;
}
$mus = mysql_query("SELECT pic, article, link FROM table WHERE topic='must' ORDER BY id DESC LIMIT 1");
$must = array();
while ($m = mysql_fetch_assoc($mus)){
$must[] = $m;
}
echo json_encode(array("items" => $daily, "exc" => $excl, "must" => $must));
That's my full php file with the queries. Items, exc, and must are arrays, so the responseText, I guess, is a multidimensional array? Is that the problem I'm having with displaying it?
EDIT 3:
console.log(a.items) gives me an "undefined" so I logged the xmlhttp.responseText.
Without seeing exactly what your JSON looks like it is hard to know for sure. However since you are encoding an array, I suspect changing:
a.items
to
a[0].items
will do the trick...
Edit
I would do:
document.getElementById('daily').innerHTML = JSON.stringify(a.items);
That will convert your object into a string that can be assigned to the innerHTML of an element. I am not sure if this is exactly what you want to do, but when you find the element you want to display using that method should work.
Edit 2
You could change your PHP to only output what you want. However, you could filter it in your JS as well:
a.items[0].pic
and
a.items[0].article
If those don't display as is you can use the stringify method, but you shouldn't need to since those items appear to be strings.
Also note, if you have multiple items you will need to change the 0 to the index of the item you are targeting.

PHP not able to pass JSON array to jQuery

Pardon me if I am making a silly mistake here... But I am little new to PHP...
I have been stuck at this for long time.
I have tried several methods but I am only able to pass ONe table row , not multiple rows
I've even tried with the following approach, but I landed with the same error.
http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Here's what I am trying to do :
1) Make Ajax call using JQuery, to fetch data from server.
$.ajax({
url: 'test.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
//use "data"
}
2) fetch table data from MySql database, using PHP.
$result = mysql_query("SELECT username,characterType FROM usertable");
3) pass ALL of the rows as JSON data, back to the calling function.
//This works , Returns one row and I am able to get the result back at AJAX end
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_fetch_assoc($result) FAILS with the following error :
XML Parsing Error: no element found Location: moz-nullprincipal:{6b1***-****somecrap numbers****-***86} Line Number 17, Column 3:
$array = mysql_fetch_assoc($result);
echo json_encode($array);
I have even tried using mysql_fetch_array($result, MYSQL_NUM) as suggested in the other relevant questions, but I am not able to workaround the problem.
Any Help is greatly appreciated.
============
UPDATE:
I may be wrong but just wanted to know, if this could be the possibility or not... Can this be a local setup related issue ? A Configuration mistake .. ?
I have done my localhost setup using "XAMPP installation" [ Apache / MySQL / Tomcat ... bundled in one package ] ...
When I run the file as "PHP application" it runs just fine ... I am able get "all rows" But when I deploy the code on my apache servers it doesn't run ... The whole php file comes as a response , with "XML parsing Error" [ I am using firebug to track the response ]
Thanks
Pranav
A few things to note here:
As Rup mentioned, $array = mysql_fetch_row($result); only returns a single row.
The other thing is that test.php does not currently return a JSON object; to see whats going on, it helps to comment out dataType: 'json', and use console.log(data); to see what is being returned. Your response probably looks something like this:
["someUsername","someChartype"]
The format of the object you are expecting is probably something more like:
[{"username":"foo","chartype":"admin"},
{"username":"bar","chartype":"user"},
{"username":"fum","chartype":"guest"}]
To get the format of the associative array, use mysql_fetch_assoc($result) instead; that will give
{"username":"someUsername","chracterType":"someChartype"}
To summarize, update your php code to:
Loop through your results, pushing them onto an array.
Encode the entire array at the end
$outputArray = array();
while( $row = mysql_fetch_assoc( $result ) ){
array_push($outputArray, $row);
}
echo json_encode($outputArray);
Take a look at How to build a JSON array from mysql database for more info. Also, as one of the answers mention, its worth using PDO rather than mysql_*
Don't start manually composing a JSON string as #Tuanderful indicated. Let json_encode() handle that -- just give it the right data. Try something like this:
$records = array();
while ( $record = mysql_fetch_assoc( $result ) ) {
$records[] = $record;
}
echo json_encode( $records );
Well I would to like this:
$.ajax({
url: 'test.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: somevar
})
var somevar = function(data) //on recieve of reply
{
//use "data"
somevar2 = jQuery.parseJSON(data)
//now You can enter each row/cell from db(/php) like this
// somevar2[0] would be the first row from php
//if You want to do something with every line You can use:
//$.each(somevar2, function(key,value){
//$('#divname').html(value.cellnameoftable)
}
I hope it will help ;)

mysql php select random with javascript rotator

I just started learning PHP, and have been trying to build a website to learn. I found a javascript script that rotates text on the internet here which looks like:
<script language="JavaScript">
function rotateEvery(sec)
{
var Quotation=new Array()
// QUOTATIONS
Quotation[0] = 'First quotation';
Quotation[1] = 'Second quotation';
Quotation[2] = 'Third quotation';
Quotation[3] = 'Fourth quotation';
Quotation[4] = 'Fifth quotation';
Quotation[5] = 'Sixth quotation';
Quotation[6] = 'You can add <b>as many</b> quotations <b>as you like</b>';
var which = Math.round(Math.random()*(Quotation.length - 1));
document.getElementById('textrotator').innerHTML = Quotation[which];
setTimeout('rotateEvery('+sec+')', sec*1000);
}
</script>
I also have a database table called events that has three fields ( id, when, tag) When is a date, tag is the description of the event (e.g Christmas Party/Halloween at my house).
What i am trying to do is select the events that are happening today and put them in my javascript rotator, randomly.
Is this possible? How would I go about implementing this? I know I am really bad at explaining my questions so if I left out any more details if you could just tell me and I can help.Thanks!
So if I understand your intent, you want to pull events from your database and pass them into the JavaScript on your page to use in your rotator:
In your PHP
Use whichever MySQL API you are using already to execute the query. Using the old mysql_*() functions would look like the following. (Note: use of the mysql_*() functions is actually NOT recommended, but it seems most likely that's what you're currently using. I'll update if I find out otherwise...)
// Assuming `when` is a real DATE or DATETIME data type in MySQL...
// compare to CURDATE() to get today's
$result = mysql_query("SELECT tag FROM events WHERE DATE(when)=CURDATE()");
if ($result) {
// array to hold all the output
$events = array();
while ($row = mysql_fetch_assoc($result)) {
// Add the event to your array
$events[] = $row['tag'];
}
// After building the array, encode it as JSON
// Later you'll echo this into your JavaScript in place of the array...
$events = json_encode($events);
}
Later in your HTML/JavaScript output
Output the JSON string (your array) into the JavaScript on your page:
function rotateEvery(sec)
{
// The JSON from PHP output here
// Would look something like
// ["Event 1","Event 2","Event 3"]
var Quotations = <?php echo $events; ?>;
var which = Math.round(Math.random()*(Quotation.length - 1));
document.getElementById('textrotator').innerHTML = Quotation[which];
setTimeout('rotateEvery('+sec+')', sec*1000);
}

AJAX enabled web form

I am new to Jquery and want some help from you guys.
i want to decode json data in jquery as i am able to pass data from php to ajax but after it came back in jquery it is not parsing it says undefined. the code is bellow
JavaSript file
$.post("GetData.php", function(data) {
if(data==false)
var tpl = '<p>no record found<p>'
else
var tpl = DrawTableRowsforSection(data);
$("#result").append($(tpl));
},"json");
function DrawTableRowsforSection(p)
{
alert(p.id[0]);
var o = '<table>';
for (var i = 0; i < p.length; i++)
alert(p.id[i]);
o += '<tr><td>'+p.id[i]+'</td><td>'+p.section_name[i]+'<td></tr>';
o+='</table>'
return O;
}
PHP Script
header('Content-Type: application/json');
mysql_connect('localhost','root','') ;
mysql_select_db('news');
session_start();
$query = 'select id,section_name from section';
if ($result = mysql_query($query)) {
if (!mysql_num_rows($result)==null) {
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$id = ToSring($row['id']);
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
The database has a table named section
fields are as follows
id int(11)
section_name varchar(20)
There are total 5 records there.
What I want is to populate a table using returned data.
Can any one guide me where I am making mistake
Regards
Kashif Afzaal
Be sure that mysql returns results and you can take them through ajax.
Also, I've seen the following mistake:
You are using the variable tpl wrong. It is just a js variable, no need to use $ .
Use this way:
$("#result").append(tpl);
OK, from the top in the PHP script:
The MySQL extension is ancient and decrepit. Use MySQLi or PDO.
You never handle a failed MySQL query, so the response will quite possibly be empty. In 99% of cases, any if block should have a corresponding else block.
The result of mysql_num_rows() is never null. Do if (mysql_num_rows($result) > 0), or better yet, just if (mysql_num_rows($result)).
Never do if (!something == something) - it rarely does what you want it to. Do if (something != something)
You never handle mysql_num_rows() failing/giving no rows, so (again) the response will quite possibly be empty.
You never do anything with the $id variable you create.
I'm pretty sure ToSring should read ToString. But there's actually no such function in PHP - you would have either define it or invoke it as a method of a class/object. Indeed, this is likely to be the problem, as it will result in a fatal error.

Categories