Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Code not executing, nor error.. (javascript)

Posted on 2010-09-22
3
Medium Priority
?
719 Views
Last Modified: 2013-11-10
Trying to implement AJAX in the style of Zend Framework In Action.
http://www.manning.com/allen/
(source code available)

I have the example site Places up and running.

Now trying to do some ZF/Ajax on my own but no success..or failure.
Problem:
None of the code blocks
evalUsername.prototype.success = function(o)
or
evalUsername.prototype.failure=function(o)

will execute!

I think it's quite similar to the ZFIA code but it just doesn't work. What is wrong with "my" code?
I get no error in the Firefox error console.
I'm not so hot on javascript.












registerform.js
----------------
/**
 * Debug
 */
function apa()
{
    alert("apa"); 
}

function hej_apa()
{
    alert("Hej apan Östen");
}


function evalUsername(userName, baseUrl) {

    var sUrl = baseUrl + "/account/checkusername/format/json/username/"
        + userName ;

    // perform the request.
    YAHOO.util.Connect.initHeader('X_REQUESTED_WITH', 'XMLHttpRequest');
    YAHOO.util.Connect.asyncRequest('GET', sUrl, this);



}

evalUsername.prototype.success = function(o)
{
    
    if(o.responseText !== undefined)
    {
        var json = eval("(" + o.responseText + ")") ;
        document.getElementById('testi').innerHTML=json.result;        
    }
    else
    {   
        this.failure(o);
    }
}


evalUsername.prototype.failure=function(o) {
     document.getElementById("testi").value="epic fail";
}


AccountController.php
----------------------
.
.
.

        //This controller contains AJAX-functions
    public $ajaxable = array('feedback'=> array('json')); //inspired by Zend Framework In Action http://www.manning.com/allen/


    public function init()
    {

            //inspired by Zend Framework In Action http://www.manning.com/allen/ :
            $ajaxContext = $this->_helper->getHelper('AjaxContext');
            $ajaxContext->initContext();
        
            
            
    }    
.
.
.
        /**
         * Ajax method
         */
        public function checkusernameAction()
        {
            $u=$this->getRequest()->getParam("username");
            $this->view->result=($u=="kalle")?true:false; //return json values
        }
.
.
.


registerform.phtml - call js function
--------------------------------------
<?php

$this->headScript()->appendFile($this->baseUrl().'/js/yui/yahoo.js');
$this->headScript()->appendFile($this->baseUrl().'/js/yui/event.js');
$this->headScript()->appendFile($this->baseUrl().'/js/yui/connection.js');
$this->headScript()->appendFile($this->baseUrl().'/js/registerform.js');

if(isset($this->form))
{
    ?>
    <br/>
    <input type="button" onclick="new evalUsername(getElementById('user-username').value,'<?=$this->baseUrl?>'); return false;" value="Evaluera username" />
    <br/>
    <input type="button" onclick="apa()" value="Apa" />
    <br/><label id="testi">testi-laabel</label>

    <?php


    $p=$this->form->user;
    $p->username->setLabel("Användarnamn");
    $p->password->setLabel("Lösenord");
    $p->confirmpass->setLabel("Bekräfta lösenord");

    $p=$this->form->name;
    $p->firstname->setLabel("Förnamn");
    $p->sirname->setLabel("Efternamn");

    $p=$this->form->email;
    $p->email->setLabel("E-post");
    $p->confirm->setLabel("Bekräfta e-post");

    $p=$this->form->location;
    $p->city->setLabel("Närmaste stad");

    $p=$this->form->sex;
    $p->sex->setLabel("Kön");

    $p=$this->form->dob;
    $p->year->setLabel("År");
    $p->month->setLabel("Månad");
    $p->day->setLabel("Dag");

    $this->form->submit->setLabel("Skicka");

    echo $this->form;
}
else
{
    ?>
    
    <?php
}
?>








CODE FROM "ZEND FRAMEWORK IN ACTION", "PLACES" APPLICATION - WORKS (manning.com/allen)
______________________________________________


_reviewFeedback.phtml 
----------------------

