create links in AS3 with PHP - php

I've got this code that retrieve data from my SQL Data Base into my AS3 code.
My table (data base) has this rows : "id", "title", "price", "information", "mail".
In my AS3 code I loaded "title".
Php Code :
header('Content-type: application/json');
$ts = gmdate("D, d M Y H:i:s") . " GMT";
header("Expires: $ts");
header("Last-Modified: $ts");
header("Pragma: no-cache");
header("Cache-Control: no-cache, must-revalidate");
$num = mysql_numrows($sql_result);
$phptheTitle = "";
$obj = array();
while ($row = mysql_fetch_array($sql_result)) {
$theTitle = $row["theTitle"];
$phptheTitle = $phptheTitle.' </br> '.$theTitle;
$datas = array();
$datas['theTitle'] = $row["theTitle"];
$datas['prix'] = $row["prix"];
$obj[] = $datas;
}
echo json_encode( array('products' => $obj) );
mysql_free_result($sql_result);
mysql_close($connection);
?>
AS3 code :
function categorieSelected(evt:Event):void {
var urlReq:URLRequest = new URLRequest ("http://www.mywebsite.com/find_annonces.php");
urlReq.method = URLRequestMethod.POST;
var urlVars:URLVariables = new URLVariables();
urlReq.data = urlVars;
trace("typeSelected");
urlVars.categorie = evt.target.value;
trace(urlVars.categorie);
varLoader2.load(urlReq);
var loader:URLLoader = new URLLoader (urlReq);
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.load(urlReq);
trace(urlReq);
loader.addEventListener(Event.COMPLETE, loadComplete);
}
function loadComplete(evt:Event):void {
trace("loadComplete");
var myResult:String = evt.target.data;
trace(myResult);
output_txt.htmlText = myResult;
var datas :Object = JSON.parse( myResult );
var products :Array = datas && datas.products ? datas.products : [];
var len:int = products.length;
for( var i:int = 0; i<len; ++i ){
trace( products[i].title, products[i].price );
}
}
So my output_txt is displaying all items in the row "title".
Now, is it possible to create a link for each title(in AS3) ?
In order to display "price", "information", "mail" when we click on the title(each title has their own "price", "information" and "mail", contain in my database).
Exemple :
The AS3 code displays "Computer". When I click on "ipod Touch" it displays "price", "information" and "mail" that is contains in my database.
Here's a short video of what I'd like to do : http://sendvid.com/whdm4sjf
EDIT
So with the help of Aaron, the code works a little bit better.
In my AS3, the user can choose a "categorie" in order to displays all the titles contains in the categorie.
For that I've put this $categorie = $_POST['categorie']; in PHP
And this code in AS3
var loader5:URLLoader = new URLLoader();
var varLoader2:URLLoader = new URLLoader;
varLoader2.dataFormat=URLLoaderDataFormat.VARIABLES;
varLoader2.addEventListener(Event.COMPLETE,completeHandler2);
function categorieSelected(evt:Event):void {
var urlReq:URLRequest = new URLRequest ("http://www.brousse-en-folie.com/sondage/convertXML.php");
urlReq.method = URLRequestMethod.POST;
var urlVars:URLVariables = new URLVariables();
urlReq.data = urlVars;
trace("typeSelected");
urlVars.categorie = evt.target.value;
varLoader2.load(urlReq);
loader5.load(new URLRequest("http://www.brousse-en-folie.com/sondage/convertXML.php"));
loader5.addEventListener(Event.COMPLETE, complete);
}
But it seems that with the JSON loading, there is a conflict and I've got this error with the function categorieSelected
Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
Here's a short video of the problem : http://sendvid.com/18rr26rb

Here's a rough idea of what I would do:
Return all your data as XML or JSON. For example you can use PHP json_encode to return the SQL results as JSON.
Load the JSON into AS3 using URLLoader and JSON.parse.
Now you have an Array of data you can iterate over and display list items.
Add a click handler to each display list item that will hide the list, and show a detailed view.
You can accomplish this many ways, here's one simple example:
PHP
$products = array();
while ($row = mysql_fetch_array($sql_result)) {
$products[] = array(
"title" => $row["theTitle"],
"price" => $row["thePrice"]
);
}
echo json_encode($products);
Which should output valid JSON like this:
[
{
"title": "Product 1",
"price": 100
},
{
"title": "Product 2",
"price": 200
},
{
"title": "Product 3",
"price": 300
}
]
AS3
Load the JSON and render it out:
var products:Array;
var list:Sprite = new Sprite();
addChild(list);
var details:TextField = new TextField();
addChild(details);
var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("products.php"));
loader.addEventListener(Event.COMPLETE, complete);
function complete(e:Event):void {
products = JSON.parse(loader.data) as Array;
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
showList();
}
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
listItem.text = item.title;
listItem.y = index * 20;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
}
function showList():void {
details.visible = false;
list.visible = true;
}
function showDetails(item:Object):void {
list.visible = false;
details.visible = true;
details.text = "Price: " + item.price + "\nInformation: " + item.information + "\nMail: " + item.mail;
}
This is just a rough start to give you an idea.

