When I try to pass the url value to the controller action, action is not getting the required value.
I'm sending the value like this:
function value(url,id)
{
alert(url);
document.getElementById('rating').innerHTML=id;
var params = 'artist='+id;
alert(params);
// var newurl='http://localhost/songs_full/public/eslresult/ratesong/userid/1/id/27';
var myAjax = new Ajax.Request(newurl,{method: 'post',parameters:params,onComplete: loadResponse});
//var myAjax = new Ajax.Request(url,{method:'POST',parameters:params,onComplete: load});
//alert(myAjax);
}
function load(http)
{
alert('success');
}
and in the controller I have:
public function ratesongAction()
{
$user=$_POST['rating'];
echo $user;
$post= $this->getRequest()->getPost();
//echo $post;
$ratesongid= $this->_getParam('id');
}
But still not getting the result.
I am using zend framework.
Need alot more information here... How are you calling these functions? Are the values being passed at any stage in the chain? You mention "action", what are you actually referring to?
Further on that - if you mean that the values are not being handled within the PHP section, are you using the correctly named parameters? I see your Javascript code mentioned one parameter called "artist", but the PHP code mentions "rating" alone.
Related
I am trying to display records from query in a table and on button clicked to make an ajax call to download the information in an xml format. The query is executed from method inside a class and the ajax request makes call to a different method inside the same class. The first method fills two private properties inside the class and the second property(the one called through the ajax request) must read the properties and fill the data inside table and make the file downloadable. When I try to read the properties from the same class though I get nulls and the foreach returns an error.
This is my ajax request(downloaderScript.js):
;
$("#downloadBtn").click(function (event) {
event.preventDefault();
event.stopPropagation();
$.ajax({
url: 'allClients.php',
type: 'post',
data: {action: 'downloader'},
complete: function (result) {
console.log(result);
},
error: function () {
console.log('Error');
}
});
});
This is the class from which I call the first and the second methods:
class HttpHandlerClient extends HttpHandlerAbstract
{
private $clientsService;
public $storedClientsHeadings;
public $storedClientsData;
public function viewAllClients()
{
$data = $this->clientsService->getAllClients(clientEntity::class);
if(isset($data)) {
$this->storedClientsHeadings = ["Client Names:", "Delivery Address:", "Phone number:"];
$this->storedClientsData = $data;
$this->render('allClientsView', $data);
}
else
{
$this->redirect('clientAdd');
}
}
public function downloader()
{
header("Content-Type: text/plain");
var_dump($this->storedClientsHeadings);
foreach ($this->storedClientsHeadings as $arrayName)
{
echo implode("\t", $arrayName)."\r\n";
}
/**
* #var clientEntity $clientData
*/
foreach ($this->storedClientsData as $clientData)
{
echo implode("\t", $clientData->getClientName())."\r\n";
echo implode("\t", $clientData->getAddressForDelivery())."\r\n";
echo implode("\t", $clientData->getPhone())."\r\n";
}
$filename = "clients_".date("Y-m-d").".xls";
header("Content-Disposition:attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");
}
And this is the php file that i use between my ajax request and the php class(The file name is: allClients.php, in common.php I make an instance of the class HttpHandlerClient):
require_once 'common.php';
if(isset($_POST['action'])){
$myHttpHandlerClient->downloader();
} elseif (isset($_GET['typer'])) {
$myHttpHandlerClient->viewClientByNumber($_GET['typer']);
} else {
$myHttpHandlerClient->viewAllClients();
}
Sorry if my question is trivial, I even started doubting that after require_once I re-run the code in common.php, making a new instance of HttpHandlerClient and because of this I get nulls in the properties. But when I was reading the documentation in php's site I did not read such a thing. Any help will be appreciated, thanks.
It sounds like what may be happening is that there is a disconnect between the javascript initially loading and then more markup being added to the DOM.
The page loads up which runs your javascript. At this point the JS only knows what is currently on the page.
Your make the first call which changes the DOM. Your javascript does not know about these changes.
You try to reference something that has not been recognized by your initial load of the Javascript.
After you make the call that changes the DOM, you may have to reinitialize your JS to recognize the changes.
Good luck
I'm trying to solve a problem in ajax which is coming out from the moment that my client asked me to not use any framework for web applications.
I have always used CodeIgniter and I never had any problem with ajax requests, especially when I had to call a method simply perform this call:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
//http://localhost/App_Name/application/controllers/user.php/ajax_check_login <-postUrl content
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// do stuff...
});
How you can see from the code above what I want to do is call a method within the controller user.php whose name is ajax_check_login.
What I have done so far to achieve the desired result is to make this code:
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}
if you want to see the complete structure of a class click here.
The problem is that this code should be placed inside each controller,
and you have to set all the methods offered, sometimes the function available reaching fifty, leads to discard this solution...
What I want to know is: how can I make a wrapper, a class that allows me to invoke a method of the controller from url and execute it?
Before all this work was done by CodeIgniter. So now I have to write my own class that allows me to access the controls easily and recall methods in different classes.
All classes that have to respond to ajax request reside in application/controllers / ... folder. In the controllers folder I have 20 controllers.
You can add ajax.php:
<?php
preg_match_all('/([^\/.]*)\.php\/([^\/]*)$/', $_SERVER['REQUEST_URI'], $matches);
$class = $matches[1][0];
$func = $matches[2][0];
$allowed_classes = array('user','account','foo');
if (isset($class) && isset($func) && in_array($class, $allowed_classes)) {
require_once "application/controllers/" . $class. ".php";
// here you could do some security checks about the requested function
// if not, then all the public functions will be possible to call
// for example if you don't want to allow any function to be called
// you can add a static function to each class:
// static function getAllowedFunctions() {return array('func1','func2');}
// and use it the same way you had checked it in the question
$obj = new $class();
$obj->$func();
// or if need to pass $_POST:
// call_user_func(array($obj, $func, $_POST));
}
and in javascript post to:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/ajax.php/user.php/ajax_check_login';
If you have apache, then you might be able to do it even without adding ajax.php by adding this to .htaccess in the controller directory:
RewriteEngine On
RewriteBase /baseUrl.../application/controllers/
RewriteRule ^([^\.]*\.php)/[^/]*$ ajax.php?file=$1&func=$2
Of course you need your real baseUrl there. And change the 1st 3 lines in the php to:
$class = $_GET['class'];
$func = $_GET['func'];
i have a multipage form with some textfields. When you fill out the form and press next the form stores the values in an object.
When you press the backbutton it reloads those values in textfields. This works fine.
But when you initially load the form, the object isn't created so there is nothing to load the values from and i get a Call to a member function on a non-object error.
example:
<inputfield value='$object->getValue()'>
is there a way to tell it that when the object doesn't exist to just leave it empty?
You could do the following before using the object:
// All methods called on this object return an empty string.
class EmptyObject {
public function __call($name, $args) {
return '';
}
}
// Use fake object if $object is not defined correctly.
if (!is_object($object)) {
$object = new EmptyObject();
}
__call is a magic method in PHP. It gets invoked every time an undefined method is called on the object.
The is also an isset method:
if(isset($object)){
//it is there
}
Try this:
$output = "<inputfield value='". (isset($object) ? $object->getValue() : '') . "'>";
There is is_object method:
if (is_object($object)){
// it is there
}
So you can check for it something like this:
<inputfield value='<?php is_object(#$object) ? $object->getValue() : '';?>'>
I'm using Actionscript 2.0 in combination with PHP, now I can make a call to my PHP file and receive data but apparently I have to use that data immediately, I cannot use it to fill my class variables.
This is what I want :
class user {
var lastname:String;
function user(in_ID:Number){
var ontvang:LoadVars = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
ontvang.onLoad = function(success:Boolean) {
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
};
}
}
I've found out that this is a big issue in AS2, I found this post to work around it if you're loading XML data but I can't seem to get it to work with LoadVars :
http://www.actionscript.org/forums/showthread.php3?t=144046
Any help would be appreciated ..
When your onLoad handler is called, it is being called as if it were a member function of the LoadVars instance, and not your user instance.
There are several ways around this, one is to use Delegate.create() to create a function which will work as intended, for example:
import mx.utils.Delegate;
class user {
var lastname:String;
var ontvang:LoadVars;
function user(in_ID:Number){
ontvang = new LoadVars();
var zend:LoadVars = new LoadVars();
zend.ID = in_ID;
ontvang.onLoad = Delegate.create(this, onLoad);
zend.sendAndLoad("http://localhost/Services/getUser.php", ontvang, "POST");
};
}
function onLoad(success:Boolean) : Void
{
if (success) {
lastname = ontvang.lastname;
} else {
lastname = 'error';
}
}
}
Don't forget that the load is asynchronous - when you create one of your user objects, the member variables won't be immediately available. What you may need to do is let your user object be capable of signaling its readiness much like LoadVars does, (e.g. with a callback function provided by the caller) so that your app is driven by by these asynchronous events.
There is basic persistence of Javascript vars/etc. You call a function/method, and the next time you call that same function/method, it is holding the data from the last time.
You can delete the vars when you are done with them, but that removes the advantage of using the code again for that instance.
So what is the proper way to write code which can be reused, on different elements, inside the same page.
Therefore, I need the ability to write code so that I can point it at several different elements, and then interact with that code segregated for each element.
So in PHP (as an example) I would do:
$element1 = new MyClass();
$element2 = new MyClass();
$element3 = new MyClass();
in that case it's the same code running in three segregated scopes. How can I do this properly with JS. Even using jQuery's extend() gives me problems.
Thanks.
Use the var keyword when defining local variables (otherwise they'll default to globals).
function foo() {
var i;
// code code code code
}
To create an instance in JavaScript you need to write a constructor function, and call that using new. For instance:
function MyClass( somevalue ) {
this.somevalue = somevalue;
this.somefunction = function() {
alert(somevalue);
}
}
var instance1 = new MyClass(1);
var instance2 = new MyClass(2);
var instance3 = new MyClass(3);
You can namespace your JavaScript to make it a lot like what you're after. See below for an example. It does sound like your problem is related to using global variables where you want to use local variables though - i.e. you declare var myvariable; outside of your function, but only want to use it and forget it within your function. In that case, declare the variable inside your function to make it local.
var MyNameSpace = function() {
return {
sayhello : function() {
alert("hello");
},
saygoodbye : function() {
alert("see ya");
}
};
}();
It sounds like what you're looking for is the ability to have instances of a class and have private data that's associated with each instance.
You can do this using the following technique:
function Foo()
{
// Member variable only visible inside Foo()
var myPrivateVar;
// Function only visible inside Foo()
var myPrivateFunction = function()
{
alert("I'm private!");
}
// Member variable visible to all
this.myPublicVar = "Hi, I'm public!";
// Function visible to all
this.myPublicFunction = function()
{
myPrivateVar = "I can set this here!";
}
}
You can create and use one of these using the following syntax:
var myFoo = new Foo();
myFoo.myPublicVar = "I can set this!";
myFoo.myPublicFunction();