I'm trying to delete a data from my database with ActionScript 3.
I've created a php on my server :
<?php
include ("shared/connect.php");
$idToDelete = $_POST['idToDelete'];
$result = mysqli_query($conn,"
DELETE FROM `annoncesNew` WHERE id=$idToDelete");
?>
Then I have to send the variable idToDelete to this php in order to delete the entry.
So I did :
deleteBtn.addEventListener(MouseEvent.CLICK, deleteThisAnnonce);
function deleteThisAnnonce(event:MouseEvent):void {
trace("deleteThisAnnonce");
var variablesDelete:URLVariables = new URLVariables();
var varDelete:URLRequest = new URLRequest("http://www.***com/***/deleteAnnonce.php");
varDelete.method=URLRequestMethod.POST;
varDelete.data=variablesDelete;
var varLoaderDelete:URLLoader = new URLLoader;
varLoaderDelete.dataFormat=URLLoaderDataFormat.VARIABLES;
varLoaderDelete.addEventListener(Event.COMPLETE,completeHandlerDelete);
ValidateAndSendDelete();
function completeHandlerDelete(event:Event):void{
trace("Data Sent");
}
function ValidateAndSendDelete():void{
trace("deleting"+item.id); //item.id is my the ID. When I trace the output is 144 so it's good.
variablesDelete.idToDelete = item.id;
varLoaderDelete.load(varDelete);
}
}
So, with this code, it's supposed to delete the data where id = 144. But I've got this error when click on the deleteBtn : Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs..
(all the traces are working correctly but my data isn't delete).
I've tried my php by changing DELETE FROMannoncesNew WHERE id=$idToDelete");withDELETE FROM annoncesNew WHERE id=144"); and execute it on my webbrowser and it worked (the line with the id 144 was deleted).
Weirdly, the line is delete with my AS3 code (so the code is working) but it throws this error 2101 anyway. Any idea why ?
Thx
I believe the problem is not in your AS3 code but that your PHP script is not returning any values back to Flash. Try to add this to your PHP script:
echo "Status=true";
And you might need this in your AS3:
varLoaderDelete.dataFormat = URLLoaderDataFormat.TEXT;
Related
I try to parse a string to a jquery object, but I dont get it in the right format. Don't know where the mistake is.
My goal is to load the data from database an put it into a dialog, where I can update the user
I have a post request in my js file which is executed pressing a button:
$.post("index.php", { "id": ID , "action": "edit_row"},
function(input){
console.log(input); //{"id":"1","fname":"Test","lname":"Name"}
console.log(input.id); //undefined
var data = $.parseJSON(input); //Uncaught SyntaxError: Unexpected token
console.log(data); //not possible
console.log(data.id); //not possible
test = {"id":"1","fname":"Test","lname":"Name"};
console.log(test); // I get the object
console.log(test.id); //1
}); // when I use ',"json"' between the brackets nothing happens, no logs are written in console
my index.php throws the string back loaded from the database:
$query = "SELECT `id`, `fname` , `lname` FROM `user` WHERE `id`= ".$id; //it's just one row
$result = sql_query($query);
while ($row= mysql_fetch_assoc($result)){
$data = $row;
};
echo json_encode($data);
//php function
function sql_query($query){
$result = mysql_query($query);
if(!$result) {
die("Request Failed: " . mysql_error());
}
return $result;
}
Edit 2
I analysed the string response in the js file And I found out that the string gehts \r\n\r\n\r\n to the end. Even when I don't respond anything from the php file...
I think there is something corrupt in my index.php while handling the ajax request.
I did the request on a different php file and there it works without any problems.
$.post("test.php", { "id": ID , "action": "edit_row"},
function(input){
console.log(input); // I get the object
console.log(input.id); //1
//testdata below
test = {"id":"1","fname":"Test","lname":"Name"};
console.log(test); // I get the object
console.log(test.id); //1
},"json"); //using ',"json"' is working on the test.php file now
Now it would be nice to know why I get those new lines even when I dont respond anything
But I think that doesnt fit to the head querstion
use this statement on top of your index.php page
<?php error_reporting(0); ?>
Since you are using mysql_query it gives a warning message for deprecated function which is causing the error. The whole warning message is returned to your page which is not in the format you expect. This statement will suppress the warning and it should be fine. But i would suggest you to use PDO or mysqli.
I'm struggling so hard with a very silly bug. I send a form via Ajax with POST but since I also wanted a GET variable, I put it in the url.
I have something like:
var xhr = getXHR();
var id = <?php echo $id ?>;
var xhrUrl = 'request_performupdate?id='+id;
Then, in the performupdate function I have :
if($_GET)
{
$a = fopen('get.txt','w');
$test=$_GET['id'];
fwrite($a,'idlol:'.$test);
}
$id=$test;
But here, the file get.txt is well written with the correct value, but I get a notice error saying $test (the second one) doesn't exist... That's unbelievable ! Hope you will have an idea, thanks very much.
-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"}
Ok so I'm experimenting with the in HTML5 and have made a simple "paint" application in Javascript to draw where the user's mouse is on the screen. Works fine.
I then wanted to save the coordinates to a file. My program already had an array of the x coordinates and an array of the y coordinates from the Javascript code.
When the user presses a button, the onClick calls a function in the Javascript, which using jQuery, as in the Top Answer here How to get JavaScript function data into a PHP variable attempts to pass this into a php file to save.
However it isn't working. Should I be passing the data back into the original php document that contains the canvas? If so how do I then get it to do the code to save as the PHP is run when the document is loaded no?
CODE:
Ok this is in the original php file which contains the HTMl for the webpage including the canvas. Here's the relevant save button:
<button type="button" onclick="saveDrawing()" id="saveButton">Save</button>
This calls the following in a separate JS file
function saveDrawing(){
// First check that not drawing and have data
if (!readyToDraw && clickX!=null){
// If ready then pass back to the PHP file the data
$url = 'file_save_test.php';
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()});
}
else {
alert("Please add some coordinate points and press Finish before saving");
}
}
and file_save_test.php contains only the following
<?php
// retrieve data from the JS
$buffer_data['x_coords'] = $_GET['x_coords'];
$buffer_data['y_coords'] = $_GET['y_coords'];
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
// first want to open a file
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'w');
// now to loop through arrays and write!
/*for ($i = 0; $i < sizeof($x_s); i++){
fwrite($file_handler, "$x_s[i], ");
fwrite($file_handler, "$y_s[i]\n");
} */
fclose($file_handler);
?>
In your PHP file it looks like your fwrite code is commented out. Are you expecting it to write to that data_test.txt file? Try changing your PHP file to print the results and have it echoed back to your javascript to see if the data is getting communicated properly.
$.get($url, {x_coords: getXCoords(), y_coords: getYCoords()},
function(data){
alert("Data Loaded: " + data);
});
PHP
print_r($_GET);
EDIT
Change your PHP file to something like this if it's alerting the data properly (it should append the coords to your file):
<?php
// retrieve data from the JS
$x_s = $_GET['x_coords'];
$y_s = $_GET['y_coords'];
$file_name = "data_test.txt";
$file_handler = fopen($file_name, 'a');
fwrite($file_handler, "$x_s, $y_s \n");
fclose($file_handler);
?>
EDIT 2
Update your for loop to your original code
for ($i = 0; $i < count($x_s); $i++){
fwrite($file_handler, $x_s[$i] . ", ". $y_s[$i] . "\n");
}
What I would do is have your save button call jQuery's $.post() method. Post the data to another PHP file that either inserts it into a database or saves it as a file. I don't recommend using the original document to post the data to because the client would have to download the entire DOM and the server would run any other code that you don't need.
That's as much as I can really help you without seeing any of your code.
I would send the data into a new php script called saveCoords.php or something..
You say you already have the coordinates in a JavaScript array, so it would look something like this...
//JAVASCRIPT FUNCTION which will request php file to store info
function storeCoords(xCoordArray, yCoordArray){
var xCoords = JSON.stringify(xCoordArray);
var yCoords = JSON.stringigy(yCoordArray);
var request = new XMLttpRequest(); //will need to change for older ie
request.onreadystatechange = function(){
//functions to handle returning information from php file..
}
request.open("GET","saveCoords.php?xCoords="+xCoords+"&yCoords="+yCoords, true);
request.send();
}
And then saveCoords.php file would look something like this:
<?php
$xCoords = json_decode($_GET['xCoords']);
$yCoords = json_decode($_GET['yCoords']);
//now you have a php array of xCoords and yCoords, which you can store
?>
Thats a skeleton but I think it hits on the major points, but comment with any questions.
i got stuck with OOP PHP and json data. i'm not completely new to OOP, but i can't get my head around this. if anyone can please explain to me, would be great!
i have the following grid object in PHP:
Class Grid {
var $data;
var $joins;
var $fields;
var $where;
var $table;
var $groupBy;
var $having;
var $limit;
var $order_by;
var $sort;
var $security;
var $set;
var $sql;
....
// loads data into the grid
function load() {
...
// setup the sql - bring it all together
$sql = "
SELECT $post[cols]
FROM `$table`
$joins
$where
$groupBy
$having
ORDER BY $order_by $sort
$limit
";
$this->sql = $sql;
// execute the sql, get back a multi dimensial array
$rows = $this->_queryMulti($sql);
// form an array of the data to send back
$data = array();
$data['rows'] = array();
foreach($rows as $i=>$row) {
foreach($row as $col=>$cell) {
// use primary key if possible, other wise use index
$key = $primaryKey ? $row[$primaryKey] : $i;
// primary key has an _ infront becuase of google chrome re ordering JSON objects
//http://code.google.com/p/v8/issues/detail?id=164
$data['rows']["_".$key][$col] = $cell;
}
}
...
$data['order_by'] = $order_by;
$data['sort'] = $sort;
$data['page'] = $page;
$data['start'] = $startRow + 1;
$data['end'] = $startRow + $nRowsShowing;
$data['colData'] = $colData;
$this->data = $data;
}
and it's called by AJAX callgrid.php:
$grid->load();
// here we need to add field in data[sql] = sql query, then we can pass it to toExcel() - how?
echo json_encode($grid->data);
what i'm trying to get is to be able to export current sql query (it can be all or searched results) into Excel using PHPExcel. So i've got toExcel.php with function toexcel($query) - that will take a query and export it to excel.
now - HOW do i pass sql query from grid to toexcel via AJAX?
I understand that i need to add to $data():
$data['sql'] = $sql;
what next?
UPDATE:
I'm using the following jquery grid:
http://square-bracket.com/openjs
I understand that PHPExcel should be initiated either by grid or jquery
A general idea of what you could do:
Create a button e.g.
export to Excel
Then in jquery you have to create something like:
var grid = $(".grid.digital_edit").loadGrid({...}); //or similar - what you did to load the data into the grid
$('#export').click(function() {
$.ajax({
url: "export_to_excel.php", // the url of the php file that will generate the excel file
data: grid.getData(), //or similar - based on the grid's API
success: function(response){
window.location.href = response.url;
}
})
});
The file export_to_excel.php will contain the code that generates the excel file:
This is where you'll initiate the PHPExcel class and create a file e.g. new_excel.xls
In your response array the $response['url'] will contain the absolute url to the newly created file. (http://www.example.com/files/new_excel.xls)
It may sound too complex, but try to separate your goals and achieve one at a time. E.g.
Create the button.
Then try to make a simple AJAX call when hitting the button.
Then create your export_to_excel.php file and try to work with the PHPExcel class.
Create a sample excel file based on the tutorials found.
Create an excel file based on your own data, but hard-coded in the php file.
Create the correct AJAX call that sends the wanted data to a php file.
Catch the correct AJAX call.
Pass the data from the AJAX call to the PHPExcel class.
Create the excel file.
Send back the url to the excel file.
Redirect the user to the url of the excel file.
EDIT
To help you a bit more: You need only one PHP script/file. The same one will receive the AJAX call from the javascript file, will generate the excel file and will return/respond the file url to the javascript file(in that order). A simplified example would be:
<?php
//export_to_excel.php
$data = $_POST['data']; // get the data from the AJAX call - it's the "data: grid.getData()" line from above
//... format the received data properly for the PHPExcel class
// later on in the same file:
$xls = new PHPExcel();
$xls->loadData($formattedData); //I assume that there is a similar loadData() method
$xls->exportToFile('/vaw/www/example.com/public/files/new_excel.xls'); // I assume that there is an exportToFile() method
$response = array(
'success' => true,
'url' => 'http://www.example.com/files/new_excel.xls'
);
header('Content-type: application/json');
// and in the end you respond back to javascript the file location
echo json_encode($response);
And then in javascript you display the file with this line
window.location.href = response.url; //response.url is $response['url'] from the PHP script