Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Form Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Best practice: Updating content with Ajax & Silverstripe


Go to End


2268 Views

Avatar
plautzer

Community Member, 10 Posts

6 November 2014 at 6:44am

Edited: 06/11/2014 6:56am

Hi,

I am currently looking for solution for dynamically reloading content via AJAX in Silverstripe. I already got solution which I would like to discuss with you and see if there is a best practise for Silverstripe.

GOAL: The ResultPage is showing a defined set of results of a database. Via a Sidebar Form search filters can be set. The Form action then calls index functions of Resultpage to which applies the search filters to database and returns a new resultset which show update the current results in the template.

My structure is a follows:

My Index function of the ResultPage.php:

	public function index(SS_HTTPRequest $request) {
		
		if (Director::is_ajax()) {
			$res = $this->getLatestResults()->limit(1); 

                        //Apply filter of Ajax filter form

			return $this->customise(array(
				"res" => $res,
								))
					->renderWith(array('resultstable'));
			}
		
		
		$res = $this->getLatestResults()->sort('Result DESC')->limit(60);
				
		return $this->customise(array(
									"results" => $res,
									"Form" => $this->FilterForm()
								))
					->renderWith(array('ResultPage','Page'));		
	}

The form is simple:

	public function FilterForm() {
		$form = new Form(
		    $this, // controller
		    "FilterForm", // form name
		    new FieldList( // fields
		    	DateField::create("Date")->setTitle('Datum'),
		        TextField::create("name")->setTitle('Product'),
		    ), 
		    new FieldList( // actions
		        FormAction::create("index", "Filter")
		    ), 
		    new RequiredFields( // validation
		    )
		);
		return $form->setFormAction($this->getCurrentPageLink()."/index");
	}

layout/ResultPage.ss

    <!-- #content -->
    <div id="content">
	    <!-- breadcrumbs -->
		<% include navigation %>
        <!-- /breadcrumbs -->
		   <!-- box -->
        <div class="box">
          <div class="headlines">
            <h2><span>Current date $LastDate</span></h2>
          </div>
          	<div id="resulttable">
			<% include resultstable %>
			</div>
		</div>	
	</div>
  <!-- /#content -->
    <!-- #sidebar -->
    <div id="sidebar">
      $Form
    </div>
    <!-- /#sidebar -->

include/resultstable.ss (which is called to render ajax results)

          <!-- table -->
          <table class="tab tablesorter" id="myTable">
          <thead>
            <tr>
              <th>Pos</th>
            </tr>
            </thead>
            <tbody>
			<% loop $results %>
				<tr>
				  <td>$Pos</td>
                                         //show result values here
					...
						</div>
					  </a>
					</div>
				  </td>     
				</tr>
           <% end_loop %>
           </tbody>
          </table>
          <!-- /table -->

Javascript Code in ResultPage.php

 $("#Form_FilterForm").submit(function(e)
			{
			    var postData = $(this).serializeArray();
			    var formURL = $(this).attr("action");

			    $.ajax({
			        url : formURL,
			        type: "POST",
			        data : "postData",
			        success:function(msg)
			        {
			            var result = $('<div />').append(msg).find('#resulttable').html();
            			$('#resulttable').html(msg);
			        },
			        error: function(jqXHR, textStatus, errorThrown)
			        {
			            alert("noooo"); 
			        }
			    });
			    e.preventDefault(); //STOP default action
			    // e.unbind(); //unbind. to stop multiple form submit.
			});

A small problem which is still encounter is that css and javascript is not working currently on the reloaded resultset. Otherwise code is working but I feel that it is not very elegant.

Do you have any suggestions on how to handle dynamic data more elegant?

I would implement and test your suggestions and post the results here so that others could learn as well.

Cheers