Zend 1 ajax with dojo informatiom person - ajax

I'm working with Zend 1 with dojo and do not know how to use ajax . In my particular case that when selecting a select , whether made ​​in consultation ajax back from the database information. To enter a ID from user print the information from user by ajax.In my work I can't use jquery.

Good question!
Not is very productive work with dojo, but is possible make exactly how do you want. You will create p element with information captured in data base
In your form, add attribute 'onChange'
$form->setAttrib('onChange', 'recoveryData()');
In js file do you have a function recoveryData(), something as:
dojo.require("dojo.html");
// clean data
var myNewElement = dojo.byId('myNewElement');
if (myNewElement != null) {
dojo.empty("myNewElement");
}
dojo.xhrPost({
content: {id: dojo.attr(dojo.byId("myElement"), "value")},
url: 'your-base-path/recovery-data/',
load: function (response) {
if (response != false) {
// converte to obj
var obj = dojo.fromJson(response);
// creat new element
var node = dojo.create("span", {
innerHTML: obj.NomeServidor,
id: "myNewElement",
'class': 'row'
}
);
dojo.place(node, dojo.byId("myElement"), "after");
}
}
});
Now, you need create an Action "recoveryDataAction()" in your Controller like this:
$data = $this->getrequest()->getPost();
$id = $data['id'];
if ($this->getrequest()->isXmlHttpRequest()) {
// disable layout
$this->_helper->layout()->disableLayout();
// disable view render
$this->_helper->viewRenderer->setNoRender();
$yourTable = new Project_Model_YourTable();
$row = $yourTable->fetchRow($id);
if ($infos != null) {
echo Zend_Json::encode($row);
return;
}
echo false;
}

Related

Laravel Search Array of Values