Related

Object in jquery using json response

I want to create an object in jquery using a json response that is return from my controller
var cellContents = {'29-08-2018': '20','18-08-2018': '60'};
This is the desired format that i want and below given is my json response
{"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]}
i tried some code to make the format that i want but it failed this is the code that i tried
var arr2 = [];
//var cellContents = JSON.parse(data.result);
for(var i=0; i<data.result.length; i++){
var arr = [];
for(var j=0; j<data.result[i].date.length; j++)
{
arr.push(parseInt(data.result[i].date[j].fcount));
}
var test = [data.result[i].followup_datee];
arr2.push(test.concat(arr));
}
var jsonString = JSON.stringify(arr2);
console.log(jsonString);
after i tried this code i got some response in the console like this
[["17-08-2018",1],["18-08-2018",1]]
This is the controller that i am using in php
public function getLeadcount()
{
$status = 1;
$arr = [];
$sess = $this->session->userdata('user_id');
$result = $this->mdl_lead_registration->getLeaddate($sess);
if(!empty($result))
{
$status = 1;
foreach($result as $res)
{
$res->{'date'} = '';
$res->date = $this->mdl_lead_registration->getLeadcount($sess,$res->followup_datee);
}
}
echo json_encode(array("status" => $status,"result" => $result));
}
I think you all understand my problem . Any sort of help is appreciable.
Use the following code:
var data = {"status":1,"result":[{"followup_datee":"17-08-2018","date":[{"fcount":"1"}]},{"followup_datee":"18-08-2018","date":[{"fcount":"1"}]}]};
var obj = {};
for (var i = 0; i < data.result.length; i++){
obj[data.result[i].followup_datee] = parseInt(data.result[i].date[0].fcount);
// Here you change the property.
// In js you can access to an object's property like an array,
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors.
// If you want to use the count as a string, use instead:
// obj[data.result[i].followup_datee] = data.result[i].date[0].fcount;
}
console.log(obj);

Ceate CSV show error for page unresponsive

I am creating CSV from fetching data from MySQL data base. there are around 18000 rows and 8 columns but it show me Page unresponsive error and show me kill page or wait:
I've used following code.
function report_print()
{
date = time();
$myFile = "report_$date.csv";
$this->load->library('parser');
$stringData = $this->input->post('data');
$fileArray = $this->getdata($stringData);
$this->generateconvert_to_csv($fileArray, $myFile, ',');
die;
}
I have also tried to create CSV with jQuery with following code but it shows me error for " Network fail".
jQuery.fn.tableToCSV = function() {
var clean_text = function(text){
text = text.replace(/"/g, '""');
return '"'+text+'"';
};
$(this).each(function(){
var table = $(this);
var caption = $(this).find('caption').text();
var title = [];
var rows = [];
$(this).find('tr').each(function(){
var data = [];
$(this).find('th').each(function(){
var text = clean_text($(this).text());
title.push(text);
});
$(this).find('td').each(function(){
var text = clean_text($(this).text());
data.push(text);
});
data = data.join(",");
rows.push(data);
});
title = title.join(",");
rows = rows.join("\n");
var csv = title + rows;
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
var download_link = document.createElement('a');
download_link.href = uri;
var ts = new Date().getTime();
if(caption==""){
download_link.download = ts+".csv";
} else {
download_link.download = caption+"-"+ts+".csv";
}
document.body.appendChild(download_link);
download_link.click();
document.body.removeChild(download_link);
});
};
Anyone's Help will be appreciated for how to create a CSV with this much record without any issue ?

Get variables fom a txtor php file

I have this code on .fla file
fm_button.visible = false;
var menu_label:Array = new Array("Introduction", "Products", "Services",
"Testimonials", "Our Company", "Contact Us");
var total:Number = menu_label.length;
var i:Number = 0;
var page:Number;
var main_menu:MovieClip = new MovieClip();
stage.addChild(main_menu);
for (i = 0; i < total; i++)
{
var btn = new flashmo_button();
btn.name = "btn" + i;
btn.x = fm_button.x;
btn.y = fm_button.y + i * ( fm_button.height + 10 );
btn.buttonMode = true;
btn.item_no = i;
btn.flashmo_click_area.addEventListener( Event.ENTER_FRAME, btn_enter );
var each_substring:Array = menu_label[i].split("|");
btn.flashmo_button_label.fm_label.text = each_substring[0];
btn.item_url = each_substring[1];
main_menu.addChild(btn);
}
function btn_over(e:MouseEvent):void
{
e.target.parent.over = true;
}
function btn_out(e:MouseEvent):void
{
e.target.parent.over = false;
}
What i want is to get this values:
("Introduction", "Products", "Services", "Testimonials", "Our
Company", "Contact Us");
from a text or php file named menu.php or menu.txt
Is this possible?
Why you need read from .php file?
Is this client-server communication?
In that case, when .fla file loads by client browser over http(s) you should do something like this:
menu.php (for example put this file to document root folder):
<?php $menu = array('Elem1', 'Elem2');
echo json_encode($menu); ?>
.fla:
var sendData:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest('/menu.php');
request.method = URLRequestMethod.GET;
var loader:URLLoader = new URLLoader(request);
loader.addEventListener(Event.COMPLETE, onCompleted);
So, your .fla are doing query to server and get's list of categories (onCompleted method receive data).
If this is not server-client communication, you should use other file format, because .php is not a data storage )

Saving Google map Points to a database

i have been playing with the Google maps trying to make a tour and save the start end and the way points in a database.
here is the java-script code that i use to pass the values
function saveRoute() {
var name = "<?php Print($log_username);?>";
var waypts = [];
var end = points.length-1;
var dest = points[end].LatLng;
if (document.getElementById("roundTrip").checked) {
end = points.length;
dest = points[0].LatLng;
}
data.start = {'lat': points[0].LatLng.lat(), 'lng': points[0].LatLng.lng()}
data.end = {'lat': dest.lat(), 'lng':dest.lng()}
for (var i=1; i<end; i++) {
waypts[i-1] = [points[i].LatLng.lat(),points[i].LatLng.lng()]
data.waypoints = waypts;
}
var str = JSON.stringify(data)
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=save&mapdata='+str)
jax.onreadystatechange = function(){ if(jax.readyState==4) {
if(jax.responseText.indexOf('bien')+1)alert('Updated');
else alert(jax.responseText)
}}
}
here is my php processing.php
<?
ob_start();
header('Cache-Control: no-store, no-cache, must-revalidate');
$data = $_REQUEST['mapdata'];
echo $data;
mysql_connect('localhost','root','');
mysql_select_db('mapdir');
if($_REQUEST['command']=='save')
{
$query = "update mapdir set value='$data'";
if(mysql_query($query))die('bien');
die(mysql_error());
}
if($_REQUEST['command']=='fetch')
{
$query = "select value from mapdir";
if(!($res = mysql_query($query)))die(mysql_error());
$rs = mysql_fetch_array($res,1);
die($rs['value']);
}
?>
i always get the ajax response as "updated" but nothing happens to the database
where i have gone wrong ?

using nested arrays by php http_build_query() and recieve them in flash AS3

i am having this hard time figuring what is needed to do,
i am using URLVariables to send/recieve values between flash and PHP
the problem is, i am unable to access nested arrays ( array inside an array ) with flash
heres an example:
$dgresult = array("total" => $results);
echo http_build_query($dgresult,"flf_");
in flash, all i need to do is to use:
var variables:URLVariables = new URLVariables(e.target.data);
then i can access it with :
variables.total
the problem now is when i have nested arrays:
$dgresult = array("total" => $results);
array_push($dgresult,$another_array);
http_build_query($dgresult,"flf_");
i can still access variables.total
but what about anything that has flf_ ?
how is that possible?
you should try to simply use established formats for complex data, such as JSON. For PHP see here and for AS3 see here. Or ready made solutions such as AMFPHP.
greetz
back2dos
or you can just parse the object
var url:String = 'http://localhost/dump.php';
var params:Object = {
test: 'ok',
nested_1: {
nested_2: {
nested_3: {
nested_4: {
hello: 'mf',
str: '~!##$%^&*()_+'
}
}
}
},
};
var request:URLRequest = new URLRequest(url);
var variables:URLVariables = new URLVariables();
parameters = fixParameters(parameters || {});
for (var key:String in parameters) {
variables[key] = parameters[key];
}
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.load(request);
and here is fixParameters method
private function fixParameters(data:Object, parameters:Object = null, prefixes:Array = null):Object {
var setPrefix:Array;
var prefixKey:String;
if (!parameters) {
parameters = {};
}
if (!prefixes) {
prefixes = [];
}
for (var key:String in data) {
setPrefix = prefixes.concat([key]);
if (typeof(data[key]) == 'object') {
parameters = fixParameters(data[key], parameters, setPrefix);
} else {
prefixKey = '';
for (var i:Number = 0; i < setPrefix.length; i++) {
prefixKey += i == 0 ? setPrefix[i] : '[' + setPrefix[i] + ']';
}
parameters[prefixKey] = data[key];
}
}
return parameters;
}

Categories