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 ?
Related
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 ?
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.
I am trying to import all the data from csv to the database.
Below code is ajax request that is sent to a php file.
$('#upload_location_csv').click(function(e){
e.preventDefault();
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]});
fi = document.getElementById("csv_file_input").files[0];
reader = new FileReader;
reader.onload = function(){
csv_data = reader.result;
$.ajax({
type:"post",
url:ajax_root_path+'fend.php',
data:{
location_id:queryDict['id'],
csv_data:csv_data,
perform_action:"save_delivery_csv_data"
},
success:function(resObj){
window.location.reload();
},
error:function(resObj){
}
});
};
reader.readAsText(fi);
});
This is the action that is performed, where here is, save_delivery_csv_data .
When I click on import csv, the page reloads and no request is sent to fend.php.
case 'save_delivery_csv_data':
{
$location_id = $param_array['location_id'];
$csv_data = $param_array['csv_data'];
$csv_data_rows = explode("\n",$csv_data);
unset($csv_data_rows[0]);
$csv_data_rows = array_values($csv_data_rows);
debug($csv_data_rows);
$csv_data_array = array();
foreach ($csv_data_rows as $csv_row_key => $csv_row_value)
{
$csv_row_value_array = explode(",",$csv_row_value);
debug($csv_row_value_array);
if(count($csv_row_value_array) == 5)
{
/*$csv_data_array[$csv_row_key] = array();
$csv_data_array[$csv_row_key]['locality_id'] = $csv_row_value_array[0];
$csv_data_array[$csv_row_key]['locality_name'] = $csv_row_value_array[1];
$csv_data_array[$csv_row_key]['minimum_order_amount'] = $csv_row_value_array[2];
$csv_data_array[$csv_row_key]['delivery_time'] = $csv_row_value_array[3];
$csv_data_array[$csv_row_key]['delivery_charge'] = $csv_row_value_array[4];*/
//debug($csv_row_value_array);
if(isset_empty($csv_row_value_array[3]))
{
//debug($csv_row_value_array);
$locality_id = $csv_row_value_array[0];
$location_outletValues = array();
$location_outletValues['cloud_site_id'] = $cloud_site_id;
$location_outletValues['location_id'] = $location_id;
$location_outletValues['locality_id'] = $locality_id;
$location_outletValues['minimum_order'] = $csv_row_value_array[2];
$location_outletValues['delivery_time'] = $csv_row_value_array[3];
$location_outletValues['delivery_charge'] = $csv_row_value_array[4];
$sql = "SELECT outlet_locality_id FROM ".PLATFORM_OUTLET_LOCALITIES."
WHERE location_id='".$location_id."' AND locality_id='".$locality_id."'";
$outlet_locality_array = $DB->query($sql);
//debug($outlet_locality_array);
if(count($outlet_locality_array) > 0)
{
$condition_array = array();
$condition_array['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
//debug($condition_array);
debug($location_outletValues);
$DB->update(PLATFORM_OUTLET_LOCALITIES,$location_outletValues,$condition_array);
}
else
{
$DB->insert(PLATFORM_OUTLET_LOCALITIES,$location_outletValues);
}
}
}
}
break;
//debug($csv_data_array);
}
What am I missing out here?? I also tried debugging variables values, but no request was sent to fend.php, whereas other request on the same page are being successfully sent.
Consider the following PHP Block. I want to output "name" to div #1 and "slog" to div #2
<?php
require_once 'db_conx.php';
$Result = mysql_query("SELECT * FROM profiles ORDER BY lastupdated desc limit 1") or die (mysql_error());
while($row = mysql_fetch_array($Result)){
$result = array();
$result['name'] = $row['name'];
$result['slog'] = $row['slog'];
echo json_encode($result);
}
mysql_close($con);
?>
Here's the ajax that just outputs json itself.
var get_fb = (function() {
var counter = 0;
var $buzfeed = $('#BuzFeed');
return function(){
$.ajax({
type: "POST",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
};
})();
get_fb();
You can update the html/content of a DOM element with the following:
document.getElementById(name).innerHTML = "text";
So in this instance:
document.getElementById('#1').innerHTML = $yourNameContent;
document.getElementById('#2').innerHTML = $yourSlogContent;
First: move var counter = 0; outside from get_fb() function;
Second: Do not call get_fb(); explicitly, because (function(){...})(); already calls method after initialization.
Third: Why use POST method if there is not data to submit!
So, do this and have a try:
var counter = 0;
var $buzfeed = $('#BuzFeed');
var get_fb = (function() {
$.ajax({
type: "GET",
url: "../php/TopBusinesses_Algoriththm.php"
}).done(function(feedback) {
counter += 1;
var $buzfeedresults = $("<div id='BuzFeedResult" + counter + "'></div>").addClass('flat-menu-button');
$buzfeedresults.text(feedback);
$buzfeed.append($buzfeedresults);
var $buzfeedDivs = $buzfeed.children('div');
if ($buzfeedDivs.length > 10) { $buzfeedDivs.last().remove(); }
setTimeout(get_fb, 1000);
})
})();
I am trying to create a video that loads the videos stred in a directory, depenant on the users id etc.
To do this, I am using php. However, I cannot then get the php to convert to xml within the actionscript:
Here is php code:
$query = "SELECT * FROM video_files ORDER BY video_id DESC";
$resultID = mysql_query($query) or die("Data not found.");
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
$xml_output .= "<PLAYLIST VIDEO_X=\"0\" VIDEO_Y=\"0\" >\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "<VIDEO TITLE=\"".$row['title']."\" THUMB=\"\" URL=\"".$row['path']."\"/>\n";
}
$xml_output .= "</PLAYLIST>";
echo $xml_output;
here is actionscript:
import fl.video.*;
var thumb_width:Number;
var thumb_height:Number;
var thumbs_x:Number;
var thumbs_y:Number;
var video_x:Number;
var video_y:Number;
var my_videos:XMLList;
var my_total:Number;
var main_container:Sprite;
var thumbs:Sprite;
var titles:Sprite;
var my_player:FLVPlayback;
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load (new URLRequest("playlist.php"));
myXMLLoader.addEventListener (Event.COMPLETE, processXML);
function processXML (e:Event):void {
var myXML:XML = new XML(e.target.data);
thumb_width = myXML.#THUMB_WIDTH;
thumb_height = myXML.#THUMB_HEIGHT;
thumbs_x = myXML.#THUMBS_X;
thumbs_y = myXML.#THUMBS_Y;
video_x = myXML.#VIDEO_X;
video_y = myXML.#VIDEO_Y;
my_videos = myXML.VIDEO;
my_total = my_videos.length();
makeContainers ();
callThumbs ();
makePlayer ();
}
function makeContainers ():void {
main_container = new Sprite();
addChild (main_container);
thumbs = new Sprite();
thumbs.addEventListener (MouseEvent.CLICK, playVideo);
thumbs.addEventListener (MouseEvent.MOUSE_OVER, onOver);
thumbs.addEventListener (MouseEvent.MOUSE_OUT, onOut);
thumbs.x = thumbs_x;
thumbs.y = thumbs_y;
thumbs.buttonMode = true;
main_container.addChild (thumbs);
titles = new Sprite();
titles.x = thumbs_x;
titles.y = thumbs_y;
main_container.addChild (titles);
}
function callThumbs ():void {
for (var i:Number = 0; i < my_total; i++) {
var thumb_url = my_videos[i].#THUMB;
var thumb_loader = new Loader();
thumb_loader.name = i;
thumb_loader.load (new URLRequest(thumb_url));
thumb_loader.contentLoaderInfo.addEventListener (Event.COMPLETE, thumbLoaded);
thumb_loader.y = (thumb_height+10)*i;
var thumb_title = my_videos[i].#TITLE;
var title_txt:TextField = new TextField();
title_txt.text = thumb_title;
title_txt.y = thumb_loader.y;
title_txt.x = thumb_width + 10;
title_txt.width = thumb_width;
title_txt.height = thumb_height;
title_txt.wordWrap = true;
titles.addChild (title_txt);
}
}
function thumbLoaded (e:Event):void {
var my_thumb:Loader = Loader(e.target.loader);
thumbs.addChild (my_thumb);
}
function makePlayer ():void {
my_player = new FLVPlayback();
my_player.skin ="videos/videoskin.swf";
my_player.skinBackgroundColor = 0xAEBEFB;
my_player.skinBackgroundAlpha = 0.9;
my_player.x = video_x;
my_player.y = video_y;
my_player.width = 500;
my_player.height = 400;
main_container.addChild (my_player);
my_player.source = my_videos[0].#URL;
}
function playVideo (e:MouseEvent):void {
var video_url = my_videos[e.target.name].#URL;
my_player.source = video_url;
}
function onOver (e:MouseEvent):void {
var my_thumb:Loader = Loader(e.target);
my_thumb.alpha = 0.5;
}
function onOut (e:MouseEvent):void {
var my_thumb:Loader = Loader (e.target);
my_thumb.alpha = 1;
}
anyone know where i am going wrong? It works with a normal xml file just not php
The format for your XML output in PHP is wrong. Every tag must be closed.
You have:
<?xml version="1.0" encoding="utf-8"?>
<PLAYLIST VIDEO_X="0" VIDEO_Y="0">
<VIDEO TITLE="videotitle" THUMB="thumbnail" URL="URL" />
</PLAYLIST>
You need to close the video tag. So output should look like this:
<?xml version="1.0" encoding="utf-8"?>
<PLAYLIST VIDEO_X="0" VIDEO_Y="0">
<VIDEO TITLE="videotitle" THUMB="thumbnail" URL="URL"></VIDEO>
</PLAYLIST>
You should also set the content-type for your PHP script.
header('Content-type: text/xml');
I don't have access to my laptop to thoroughly test your code, but this is my answer from a first glance at your code.