In my user registration workflow, I ask the user to select a pre-defined list of classifications (which I use a series of checkboxes for). Currently, I update my model with those values (or a blank value if the box isn't checked) when they move to the next step. These are not currently structured as an array, rather as a separate and distinct checkbox.
My 2 questions are as follows:
1) I read that if I save the checkboxes as an array I won't be able to easily search the database for users with a particular classification.
2) If that's true, I'm fine with my current structure, but I need to properly validate (server-side) that at least one of the checkboxes is selected otherwise provide an error. I have tried the following, but it doesn't return anything and the database record is created with nothing in each column.
if ($request->all() === "")
{
return Request::json('you must select one');
}
Database Table Migration:
Schema::create('user_type', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('games');
$table->string('art');
$table->string('music');
$table->string('building_stuff');
$table->string('educational');
$table->timestamps();
});
Javascript: (I submit as AJAX)
$('.modal-type-btn').click(function(e){
e.preventDefault();
if($('.checkbox-games').is(':checked'))
{
var games = "games";
} else {
var games = "";
}
if($('.checkbox-art').is(':checked'))
{
var art = "art";
} else {
var art = "";
}
if($('.checkbox-music').is(':checked'))
{
var music = music;
} else {
var music = "";
}
if($('.checkbox-building-stuff').is(':checked'))
{
var buildingStuff = "buildingstuff";
} else {
var buildingStuff = "";
}
if($('.checkbox-educational').is(':checked'))
{
var educational = "educational";
} else {
var educational = "";
}
$.ajax({
type: "POST",
url: "/profile/setup/1",
data: {games:games, art:art, music:music, buildingStuff:buildingStuff, educational:educational},
error: function(data){
console.log(data);
},
success: function(data){
console.log(data);
}
});
Thanks!
So, firstly you're much better of using them as an array and doing something like:
html:
<input type="checkbox" name="options[games]" value="1" />
that way, you can just get the form data and pass that into your $.ajax call:
...
data: $('form').serialize(),
....
and then in your controller, checking that the length of options is at least one:
$options = Input::get('options');
if(count($options) > 0){ ... }
You'll also probably want to define a list of "allowed" options and then use that to build your query:
private $_allowed_options = array('education', 'buildingStuff' ...);
public function update()
{
$options = Input::get('options');
foreach($this->_allowed_options as $allowed_options){
if(array_key_exists($allowed_option, $option)){
// add this option to our sql to add it to our user
// as they have selected it
}else{
// the user didn't select this one, so add it to be removed
// from the users
}
}
}

sending data from controller to model

I have the following code on my site which sending data to Ajax and works normal. It is about add to cart.
public function adding()
{
$id_lap=$this->input->post('id_lap');
$num_items=$this->input->post('num_items');
$price=$this->input->post('price');
if($id_lap !='')
{
$this->session->set_userdata('num_items',$num_items);
$this->session->set_userdata('price_new',$price);
$response=array(
'status'=>1,
'num_items'=>$num_items,
'price_new'=>$price
);
} else {
$response=array(
'status'=>0
);
}
echo json_encode($response);
}
When I want to send data to model also where I want to write data into database along with IP adress which I will collect with model. When I add new row anywhere my Ajax crashed. Part of code which I want to add is:
$this->users_mod->AddSesija($id_lap,$price);
And Ajax code which I am using is :
function Addtocart(id,prices)
{
var id_lap=id;
var ajaxURL= BASE_URL +'home/adding';
var num_items = parseInt($('#num_items').html()) + 1;
var price = parseInt($('#price_b').html());
var price_new = price + prices;
/*console.log(id_lap +' '+num_items+' '+price_new);
$('#num_items').html(num_items);
$('#price_b').html(price_new); */
$.ajax({
url:ajaxURL,
type:'POST',
data:{'id_lap':id_lap,'num_items':num_items,'price':price_new},
success:function(response)
{
var parsed = JSON.parse(response);
if(parsed.status ==1)
{
$('#num_items').html(parsed.num_items);
$('#price_b').html(parsed.price_new);
}
}
}
)
}
I am agree with Vladimir Glisovic in concept. we know that for adding or inserting group of data we should bind them into an array.
Sample:
$data=array( 'ip_adress'=>$ip_adress, 'id_lap'=>$id_lap, 'cena'=>$price );
N.b: get IP address from PHP code keep in $ip_address.
Then pass the data to model with the CI syntax.
Model calling in Controller:
$this->users_mod->AddSesija($data);
Now write the inserting code in the model file as
public function AddSesija($data){
insertion code here.....
}
Hope it will help you.
Thanks!
Amadercode

How to access local paths on TYPO3 using eID

I have an image map on my frontend and from there I need to access some images that are stored on different folders under the fileadmin directory. And I'm trying to do it with eID, following this example:
[http://www.alexanderschnitzler.de/2011/06/howto-ajax-requests-with-extbase-and-fluid/][1]
But my problem is that I can only access one directory. I haven't been able to access different directories based on the user selection from my front end.
This is the code of what I been trying to do:
On my Controller I have an ajaxAction, where I need to give the full path of one directory, because I haven't figure it out how pass the directory id on to my ajaxAction, here might be my question and maybe the solution:
/**
* #return void
*/
public function ajaxAction() {
$image_file_path = "fileadmin/Images/Sattic/Amik/small";
//$image_file_path = "fileadmin/Images/Sattic/'+$id+'";
$d = dir($image_file_path) or die("Wrong path: $image_file_path");
while (false !== ($entry = $d ->read())) {
if($entry != '.' && $entry != '..' && !is_dir($dir.$entry))
$images[] = $entry;
}
$d->close();
rsort($images);
return json_encode($images);
}
On my index.html I have a map tag where the function updateImage(id) is called, when the user clicks on the different areas and my updataImage(id) function looks like this:
function updateImageGallery(id) {
console.log(id);
var ajaxUrl = "{f:uri.action(action:'ajax', pageType:'100101')}";
$.getJSON(ajaxUrl, function(data) {
var items1 = [];
var items2 = [];
$data = data;
console.log('dataLength: ' + $data.length);
console.log('dataArray: ' + $data);
$.each($data.slice(0, 4), function(key, val) {
valLink = val.replace("small.", "");
items1.push('<td><img width="145" height="145" id="" src="fileadmin/Images/Sattic/' + id +'/small/'+ val +'"/></td>');
});
$('<tr/>', {
html: items1.join('')
}).appendTo('#glRegion');
$.each($data.slice(4, 8), function(key, val) {
valLink = val.replace("small.", "");
items2.push('<td><img width="145" height="145" id="" src="fileadmin/Images/Sattic/' + id +'/small/'+ val +'"/></td>');
});
$('<tr/>', {
html: items2.join('')
}).appendTo('#glRegion');
});
return false;
}
I would like to be able to pass from updateImageGallery(id) function, the id of the directory, so I could get the images for each directory.
Is it possible to do this? I hope so, I have 30 different regions and if I solve my problem the way I'm doing now I would need to use 30 different eID's. I guess it might be a smarter way to solve this.
Any sugestions?
You can use t3lib_div::_GET('myid') to access the myid get variable.
I guess you can use var ajaxUrl = "{f:uri.action(action:'ajax',**myid:id,** pageType:'100101')}"; to set it.
Anyway, sure to generate a list of valid paths/ids inside you PHP script and check the get parameter agains those.

Kohana validation client-side ajax

i've been working on a validation script for client-side, that uses built-in Kohana validation, trying to do it in a way that works both client and server sides. So far i made the server side work, but i need some help improving my javascript (My javascript knowlodgement ain't that good) and finish implementing it. (Currently it works for inputs and textareas).
A random controller:
// ...
$errors = array();
if ($this->request->method() == 'POST')
{
// Post to validate/look and get the decoded array
$validate = Request::factory('validate/look')->post($this->request->post())->execute()->body();
$errors = json_decode($validate, TRUE);
// Empty array, Validation OK
if ($errors === array())
{
// anything u want here
}
}
Now, the Validation controller (which will be called from any controller, or via ajax):
class Controller_Validate extends Controller {
public function action_look()
{
//$user = $this->user->loader() ? $this->user : NULL;
//Validation
$valid = Validation::factory($this->request->post())
->rules('name', array(
array('not_empty'),
array('min_length', array(':value', 10)),
array('max_length', array(':value', 80)),
array('regex', array(':value', '/^[\pL\pN ]++$/uD')),
array(array($this, 'check_name')),
))
->rules('description', array(
array('not_empty'),
))
->rule('look_tags', array($this, 'check_tags'))
;
$valid->check();
// Only get messages for the posted fields
$resp = array_intersect_key($valid->errors('uploadlook'), $this->request->post());
$this->response->body(json_encode($resp));
}
}
And this is the javascript:
$(function(){
$('.validate').find('input,textarea').blur(function(){
var element = $(this);
var name = $(this).attr('name');
var value = $(this).val();
$.ajax({
type: 'POST',
url: '/comunidad/validate/look',
data: name + '=' + value,
success: function(e){
e = JSON.parse(e);
if(e.length !== 0) {
var msg = e[name];
var error = '<p>' + msg + '</p>';
if (element.next().length === 0) element.after(error);
else element.next().replaceWith(error);
} else {
if (element.next().length) element.next().remove();
}
}
});
});
});
I need some feedback and little help completing the javascript :)
Some feedback on the code:
The validation code shoud be put in a helper and should just return an array. Then you should have an AJAX-controller that uses the helper and outputs JSON. The serverside check should only use the helper.
That would be much cleaner and the json encode/decode on the server side is pretty ugly when you can just return an array.
What is wrong with the javascript?

dojo.xhrPost and Zend Framework action, no POST data, not using a form

I'm trying to send some data via dojo.xhrPost to an Zend Controller Action. I can see the data being sent in Firebug console. However, when inspecting the post data, the array is empty.
I'm not sure if it is possible to send an arbitrary string of data via dojo.xhrPost without using a form. This is probably a very n00b mistake. In any case, I'll post my code here and see what you all think.
In my layout script I have:
<?php
$sizeurl = $this->baseUrl() . '/account/uisize';
?>
function resizeText(multiplier)
{
if (document.body.style.fontSize == "")
{
document.body.style.fontSize = "1.0em";
}
document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.1) + "em";
var size = document.body.style.fontSize;
var xhrArgs = {
url: "<?= $sizeurl; ?>",
postData: size,
handleAs: "text"
}
dojo.xhrPost(xhrArgs);
}
Then my action is:
public function uisizeAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
print_r($_POST);
$request = $this->getRequest();
if ($request->isXmlHttpRequest())
{
$postdata = $request->getPost();
print_r($postdata);
if ($postdata)
{
$user = new Application_Model_DbTable_User();
$user->updateSize($postdata);
}
}
}
I'm pretty sure that post data from a form is an array with the form elements' names as the keys. When looking at the dojo.xhrPost examples on the dojo campus web site (http://docs.dojocampus.org/dojo/xhrPost second one to be precise), it looks as if I can just send a string of data. How do I access this data from a Zend Controller Action?
I'm using ZF 1.10 and Dojo 1.4.2
Thanks for your help!
PS
I'd try to ask on one of the related questions, but I cannot seem to comment.
After reading about http methods here:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
I figured that I need to encode the data sent in a way that will be converted to an array by PHP. So here is the new bit of javascript:
function resizeText(multiplier)
{
if (document.body.style.fontSize == "")
{
document.body.style.fontSize = "1.0em";
}
document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.1) + "em";
var rawdata = "uisize="+document.body.style.fontSize;
var xhrArgs = {
url: "<?= $sizeurl; ?>",
postData: rawdata,
handleAs: "text"
}
//Call the asynchronous xhrPost
dojo.xhrPost(xhrArgs);
}
The difference is I am now specifying a key pair and sending that. When using AJAX that could make forms overkill. So now my UI is resized and the size is stored with the user's profile. So the next page they request will use the size they set. Cool.

Resources