Communicating with a DB in LimeJS - database

What is the proper way to load variables into my game from a DB?
I tried using Ajax and the Prototype library, but that doesn't seem to work. Here's what I did:
In my main .js game file...
var rawVocab = new Array();
var optionVocab = new Array();
new Ajax.Request('load_vocab.php', {
onSuccess : function(xmlhttp) {
eval(xmlhttp.responseText);
}
});
'load_vocab.php' looks like this...
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$username = "user";
$password = "***************";
try {
$conn = new PDO('mysql:host=localhost;dbname=tygrif_school', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM vocabulary_game WHERE game_type = :game_type');
$stmt->execute(array('game_type' => 'target'));
$i=0;
while($row = $stmt->fetch()) {
echo "rawVocab[".$i."]['word']='".$row['word']."';";
echo "rawVocab[".$i."]['translation']='".$row['translation']."';";
echo "rawVocab[".$i."]['example_sentence_1']='".$row['example_sentence_1']."';";
$i++;
}
$stmt = $conn->prepare('SELECT * FROM vocabulary_game');
$stmt->execute(array());
$i=0;
while($row = $stmt->fetch()) {
echo "optionVocab[".$i."]['word']='".$row['word']."';";
echo "optionVocab[".$i."]['translation']='".$row['translation']."';";
echo "optionVocab[".$i."]['example_sentence_1']='".$row['example_sentence_1']."';";
$i++;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo '</response>';
?>
Is there some built in way to handle this with the goog library?

Apparently, Google Closure has a built-in way (goog.net.XhrIo) to handle Ajax calls.
1 - http://docs.closure-library.googlecode.com/git/class_goog_net_XhrIo.html
2 - http://www.daveoncode.com/2009/11/17/goog-net-xhrio-make-simple-ajax-calls-with-google-closure/

Related

how can i combine href with id number

Trying to get some data from db but I can't use href with id number in code.
I tried everything but coldn't make it.
<?php
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array($db->quoteName('title')));
$query->select(array($db->quoteName('id')));
$query->select(array($db->quoteName('start_date')));
$query->select(array($db->quoteName('end_date')));
$query->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
$results = $db->loadObjectList();
// display the results
foreach ( $results as $result) {
echo <<<HTML
$result->title .
HTML;
echo "<p>" . $result->start_date . "</p>";
echo "<p>" . $result->end_date . "</p>";
}
?>
I will be appreciated if someone help me.
Thanks in advance
Demonstration of issue then my suggested solution: (Online Demo)
$result = new stdClass();
$result->id = 333;
$result->title = 'title text';
echo <<<HTML
$result->title .
HTML;
Output:
Notice: Undefined variable: id in /in/s1YZG on line 7
title text .
Notice that $id isn't a declared variable. If it was, it would be rendered but all characters between the curly braces are treated literally because you are trying to echo within an echo.
Without heredoc syntax (heredoc can be funny about tabbing depending on php version):
echo "{$result->title} . "; // curly braces may help IDEs with highlighting
New Output:
title text .
As for your query building syntax...
You can save some typing and chain the method calls onto getQuery().
None of the quoteName() calls are necessary for stability/security, but if you insist on toeing Joomla's preferred practices, you can call quoteName() on the array in select().
Suggested Code:
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName(array('title', 'id', 'start_date', 'end_date')))
->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
if (!$results = $db->loadObjectList()) {
echo "No results";
} else {
foreach ($results as $row) {
echo "{$row->title} . ";
echo "<p>{$row->start_date}</p>";
echo "<p>{$row->end_date}</p>";
}
}
Here is another post where loadObjectList() is called after a SELECT query which includes query error checking: https://joomla.stackexchange.com/a/22963/12352
When you have Joomla questions, please post them on Joomla Stack Exchange.
I would try it like this:
also you are trying to echo $id which isnt assigned. should be $results->id
<?php
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select(array('title', 'id', 'start_date', 'end_date' ));
$query->from($db->quoteName('#__rbid_auctions'));
$db->setQuery($query);
$results = $db->loadObjectList();
// display the results
foreach ( $results as $key => $result) {
echo ' <a href="index.php?option=com_rbids&task=viewbids&id='.$result->id .'>'.$result->title .'</a>';
echo "<p>" . $result->start_date . "</p>";
echo "<p>" . $result->end_date . "</p>";
}
?>

CakePHP 3.x call function

I have a view that is add a called help desk opening form (referring to add function, of course), and have this function is to upload that file to attach request, which is connected with a component, but I do not want to Let them in different view, because if I just send a file upload through the view, the image is "lost " and does not turn the call. I need within the add function I can call the upload function, to join views. If I call her by $ this-> upload (); Or simply make all the checking in of add, does not find the component, returning me an error (which I put down ), I believe the conflict is in the request-> data but do not know if there is a way to join the way I explained.
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is(['post', 'put'])) {
$this->Posts->patchEntity($post, $this->request->data);
$post->user_id = $this->Auth->user('id');
if ($this->Posts->save($post)) {
$this->Flash->success(__('send'));
return $this->redirect(['action' => 'listar']);
}
$this->Flash->error(__('not send'));
}
$this->set(compact('post'));
}
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data(['uploadfile']));
return $this->redirect(['action'=>'add']);
}
}
Component:
public function send( $data )
{
if ( !empty( $data) ) {
if ( count( $data) > $this->max_files ) {
throw new InternalErrorException("Error Processing Request. Max number files accepted is {$this->max_files}", 1);
}
foreach ($data as $file) {
$filename = $file['name']; //line 32
$file_tmp_name = $file['tmp_name']; //33
$dir = WWW_ROOT.'img'.DS.'Anexos';
$allowed = array('png', 'jpg', 'jpeg');
if ( !in_array( substr( strrchr( $filename , '.') , 1 ) , $allowed) ) {
throw new InternalErrorException("Error Processing Request.", 1);
}elseif( is_uploaded_file( $file_tmp_name ) ){
$filename = Text::uuid().'-'.$filename;
$filedb = TableRegistry::get('Arquivos');
$entity = $filedb->newEntity();
$entity->filename = $filename;
$filedb->save($entity);
move_uploaded_file($file_tmp_name, $dir.DS.$filename);
}
}
}
}
Error when calling upload();
Warning (2): Illegal string offset 'name' [APP/Controller\Component\UploadComponent.php, line 32]
Warning (2): Illegal string offset 'tmp_name' [APP/Controller\Component\UploadComponent.php, line 33]
view:
<?php
//this is my view add ;
echo $this->Form->input('id' );
echo $this->Form->input('titulo');
echo $this->Form->input('ip');
echo $this->Form->input('mensagem');
?>
//and this is my view upload, I would like to join with add ;
<?php echo $this->Form->create(null, ['type' => 'file']); ?>
<label>Arquivos</label>
<?php
echo $this->Form->file('uploadfile.', ['multiple']);
echo $this->Form->button('Anexar', ['action' => 'submit']);
echo $this->Form->end();
?>
You aren't accessing uploadfile array. This line $this->Upload->send($this->request->data(['uploadfile'])); should be like $this->Upload->send($this->request->data('uploadfile'));.
public function upload()
{
if ( !empty( $this->request->data ) ) {
$this->Upload->send($this->request->data('uploadfile'));
return $this->redirect(['action'=>'add']);
}
}

