Titanium Appcelerator - How to Pull Remote Data - php

I'm using the following code to pull data and nothing happens. Here's my PHP CODE.
$getall = "SELECT * FROM pages WHERE account_id=$id ORDER BY course_id";
$showall = #mysqli_query ($dbc, $getall); // Run the query.
$json = array();
if (mysqli_num_rows($showall) > 0)
{
while ($row=$showall->fetch_assoc()) {
$json[]=array(
'logged' => true,
'pagename'=>$row['pagename'],
);
} // end while
header("Content-Type: text/json");
echo json_encode(array( 'pages' => $json ));
}
And here's my JS CODE that runs the app.
sendit.open('GET', 'http://myurl.com/mypages.php');
sendit.send();
sendit.onload = function(){
var json = JSON.parse(this.responseText);
var json = json.pages;
var dataArray = [];
var pos;
for( pos=0; pos < json.length; pos++){
dataArray.push({title:'' + json[pos].pagename + ''});
// set the array to the tableView
tableview.setData(dataArray);
};
};
var tableview = Ti.UI.createTableView({
});
currentWin.add(tableview);
When I run the app, all I get is a blank table. Any help would be greatly appreciated.

Have you tried to move sendit.send(); below sendit.open?
Put a log in your onload event to make sure it is being fired at all.
It states in the docs that the onload must be defined before you call open in order for that even to be registered.

You're embedding your array in another array, so on the javascript side it'd be:
dataArray.push({title:'' + json.pages[pos].pagename + ''});
^^^^^ - missing level

You should have sendit.onload before send it.send.
I would also recommend you to implement sendit.onerror method, as well as intermediate Ti.API.debug(stuff);
You also double the declaration of json, with is working, but not great.

Related

JavaScript PHP HighChart transform a PHP array to a javascript array

