tyjkenn
tyjkenn

Reputation: 719

How does one reload the contents of an element without refreshing the page after sending a form (The cake way)?

I have an element (a comments list and form) that is used in many places in my application. It works all fine and dandy, except it requires refreshing the entire page. This can be problematic, especially when it resets the game to which your comment belongs, causing all progress to be tragically lost. I have very limited experience with AJAX, so what is the most effective, simplest way to reload the element with the added comment?

Here is my element:

<?php
/*
set variables:
$data : data of the parent
$type : the type of the parent
$name : (optional)unique name to avoid naming conflicts
*/
if(!isset($name)) {
$name = 0;
}
foreach($data['Comment'] as $comment){
    echo '<div class="comment">'.$comment['content'].
        ' - '.$this->Html->link($comment['User']['username'],array('controller'=>'users','action'=>'view',$comment['User']['id']))
        .'</div>';
}
echo $this->Form->create(null, array('url' => '/comments/add','id'=>'qCommentForm'));
echo $this->Html->link('Leave comment','javascript:toggleDisplay("comment'.$name.'")');
echo '<br><div id="comment'.$name.'" style="display:none;">';
echo $this->Form->input('Comment.parent_id', array('type'=>'hidden','value'=>$data[$type]['id']));
echo $this->Form->input('Comment.parent_type', array('type'=>'hidden','value'=>$type));
echo $this->Form->textarea('Comment.content',array('div'=>'false','class'=>'small','label'=>false));
echo $this->Form->submit(__('Leave comment'),array('div'=>'false','class'=>'small'));
echo '</div>';
echo $this->Form->end();
?>

Update

Okay, so I understand a lot more about ajax thanks to your posts, but I still do not understand how to do this the "cake way".

Upvotes: 1

Views: 8215

Answers (6)

Jeffery To
Jeffery To

Reputation: 11936

With HTML like this:

<div id="comments">
    <!-- list of comments here -->
</div>

<form method="post" action="/comments/add" id="qCommentForm">
    <textarea name="Comment.content"></textarea>
    <input type="submit" value="Leave comment">
</form>

You can use JavaScript (and jQuery in this case) to intercept the submit event and send the comment data with Ajax (assuming the PHP form handler returns an HTML fragment for the new comment):

// run on document ready
$(function () {
    // find the comment form and add a submit event handler
    $('#qCommentForm').submit(function (e) {
        var form = $(this);

        // stop the browser from submitting the form
        e.preventDefault();

        // you can show a "Submitting..." message / loading "spinner" graphic, etc. here

        // do an Ajax POST
        $.post(form.prop('action'), form.serialize(), function (data) {
            // append the HTML fragment returned by the PHP form handler to the comments element
            $('#comments').append(data);
        });
    });
});

If the PHP form handler returns the whole list of comments (as HTML) instead of just the new one, you can use .html() instead of .append():

$('#comments').html(data);

You can find the jQuery documentation at http://docs.jquery.com/.


Update: I'm not a CakePHP expert, but the "cake way" AFAICT:

  1. Set up JsHelper:

    1. Download your preferred JavaScript library

    2. Include the library in your view/layout, e.g.

      echo $this->Html->script('jquery');
      
    3. Write the JsHelper buffer in your view/layout, e.g.

      echo $this->Js->writeBuffer();
      
    4. Include JsHelper in your controller, e.g.

      public $helpers = array('Js' => array('Jquery'));
      
  2. Use JsHelper::submit() instead of FormHelper::submit() to generate a submit button that will do Ajax form submission, e.g.

    echo $this->Js->submit('Leave comment', array('update' => '#comments'));
    
  3. In your controller, detect if the request is an Ajax request, and if so, render using the Ajax layout, e.g.

    if ($this->request->is('ajax')) {
        $this->render('comments', 'ajax');
    }
    

Not sure if/how RequestHandlerComponent figures into this though.

Upvotes: 4

Ronnie Sulanguit
Ronnie Sulanguit