Issues with results from joomla database to screen

I seem to be stuck. I have checked this document JDatabase 3.0
And i cant figure out why my rusults from the column wont display on the screen.
Its possible its an issue with the WHERE statement but it does echo out the correct username so I'm not sure. Here is the code I have been manipulating.
{source 0}
<?php
$user =& JFactory::getUser();
if (!$user->guest)
$name = $user->username;
$db =& JFactory::getDbo();
$query = $db->getQuery(true);
$query = "SELECT image_url FROM #__image_data WHERE user_name = $name";
$db->setQuery($query);
$results = $db->image_url(); //also tried $results = $db->loadObjectList
and loadAssocList
echo $results
?>
{/source}
You need
$list = $db->loadObjectList();
foreach ($list as $item){
echo $item->image_url.'<br />';
}

cakephp post data field missing from SQL update statement

Having trouble geting cakephp to update a record.
Controller Code:
public function viewBenefit($id) {
if ($this->request->is('post')) {
$this->set('post', $this->request->data);
$this->Benefit->id = $id;
if ($this->Benefit->save($this->Benefit->data)) {
$myVars['Sucsess'] = TRUE;
$this->Session->setFlash('Updates Saved');
} else {
$myVars['NewID'] = 0;
$myVars['Sucsess'] = False;
$this->Session->setFlash('There was an error.');
}
}
$this->Benefit->recursive = 2;
$this->Benefit->id = $id;
$this->set('benefit', $this->Benefit->read());
}
Relevant View Code:
<?php echo $this->Form->create('Benefit',array('action'=>'edit','url' => '#')); ?>
<?php echo $this->Form->input('id',array('type'=>'hidden')) . "\n"; ?>
<?php echo $this->Form->input('short_description',array('type'=>'textarea')) . "\n"; ?>
<?php echo $this->Form->end(); ?>
NOTE: The Form is sumbitted via JS
POST Data (via debug($post); )
array(
'Benefit' => array(
'id' => '1952e98e-f589-47d4-b458-11a1bd58ba3b',
'short_description' => '<p>This is great sample insurance 321321</p>'
)
)
SQL UPDATE statment:
UPDATE `c16memberdev`.`benefits` SET `modified` = '2012-12-04 10:45:16' WHERE `c16memberdev`.`benefits`.`id` = '1952e98e-f589-47d4-b458-11a1bd58ba3b'
As you can see the field "short_description" does not get added to the SQL statement, and therefore the data not added to the database. Thanks for your help.
Try changing
$this->Benefit->save($this->Benefit->data)
to
$this->Benefit->save($this->request->data)

Get array from model, then pass to view

Simple, but for me as a beginner, a problem. I need to pass an array from my model (array is filled with info while reading a text file) to a controller and then finally to a view.
My model:
function show_notes(){
$file = "notes.txt";
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
$notes = array (
'user'=> '$user',
'content'=> '$content'
);
}
return $notes;
}
Controller:
function members_area()
{
$this->load->model('Note_model');
$notes[] = $this->Note_model->show_notes();
$this->load->view('includes/header');
$this->load->view('members_area', $notes);
$this->load->view('includes/footer');
}
And in view I use this:
foreach ($notes as $item)
{
echo "<h1>$user</h>";
echo "<p>$content</p>";
}
And I am getting error that notes variable is undefined in my view.
I think I just don't understand how arrays work. I have tried to read about that, I have tried some examples similar to this, but still can't get it.
In your controller:
$data['notes'] = $this->Note_model->show_notes();
...
$this->load->view('members_area', $data);
EDIT:
In your view:
<?php foreach ($notes as $item):?>
<h1><?php echo $item['user']; ?></h1>
<p><?php echo $item['content'] ?></p>
<?php endforeach; ?>
In your model:
$notes = array();
foreach(file($file) as $entry)
{
list($user, $content) = array_map('trim', explode(':', $entry));
array_push($notes, array('user' => $user, 'content' => $content));
}
return $notes;
Replace this
$notes[] = $this->Note_model->show_notes();
with this
$notes['notes'] = $this->Note_model->show_notes();

Resources