<?php
$id = $this->id;
$yesCount = $this->helpful_yes;
$totalCount = $this->helpful_total;
?>

<span id="counts-<?php echo $id ?>" >
    <?php echo $yesCount ?> of <?php echo $totalCount; ?>
</span>
people found this review helpful. Was this review 
helpful to you? 
<span id="yesno-<?php echo $id?>" >
    <a href="#" onclick="new ReviewFeedback(1, 
        <?php echo $id; ?>,'<?php echo $this->baseUrl(); ?>');
        return false;">Yes</a> 
    <a href="#" onclick="new ReviewFeedback(0, 
        <?php echo $id; ?>,'<?php echo $this->baseUrl(); ?>'); 
        return false;">No</a>
<span id="spinner-<?php echo $id ?>"></span></span>
<div id="message-<?php echo $id ?>"></div>


review_feedback.js
-------------------
// ReviewFeedback class used as callback to

// YUI connection manager

function ReviewFeedback(response, reviewId, baseUrl) {

	this.id = reviewId;

	this.baseUrl = baseUrl;

	

	// turn on spinner and empty the informationmessage

	this.startSpinner();

	this.message("","");



	// ensure that we don't have to encode parameters

	var reviewId = parseInt(reviewId);

	var response = parseInt(response);



    var sUrl = baseUrl + "/review/feedback/format/json/id/"

        + reviewId + "/helpful/" + response;



	// perform the request.

    YAHOO.util.Connect.initHeader('X_REQUESTED_WITH', 'XMLHttpRequest');

    YAHOO.util.Connect.asyncRequest('GET', sUrl, this);



} 



ReviewFeedback.prototype.success = function(o) {

    if(o.responseText !== undefined){

		var json = eval("(" + o.responseText + ")") ;

		if(json.result && json.id == this.id) {		

			// update the information text to include the new counts

            document.getElementById('counts-'+json.id).innerHTML 

                = json.helpful_yes + ' of ' + json.helpful_total;

			

            // say thank you and stop the spinner

            this.message("success", 'Thank you for your feedback.');

            this.stopSpinner();

			

            // remove yes/no buttons as they aren't needed after feedback

            document.getElementById('yesno-'+json.id).innerHTML = "";			

        } else {

            this.failure(o);

        }

    }

}



ReviewFeedback.prototype.failure = function(o) {

	// inform the user of failure and stop the spinner

	var text = "Sorry, our feedback system hasn't worked. Please try later.";

	this.message("failed", text);

	this.stopSpinner();

}



ReviewFeedback.prototype.startSpinner = function() {

    var spinner = document.getElementById('spinner-'+this.id);

    var url = this.baseUrl+'/img/logo.gif';

    spinner.innerHTML = '<img src="'+ url +' " border="0" />';

}



ReviewFeedback.prototype.stopSpinner = function() {

	document.getElementById('spinner-'+this.id).innerHTML = ""; 

}



ReviewFeedback.prototype.message = function(class_, text) {

	document.getElementById('message-'+this.id).className = class_;

	document.getElementById('message-'+this.id).innerHTML = text; 

}




ReviewController.php
--------------------
<?php

class ReviewController extends Zend_Controller_Action
{
    public $ajaxable = array('feedback'=> array('json'));
    function init()
    {
        $readActions = array('index' , 'feedback' , 'add');
        $writeActions = array();
        $this->_helper->_acl->allow('member', $readActions);
        $this->_helper->_acl->allow('admin', $writeActions);
        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        //$ajaxContext->addActionContext('feedback', 'json');
        $ajaxContext->initContext();

       
    }
    
    public function addAction()
    {
    	$userId = (int)Zend_Auth::getInstance()->getIdentity()->id;
    	$users = new Users();
    	$user = $users->fetchRow('id='.$userId);
    	
        $this->view->messages = array();
        $redirector = $this->_helper->getHelper('Redirector'); /* @var $redirector Zend_Controller_Action_Helper_Redirector */
        
        $placeId = (int) $this->getRequest()->getParam('placeId');
        $this->view->placeId = $placeId;
        
        if ($this->view->placeId > 0) {
            $places = new Places();
            $place = $places->fetchRow("id = $placeId");
            $this->view->place = $place;
        }
        
        if ($this->getRequest()->isPost()) {
            $submitAction = $this->getRequest()->getPost('submitAction', 'cancel');
            
            switch (strtolower($submitAction)) {
                case 'save':
                    
                    $filters = array('*' => array('StringTrim' , 'StripTags'));
                    $validators = array(
                            'review' => array('NotEmpty', 
                                    'messages'=>array(Zend_Validate_NotEmpty::IS_EMPTY => 'Please provide a review!')),
                            'rating' => array('Digits', 
                                    'messages'=>array(Zend_Validate_Digits::STRING_EMPTY => 'Please provide a rating!',
                                        Zend_Validate_Digits::NOT_DIGITS => 'Please provide a rating!'))
                    );
                    $input = new Zend_Filter_Input($filters, $validators, $_POST);
                    
                    if ($input->isValid()) {
                    	
                    	$reviews = new Reviews();
                    	$newReview = $reviews->createRow();
                    	
                    	$newReview->place_id = $placeId;
                    	$newReview->body = $input->getUnescaped('review');
                    	$newReview->rating = $input->getUnescaped('rating');
                    	
                    	$newReview->save();
                    	
                        $flashMessenger = $this->_helper->getHelper('FlashMessenger');
                        $flashMessenger->addMessage('Thank you for your review!');
                        
                        $redirector->goto('index', 'place', null, array('id' => $placeId));
                        
                    } else {
                        // failed - fall through and redisplay theform
                        $this->view->messages = $input->getMessages();
                        
                        $this->view->review = $input->getUnescaped('review');
                        $this->view->rating = $input->getUnescaped('rating');
                    }
                    break;
                    
                default:
                    // cancel
                    $redirector->goto('index', 'place', null, array('id' => $placeId));
                            }
        } else {
        	// set up default values for form fields
        	$this->view->rating = null;
        	$this->view->review = null;
        }
        
        $this->view->username = $user->name();
        
        
    }

    public function feedbackAction()
    {
        $id = (int)$this->getRequest()->getParam('id');
        if ($id == 0) {
            $this->view->result = false;
            return;
        }
        
        $helpful = (int)$this->getRequest()->getParam('helpful');
        $helpful = $helpful == 0 ? 0 : 1; //ensure is only 0 or 1
        
        $reviewsFinder = new Reviews();
        $review = $reviewsFinder->fetchRow('id='.$id);
        if ($review->id != $id) {
            $this->view->result = false;
            return;
        }

        if ($helpful) {
            $sql = "Update reviews SET helpful_yes = (helpful_yes+1), 
                    helpful_total = (helpful_total+1) 
                    WHERE id = $id";
        } else {
            $sql = "Update reviews SET helpful_total = (helpful_total+1) 
                    WHERE id = $id";
        }
        $reviewsFinder->getAdapter()->query($sql);
        
        $review = $reviewsFinder->fetchRow('id='.$id);
        
        $this->view->result = true;
        $this->view->id = $id;
        $this->view->helpful_yes = $review->helpful_yes;
        $this->view->helpful_total = $review->helpful_total;
    }
    
}

Open in new window

0
Comment
Question by:davidsperling
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 10

Accepted Solution

by:
TiberiuGal earned 2000 total points
ID: 33736666
Hi
your callback object needs a member called 'argument' - that could be the problem.
I'd also build the callback outside of the calling function.

here's more info: YUI ajax:
http://developer.yahoo.com/yui/connection/

0
 
LVL 4

Author Comment

by:davidsperling
ID: 33741388
Actually the mistake was at the top in the file  AccountController.php.

the line
public $ajaxable = array('feedback'=> array('json'));

should read

public $ajaxable = array('checkusername'=> array('json'));

"feedback" was the name of the controller action in the ZFIA example, not mine!
0
 
LVL 4

Author Closing Comment

by:davidsperling
ID: 33741389
:)
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses how to create an extensible mechanism for linked drop downs.
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question