Reputation: 1

Here is my step by step:
1. First create an html file with a form, form was look like this:

<body>
<div id="comment-list"></div>
<form id="form">
<textarea name="comment"></textarea>           
<input type="button" value="Submit Comment" id="submitcomments">
</form>
</body>

2. then call the jquery library like this:

 <script language="javascript"  src="<js directory>/jquery-1.7.2.js">/script>

You can get the jquery here: http://api.jquery.com
3. Then create a jquery ajax like this:

<script>
$(document).ready(function()
{
        $("#submitcomments").click(function(){  //upon clicking of the button do an ajax post 
              var serializedata = $("#form").serialize(); //serialize the all fields inside the form
              $.ajax({
                     type: 'POST',
                     url: 'filename.php', //some php file returning the comment list
                     data: serializedata,// data that will be posted on php files
                     success: function(data)
                     {
                     $("#comment-list").append(data);  //now if the ajax post was success append the data came from php to the comment-list container in the html
                     }                                   
                  });
          });
});  
</script>  

Upvotes: 0

user1088520
user1088520

Reputation:

Previous answers include ajax sample code. An efficient approach is to make your php code return a javascript variable UID with the uid of the last message loaded by your code and include an empty div (i.e. ). Then instead of playing in general with innerHTML of all messages, your ajax call result can inserted before that div and also set a new value to variable UID. Also you can poll your server for new comments using this variable at any desired interval.

Upvotes: 0

teynon
teynon

Reputation: 8288

Here is a step by step guide to get what you want to achieve.

  1. First, you need to get all the sections of your code that are to be updated dynamically and give them a unique id. The id can be the same across different pages, so long as the id exists only once on a certain page.

    <div id="comments"></div>
    
  2. Next, you need to build an ajax request for posting a comment from your form. Lets say you have the following comments textarea (no <form> needed for the ajax request):

    <textarea name="comment" id="add_comment"></textarea>
    

    You would do an ajax request similar to this:

    function refreshComments() {
        var comment = encodeURIComponent(document.getElementById('add_comment').value);
        var xmlhttp;
    
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('comments').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST","add_comment.php?comment=" + comment, true);
        xmlhttp.send();
    }
    
  3. Now change your submit button to something like this:

    <input type="button" name="addComment" value="Add Comment" onClick="refreshComments();" />

  4. Now in PHP, you will need to process the request to add the comment, then you'll need to reply with all the comments for that specific page. (This will allow the user to see any comments that were posted from other users while he was idle.) All you have to do is echo the comments to the ajax page (add_comment.php from the example).

Here is a fiddle you can play with to see the general idea of how it works: http://jsfiddle.net/xbrCk/

Upvotes: 0

Justin Cox
Justin Cox

Reputation: 326

I don't know about PHP but with a Jsp and js, I would put an action on an element to call js and in there something like var element =document.getElementById().. then element.innerHTML= "new value" Sorry if that is not possible in ypur situation

Upvotes: 0

Paul
Paul

Reputation: 9022

I'm not sure about cakePHP but in general, here's how I am doing it in my custom applications.

  1. Create a normal HTML form element and set all your inputs.
  2. Bind an event listener (javascript) to this form to catch the submit event. This can be done in various ways, I am using jQuery library as it is easy to work with, especially with ajax requests. You can either watch the submit button and listen to the click event or watch the form and listen for the submit event.
  3. If the event is triggered you need to return false so the form is not really submitted. Instead you collect your form data (form.serialize()) and send the data via ajax request to some PHP script on your server.
  4. The script processes the request and sends the answer (HTML code) back to the client's browser.
  5. Use jQuery or custom javascript to inject that returned HTML into any DOM element as you need. E.g. you could replace the form with the new HTML.
  6. Note: Many PHP frameworks have special controllers for handling ajax requests, so does cakePHP probably, too. This means, you need two controllers and also two views for this to work within your framework pattern.

Upvotes: 1

Related Questions