I saw other posts but it doesn't work. I am a bit confused here on how I implement an array into JS from PHP...
In the PHP file (test.php) I have :
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
And in JavaScript I have :
<?php include 'test.php'; ?>
...
data: (function() {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i++) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
So what I look for is to put $value=$row['value']; in the y : and $date=$row['date']; in the x : OR perhaps putting the entire table $table in the var data will work also .
I'm new to JavaScript, so thanks in advance..!
So in your php file....
Add a line at the bottom that converts the table to json data.
And give it a variable...
$table = array();
while($row = mysqli_fetch_assoc($result) )
{
$value=$row['value'];
$date=$row['date'];
$table[$value]=$date;
}
$jsondata = json_encode($table);
Then in your other file....
echo that variable into your data object, in the javascript.
Remember to remove that whole random number generating function...(its just an example)
Echoing PHP into javascript is definitely not considered good practice though.
And it would be better to actually do an ajax call to your php file, and insert like that....I'll also show you how to do ajax.
<?php include 'test.php'; ?>
...
data: [<?php echo $jsondata;?>], //remove that function that was here..
// it was just to generate random numbers for the demo
....
}
EDIT / UPDATE For ajax...
So for ajax...instead of assigning a variable to $jsondata.
Just return it like so...(in your PHP file)
return json_encode($table);
Then for this way....you dont include('test.php') like you did before.
Instead you just have this script inside your $(document).ready(function(){....
$.getJSON('test.php', function(myJSON) {
//and inside this function you put your highcharts stuff...
//remove that function() that generates random data
// And you will put the 'myJSON' return object inside the 'data':[] array...
// Provided you have structured your data correctly for highcharts, it should work...
// If not.... it'll be a start, and you're well on your way to debugging it
}

What's wrong with this database call?

-Issue Still Unresolved-
I'm trying to call a database, put all the rows of a table in an array, pass that table to my JS as json data, and then use that data as parameters for a function.
When I run the script nothing happens. I don't get any errors in the console, the rest of the script loads normally. I'm pretty new to mySQL and PHP, what am I doing wrong here? I suspect that I goofed up the php somehow.
XAMPP server, being tested on my desktop
all linked files are in the same directory
There are no visible errors displayed anywhere. As far as I can tell, the script doesn't even try to load the PHP to begin with, but also doesn't display an error in firebug's console
Attempted:
Renaming the table without spaces
placing the for loop inside the callback function
amending php errors
Here's the updated JS I'm using:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {"table" : "firstlist"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
and here's the updated PHP:
error_reporting(E_ALL); ini_set('display_errors','On');
$con = mysql_connect("localhost", "root", "m3648y73");
if (!$con){die('Could not connect: ' . mysql_error());};
mysql_select_db("tasklistdb", $con);
$table = $_GET['table'];
$sql = mysql_query("SELECT taskName, taskId, taskDescription, taskComplete FROM `".$table."`");
$listTasks = array();
while ($row_user = mysql_fetch_assoc($sql))
$listTasks[] = $row_user;
echo json_encode($listTasks);
mysql_close($con);
Am I linking to the DB correctly?
getJSON is asynchronous call. So before it could fetch values from PHP and execute the callback function, it moves to the for loop and here table is empty.
Solution: shift your for loop inside the callback function
You are missing a semi colon on the line $listTasks = array() in the php file
This happens because js-code after async request executed earlier than request itself is over. Try this:
this.taskMenu = function()
{
var table = [];
$.getJSON("taskMaster.php", {table : "first list"},
function(data)
{
table.push(data);
for(i=0; i<table.length; i++)
{
var taskId = table[i].taskName.replace(/\s+/g,"") + i;
formatTask("interface",taskId,table[i].taskName,table[i].taskDescription,table[i].taskComplete);
}
});
}
Your table name can't be 'first list'
You can't have a space in a MySQL table name.
Also you should put put table in the JSON value in double-quotes like {"table":"table_name"}

Using php, ajax and jqplot to make a pie chart

I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.

json object usage with ajax returned array

I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}

Passing array with ajax - can't print

I hope this problem is very simple, I can't figure out the solution myself it seems. Been trying and googling for hours, driving me nuts :) Ok, so I have a drag'n'drop + sortable (using scriptaculous and prototype for your information) on my index.php. I use this code to send the items dropped in a div using this code:
<script type="text/javascript">
//<![CDATA[
document.observe('dom:loaded', function() {
var changeEffect;
Sortable.create("selectedSetupTop", {containment: ['listStr', 'selectedSetupTop'], tag:'img', overlap:'vertical', constraint:false, dropOnEmpty: true,
onChange: function(item) {
var list = Sortable.options(item).element;
$('changeNotification').update(Sortable.serialize(list).escapeHTML());
if(changeEffect) changeEffect.cancel();
changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" });
},
onUpdate: function(list) {
new Ajax.Request("script.php", {
method: "post",
parameters: { data: Sortable.serialize(list), container: list.id }
onLoading: function(){$('activityIndicator').show(), $('activityIndicator2').hide()},
onLoaded: function(){$('activityIndicator').hide(), $('activityIndicator2').show()},
});
}
});
});
// ]]>
</script>
I've been using this code before so I "kind of know" it will send me data to my script.php page. selectedSetupTop is my div containing the elements. Don't mind about the notification and the activityIndicator thingy. My script.php page looks like this for the moment:
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$test .= $selectedSetupTop[$i];
}
echo "<script>alert('$test');</script>";
I can't seem to get any output in the alert message, it's just blank. The purpose of the script.php is to update a row in a database and it will look kind of like this:
$sql = mysql_query("UPDATE table SET row = '$arrayInStringFormat' WHERE id = '1'") or die(mysql_error());
where the $arrayInStringFormat is a conversion of the array $selectedSetupTop to the format (1, 2, 3, 4). I guess I'll solve that using implode or something, but the problem is parsing the array $selectedSetupTop. I'm not it passes between the pages at all, really appreciate help! Tell me if I need to explain further.
Thanks in advance!
''''''
EDIT 1
If it will help, I used this code before that I know will send me the data and use it. Notice I don't wanna do my task like the way I do below:
$querySetup = $_GET["s"];
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$sql = mysql_query("UPDATE " . $querySetup . " SET orderId = $i, hero_selected = 'n' WHERE imageId = $selectedSetupTop[$i]") or die(mysql_error());
}
''''''
EDIT 2
So it does parse, but I still have the problem I can't print it. I wanna implode the array somehow.
Not sure how AJAX works in Scriptalicious/Prototype, but you don't seem to be getting the data from the AJAX call. In jQuery it would be something like this where the data you receive from the script is returned as the argument of the function.
onLoaded: function(msg){
$('activityIndicator').hide(),
$('activityIndicator2').show(),
alert(msg)
}
Secondly, you can't echo a PHP array, you have to encode it to JSON:
echo json_encode($test);

Categories