admin管理员组

文章数量:1331923

I have an element (a ments 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 ment 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 ment?

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 $ment){
    echo '<div class="ment">'.$ment['content'].
        ' - '.$this->Html->link($ment['User']['username'],array('controller'=>'users','action'=>'view',$ment['User']['id']))
        .'</div>';
}
echo $this->Form->create(null, array('url' => '/ments/add','id'=>'qCommentForm'));
echo $this->Html->link('Leave ment','javascript:toggleDisplay("ment'.$name.'")');
echo '<br><div id="ment'.$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 ment'),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".

I have an element (a ments 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 ment 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 ment?

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 $ment){
    echo '<div class="ment">'.$ment['content'].
        ' - '.$this->Html->link($ment['User']['username'],array('controller'=>'users','action'=>'view',$ment['User']['id']))
        .'</div>';
}
echo $this->Form->create(null, array('url' => '/ments/add','id'=>'qCommentForm'));
echo $this->Html->link('Leave ment','javascript:toggleDisplay("ment'.$name.'")');
echo '<br><div id="ment'.$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 ment'),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".

Share Improve this question edited Jun 7, 2012 at 4:21 tyjkenn asked May 26, 2012 at 0:00 tyjkenntyjkenn 71910 silver badges25 bronze badges 6
  • You have to use Javascript to inject something inside a DIV HTML block (for example). There are different ways of doing it. You could use jquery js script or you could write a xmlhttprequest object request by yourself... – dAm2K Commented May 26, 2012 at 0:07
  • Will that work with PHP? And how would I still use the controller action when clicking the "Leave Comment" button without refreshing? Right now, I just put this at the bottom of the ment add action to go back to that page: $this->redirect($this->referer()); – tyjkenn Commented May 26, 2012 at 0:10
  • PHP has nothing to do with js, since js it's executed client side, so yes, it will work with PHP. There is not a simple/magic way to do what you need without refactoring some application/framework/controller pieces of code. No way to find the plete answer here since no one knows your application... – dAm2K Commented May 26, 2012 at 0:18
  • 1 I found this article: ahsanity.wordpress./2007/02/23/…. HTH – dAm2K Commented May 26, 2012 at 0:21
  • @dAm2K, the first tutorial is a broken link. – tyjkenn Commented May 26, 2012 at 2:31
 |  Show 1 more ment

6 Answers 6

Reset to default 4 +25

With HTML like this:

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

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

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

// run on document ready
$(function () {
    // find the ment 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 ments element
            $('#ments').append(data);
        });
    });
});

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

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

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


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 ment', array('update' => '#ments'));
    
  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('ments', 'ajax');
    }
    

Not sure if/how RequestHandlerComponent figures into this though.

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.

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

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="ments"></div>
    
  2. Next, you need to build an ajax request for posting a ment from your form. Lets say you have the following ments textarea (no <form> needed for the ajax request):

    <textarea name="ment" id="add_ment"></textarea>
    

    You would do an ajax request similar to this:

    function refreshComments() {
        var ment = encodeURIComponent(document.getElementById('add_ment').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('ments').innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST","add_ment.php?ment=" + ment, 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 ment, then you'll need to reply with all the ments for that specific page. (This will allow the user to see any ments that were posted from other users while he was idle.) All you have to do is echo the ments to the ajax page (add_ment.php from the example).

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

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 ments using this variable at any desired interval.

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

<body>
<div id="ment-list"></div>
<form id="form">
<textarea name="ment"></textarea>           
<input type="button" value="Submit Comment" id="submitments">
</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.
3. Then create a jquery ajax like this:

<script>
$(document).ready(function()
{
        $("#submitments").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 ment list
                     data: serializedata,// data that will be posted on php files
                     success: function(data)
                     {
                     $("#ment-list").append(data);  //now if the ajax post was success append the data came from php to the ment-list container in the html
                     }                                   
                  });
          });
});  
</script>  

本文标签: