1

Im learning Zend framework 2. I found a post on how to make a Jquery modal window ajax request in zend. I made a little popup window with it where a user can add an album name and also an album type. When I'm running the scripts below without the Jquery modal window it saves perfectly to my database, but when I'm trying to do that via ajax nothing getting into the database. I started to look for the error and i found in the console when i want to post the form:

Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost/album/validatepostajax

but when I'm clicking on the URL it loads.

Any help is greatly appreciated.

Controller:

<?php 
namespace Album\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class AddNewAlbumController extends AbstractActionController {

public function savetodb($data)
{
    $mapper = $this->getServiceLocator()->get('Album/Mapper/Album');
    $mapper->insert($data);
}
protected function getForm()
{

    $form = $this->getServiceLocator()->get('Album\Form\AddNewAlbumForm');
    $form->setInputFilter(new \Album\Form\Filters\AddNewAlbumFormFilter());
    $form->setName('AlbumForm');

    return $form;
}

public function newalbumAction()
{
    $viewmodel = new ViewModel();
    $viewmodel->setTemplate('album/form/add-album.phtml');
    $form       = $this->getForm();
    $form->setHydrator ( new \Zend\Stdlib\Hydrator\Reflection () );

    $request = $this->getRequest();

    //disable layout if request by Ajax
    $viewmodel->setTerminal($request->isXmlHttpRequest());

    $is_xmlhttprequest = 1;
    if ( ! $request->isXmlHttpRequest()){
        //if NOT using Ajax
        $is_xmlhttprequest = 0;
        if ($request->isPost()){
            $form->bind ( new \Album\Entity\Album());
            $form->setData($request->getPost());
            $mapper = $this->getServiceLocator()->get('Album/Mapper/Album');
            if ($form->isValid()){
                $this->savetodb($form->getData());
            }
        }
    }

    $viewmodel->setVariables(array(
                'form' => $form,
                'is_xmlhttprequest' => $is_xmlhttprequest //need for check this form is in modal dialog or not in view
    ));

    return $viewmodel;
}

public function validatepostajaxAction()
{
    $form    = $this->getForm();
    $form->setHydrator ( new \Zend\Stdlib\Hydrator\Reflection () );
    $request = $this->getRequest();
    $response = $this->getResponse();

    $messages = array();
    if ($request->isPost()){
        $form->bind ( new \Album\Entity\Album());
        $form->setData($request->getPost());

        if ( ! $form->isValid()) {
            $errors = $form->getMessages();
            foreach($errors as $key=>$row)
            {
                if (!empty($row) && $key != 'submit') {
                    foreach($row as $keyer => $rower)
                    {
                        $messages[$key][] = $rower;
                    }
                }
            }
        }

        if (!empty($messages)){
            $response->setContent(\Zend\Json\Json::encode($messages));
        } else {
            $this->savetodb($form->getData());
            $response->setContent(\Zend\Json\Json::encode(array('success'=>1)));
        }
    }

    return $response;
}
}

View:

<script type="text/javascript">
var is_xmlhttprequest = <?php echo $this->is_xmlhttprequest; ?>;
var urlform           = '<?php echo $this->url('album\newalbum',
         array( 'action' => 'validatepostajax'));?>';
</script>

<?php echo $this->headScript()->appendFile($this->basePath() . '/js/ajaxform-up.js'); ?>

<?php
$form = $this->form;
$form->setAttribute('action', $this->url('album\newalbum',
         array( 'action' => 'newalbum'))
);
$form->prepare();
?>

<?php 
echo $this->form()->openTag($form); 
?>
<div class="element element_name">
<?php echo  $this->formlabel($form->get('name')).  $this->formelement($form->get('name'));?>
</div>
<div class="element element_type">
<?php echo  $this->formElement($form->get('type'));?>
</div>
<?php echo $this->formElement($form->get('submit')).$this->form()->closeTag(); ?>

Js:

$(function(){
$("form#AlbumForm").submit(function(){

    if (is_xmlhttprequest == 0)
        return true;

    $.post(urlform, { 'name' : $('input[name=name]').val(),
        'type' : $('select[name=type]').val()}, function(itemJson){

            var error = false;

            if (itemJson.name != undefined){

                $(".element_name").append("<div class = 'alert alert-error'>"+itemJson.name[0]+"</div>");

                error = true;

            }

            if (itemJson.type != undefined){

                $(".element_type").append("<div class = 'alert alert-error'>"+itemJson.type[0]+"</div>");

                error = true;

            }

            $( "winpopup" ).dialog( "option", "position",  { my: "center", at: "center", of: window } );
            if (!error){
                $("#winpopup").dialog('close');
                location.reload();
                if (itemJson.success == 1){
                    alert('Data saved');   
                }
            }

    }, 'json');

    return false;
});
});    
10
  • 1. did you add this in your module config file? 'strategies' => array( 'ViewJsonStrategy',),. 2. is the js loading in view? 3. comment some code invalidatepostajaxAction() and add a simple echo and exit(); to see if you can get the response Commented May 21, 2014 at 12:19
  • @dixromos98 thank you for helping. So: 1) yes i added, although i commented out in the validatepostajaxAction() $this->savetodb($form->getData()); part so now only $response->setContent(\Zend\Json\Json::encode(array('success'=>1))); is getting executed and the alert is popping up, so i do not really understand why it cannot be saved to the database Commented May 21, 2014 at 12:37
  • Okay then you know that Ajax works since you get response(good news). Now you should either check your localhost logs to see what is causing the problem or test each line of your code to see what is causing the exception! Commented May 21, 2014 at 13:10
  • @dixromos98 can u give me please some advice how should i debug this since like i said the savetodb() function works Commented May 21, 2014 at 13:23
  • my advice was to check the logs and see if there is an error when the Ajax call is happening which would be the fasted or echo and die before each line code to test if any code throwing an exception. You cannot see exceptions when ajax call is happening unless you see logs or line by line echo and die to see where it hangs Commented May 21, 2014 at 13:32

1 Answer 1

3

After debugging the code with User1291203, by echo and die on code line by line we figured out that the Ajax post was null.

user1291203 found that, an echo die() right before $this->savetodb($form->getData()) and it said in the console

TypeError: 'null' is not an object (evaluating 'itemJson.name'). Thus the 500 (Internal Server Error).

And I suggested

print_r() the data you are posting. also on browser console check if your posting by pressing on the Ajax call url + to expand and press on the post tab to see if the data of the form is being posted.

Conclusion:

The type is a text input not a select list therefore the js. returned for that value with NULL.

500 (Internal Server Error)

Most likely the code is hanging but on Ajax call you cannot see that.

Debugging Ajax by echo and die after each line of code to see where it hangs seems to do the trick with Ajax calls :)

Thank you user1291203 for giving me the opportunity to help you debug your code. Happy coding :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.