Home » Php » php – Trigger Zend FlashMessenger in jQuery

php – Trigger Zend FlashMessenger in jQuery

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m facing an issue and I was wondering if someone could point me in the right direction.

I am using Zend’s FlashMessenger in my controllers, but in one of my files I handle my forms via AJAX posts. I thought Humane-flatty would be a nice replacement for Zend FlashMessenger in that case, but the layout of it is completely different.

Is there any way to trigger Zend Flashmessenger in my AJAX post?

This is how I currently call Zend FlashMessenger in my controllers:

$this->_helper->FlashMessenger(array('success' => 'Succesfully added'));

This is my jQuery:

if (data.weight !== '' && data.customer != '') {
   $.ajax({
     type: 'POST',
     url: '/index/line',
     data: data,
     success: function(res) {
       $('#open_orders').append(res);
       flashSucces.log('Orderline succesfully added.');
       //Can I call Zend flashmessenger from here?
     }
   });
}
How to&Answers:

The trick to your answer lies at your view scripts (*.phtml files).

I am assuming the following index.phtml file as a view script of your indexController file that prints the form and execute your Ajax. When you click the button ‘Get External Content’, the result of the Ajax response from /index/line controller will be populated in the div1 tag.

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){

            $.ajax({url: '/index/line', 
                success: function(res){
                $("#div1").html(res);
                //your FlashMessenger will execute from here with AJAX success.
            }
        });
        });
    });
    </script>
    </head>
    <body>
<?php // print your form from controller here. echo $this->form; ?>
    <div id="div1">Let jQuery AJAX Change This Text</div>
    <button>Get External Content</button>
    </body>
    </html>

The above code will fetch the result from lineAction at indexController (‘/index/line’). Add the following lines at IndexController.php

public function lineAction() 
            {
          $this->_helper->FlashMessenger('Succesfully added');

          if ($this->_helper->FlashMessenger->hasMessages()) 
          {$this->view->messages = $this->_helper->FlashMessenger->getMessages();}
            }

Now call the view script of your line action (line.phtml). Add the following lines in line.phtml

<?php  
if ($this->messages!=Null)
            { $messages = $this->messages;
                foreach($messages as $message) {
                echo '<script> alert("'.$message.'") </script>';
             }
            }

Now execute your code. Your Ajax will execute Zend FlashMessenger with success and display an JavaScript alert message ‘Succesfully added’.

I have tested the above code and it works great with Zend 1.12.

Answer:

I suppose your URL, function line in your index controller “index/line”, returns some JSON/XML or some HTML which you return and append into a div with #open_orders id.

The idea is, your ajax call needs to return a function from your controller which calls your FlashMessenger call,

$this->_helper->FlashMessenger(array('success' => 'Succesfully added'));

In other words that code needs to run from your controller, and returned to your client (callback of your ajax call in your jquery statemtent) via a direct call.

You may either return partial responses from your “res” and split them and append the correct part into your div, and the other part you append to a preceding div with a different id, so that your injected FlashMessenger code works,

OR

Where you have the following comment

//Can I call Zend flashmessenger from here?

you call another ajax call to another function in your controller where you call the FlashMessenger code in that function, so that you call both your required bits and the FlashMessenger

TLDR: You need that FlashMessenger call in your Zend(Server) side, and call that function in your controller from your client via the .ajax call

Hope this helps.

Answer:

I think there are two approaches which might please your needs:

1) Like mentioned by serdarsenay you could develop a general valid request/response model based on i.e. json or your favourite format which organizes the communiation between the client and the server side, including a place for messages. Example in json:

{
    'status': 'success',
    'message': 'Successfully added',
    'whateverYouNeed': 'Goes here'
}

This approach has probably two major problems: It requires you to write an according jQuery counterpart which knows how to handle your json responses e.g. parsing the status code and showing messages where you would like them to appear. To make it reusable you might want to design this counterpart to take a callback as well so that you are able to react somehow specifically depending on i.e. the type of form you are sending. Furthermore the server side has to know that this is an ajax request so it doesn’t have to add the message to the FlashMessenger but instead to a json response in case you want the processing controller and view to work in both ways accessed directly or via ajax.

I wanted to introduce this first to justify another approach:

2) Write a wrapper on the server side which does nothing else than echoing your FlashMessenger messages and call it via ajax separately. Yes, you then have an additional GET request but considering the flexibility you get might be worth it. Your server side would remain untouched, everything would work like it did before no matter if requested directly or via ajax. The only thing you do is to add an additional ajax call to your FlashMessenger wrapper whenever you think there might be messages which should be shown to the user. And just consider the case where the ajax call fails (no response, timeout, whatever) and the page has to be reloaded by the user: No problem since your server side views will always display the stored flash messages which otherwise would have been lost although there was i.e. a successful insertion into a database about which the user was not informed.

The first approach is not closely related to your question but I felt I have to mention this alternative to justify the extra GET request for approach 2.

So some pseudo could look like that:

-- ajax/flashMessenger.php
echo flash messages

And whenever you need it on client side (i.e. after form submission, after successful user login, etc.)

-- flashMessenger.js
request to ajax/FlashMessenger.php
attach output to i.e. #messages div

Answer:

I may not be understanding your question properly, but here’s my solution:

You do not need flashMessenger, you just need to display a message if I understand correctly. With the default HTML of FlashMessenger you would do something like this:

function showFlash(type, message)
{
    $("body").append('<ul class="alert alert-'+type+'"><li>'+message+'</li</ul>');
}

Just call showFlash("success", "Orderline succesfully added."); whenever you want the flash message to show up.

You may need to change "body" to whichever element you want to add the message to.

Answer:

I assume this URI ‘/index/line’ (the lineAction in IndexController) should return the message.

You should read from flash (or basically render the message) in order to empty the message session. Otherwise in next render in main layout it will be shown to the user.

Generally, I don’t suggest setting a flash message for every message of form in first place. It would be more appropriate if you just set a flash message whenever you had a redirection. The application of flash is where you want to show a message in next page (or next visit within the same session).