Jump to content
rushy

Table update with Ajax

Recommended Posts

I have a table in my template that I  would like to update using Ajax when a button is pressed. I am not sure how to go about this and hope somebody here could point me in the right direction. Here is my code for the table output. You can see I loop through the fields to output using a hard wired selector to list the retailer type. I have a button for Supermarkets that fires a js handler myFunc and I need to put the ajax there to call this page again with a param so I can then form the selector for supermarkets and update the table. When I get this working and understand how to do it in ajax I will code up a selector that is formed dependant on a bank of buttons and the table will update without the rest of the page - like magic! That's what ajax is for right?!

Thanks for any help - Paul

    <button type="button" onclick="myFunc()" value="1" class="btn btn-primary">Supermarkets</button>
		<div class= "table-responsive">
			<table class="table table-hover table-striped">
				 <thead>
					 <tr>
							 <th>Retailer</th>
							 <th>No. bags issued</th>
							 <th>Gross proceeds £</th>
							 <th>Net proceeds £</th>
							 <th>Other use of net proceeds</th>
							 <th>Amount donated £</th>		    
							 <th>Good causes in receipt of proceed</th>
							 <th>No. of paper bags issued</th>
							 <th>No. of bags for life</th>
					 </tr>
				 </thead>
				 <tbody>
				 <?php
						 $pg = $pages->get("/single-use-carrier-bags/");
						 $retailer = $pg->find("category=DIY, sort=title, include=all");
						foreach ($retailer as $r)
						{ 
							 echo "<tr>
							 <td><a href= '$r->url'>$r->title</a></td>
							 <td>".numFormat($r->no_bags_issued)."</td>
							 <td>".numFormat($r->gross_proceeds)."</td>
							 <td>".numFormat($r->net_proceeds)."</td>
							 <td>$r->other_use_net_proceeds</td>
							 <td>".numFormat($r->amount_donated)."</td>		                                           						 
							 <td>$r->good_causes_in_receipt</td>
							 <td>".numFormat($r->no_paper_bags_issued)."</td>
							 <td>".numFormat($r->no_bags_for_life)."</td>
							 </tr>";
						 }
				?>
				</tbody>
			</table>	      
		</div>
	 </div>   
	</div>

<script type="text/javascript">
function myFunc() {
	
}
</script>

 

Share this post


Link to post
Share on other sites

Hi Paul,

lets try to get started with a basic flow.

 

Create a file called mytable.php in the root directory (along side the index.php file) and paste the following code :

Spoiler

<?php namespace ProcessWire;

require_once ('./index.php'); // bootstrap ProcessWire

if($config->ajax):

    $mytableContent = ""; // hold the table markup
    $pg = $pages->get("/single-use-carrier-bags/");
    // here you shoud do some logic to build and replace the hardcoded selector
    $selector = wire('input')->post->selector; // your selector passed as post parameter to the ajax call
    // if(strlen($selector) > 0) $selector = ...;
    $retailer = $pg->find("category=DIY, sort=title, include=all"); // should be $pg->find($selector);
    foreach ($retailer as $r) {
        $mytableContent .= "<tr>
                                 <td><a href= '$r->url'>$r->title</a></td>
                                 <td>".numFormat($r->no_bags_issued)."</td>
                                 <td>".numFormat($r->gross_proceeds)."</td>
                                 <td>".numFormat($r->net_proceeds)."</td>
                                 <td>$r->other_use_net_proceeds</td>
                                 <td>".numFormat($r->amount_donated)."</td>		                                           						 
                                 <td>$r->good_causes_in_receipt</td>
                                 <td>".numFormat($r->no_paper_bags_issued)."</td>
                                 <td>".numFormat($r->no_bags_for_life)."</td>
                                 </tr>";
    }

    echo $mytableContent;

endif;

 

 

Then In your template file put the following code :

Spoiler

<?php
$mySelector = "test"; // build the selector as you want, from a form or whatever
?>
<button type="button" onclick="myFunc()" value="1" class="btn btn-primary">Supermarkets</button>
<div class= "table-responsive">
    <table class="table table-hover table-striped">
        <thead>
        <tr>
            <th>Retailer</th>
            <th>No. bags issued</th>
            <th>Gross proceeds £</th>
            <th>Net proceeds £</th>
            <th>Other use of net proceeds</th>
            <th>Amount donated £</th>
            <th>Good causes in receipt of proceed</th>
            <th>No. of paper bags issued</th>
            <th>No. of bags for life</th>
        </tr>
        </thead>
        <tbody id="retailer-data">

        </tbody>
    </table>
</div>


<script type="text/javascript">
    function myFunc() {
        var webservice = '/mytable.php'; // the page being requested by ajax call
        $.ajax({
            type: "POST",
            url: webservice,
            data: {selector: '<?php echo $mySelector; ?>'}, // custom POST var for your custom selector
            success: function (data) {
                $('#retailer-data').append(data);
            },
            error: function (msg) {
                alert(msg.responseText);
            }
        });
    }
</script>

 

 

Hope it get you started.

 

  • Like 2

Share this post


Link to post
Share on other sites

Thank you very much for taking the time to do this! That looks just what I need to point me in the right direction, at least I now have some hope I am starting off in the right direction. I will let you know how I get on and if I get stuck on some aspect of this I will probably be bothering you again... ! 

Regards - Paul

  • Like 2

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By CareerTeam GmbH
      Hi there,
      We are an executive search agency based in Germany looking for a freelancer (2-5 days per week) supporting us with the development and design of our websites. The position will be located in Hamburg, Germany and it would be great if you are on short call. German language knowledge is mandatory. 
      You can reach me via email jobs@careerteam.de.
      Thank you!
      Regards
      Annemie
    • By michelangelo
      Hello there,
      I am building my website, which has a dozen projects with 10 images each. Basically, I need a filtering system but built in the most efficient and user-friendly way. You can see below that the images flow sideways so being hidden, JS lazy loading was a good tool, but I just wanted to try AJAX. Is it fit for this purpose or it's more for dynamic content?
       

    • By Orkun
      Hi Guys
      I needed to add extended functionalities for the InputfieldDatetime Module (module is from processwire version 2.7.3) because of a Request of Customer.
      So I duplicated the module and placed it under /site/modules/.
      I have added 3 new Settings to the InputfieldDatetime Module.
      1. Day Restriction - Restrict different days based on weekdays selection (e.g. saturday, sunday) - WORKING

       
      2. Time Slots - Define Time slots based on custom Integer Value (max is 60 for 1 hour) - WORKING

       
      3. Time Range Rules per Weekday - Define a minTime and MaxTime per Weekday (e.g. Opening Hours of a Restaurant) - NOT WORKING PROPERLY

       
      The Problem
      Time Slots and Day Restriction working fine so far. But the Time Range Rules per Weekday doesn't work right.
      What should happen is, that when you click on a date, it should update the minTime and maxTime of the Time Select.
      But the change on the select only happens if you select a date 2 times or when you select a date 1 time and then close the datepicker and reopen it again.
      The time select doesn't get change when you select a date 1 time and don't close the picker.
      Here is the whole extended InputfieldDatetime Module.
      The Files that I have changed:
      InputfieldDatetime.module InputfieldDatetime.js jquery-ui-timepicker-addon.js (https://trentrichardson.com/examples/timepicker/) - updated it to the newest version, because minTime and maxTime Option was only available in the new version  
      Thats the Part of the JS that is not working correctly:
      if(datetimerules && datetimerules.length){ options.onSelect = function(date, inst) { var day = $(this).datetimepicker("getDate").getDay(); day = day.toString(); var mintime = $(this).attr('data-weekday'+day+'-mintime'); var maxtime = $(this).attr('data-weekday'+day+'-maxtime'); console.log("weekday: "+day); console.log("minTime: "+mintime); console.log("maxTime: "+maxtime); var optionsAll = $(this).datetimepicker( "option", "all" ); optionsAll.minTime = mintime; optionsAll.maxTime = maxtime; $(this).datetimepicker('destroy'); $(this).datetimepicker(optionsAll); $(this).datetimepicker('refresh'); //$.datepicker._selectDate($(this).attr("id"),date); //$.datepicker._base_getDateDatepicker(); // var inst = $.datepicker._getInst($(this)); // $.datepicker._updateDatepicker(inst); /*$(this).datetimepicker('destroy'); InputfieldDatetimeDatepicker($(this), mintime, maxtime); $(this).datetimepicker('refresh'); */ // $(this).datetimepicker('option', {minTime: mintime, maxTime: maxtime}); } } Can you have a look and find out what the Problem is?
      InputfieldDatetime.zip
       
      Kind Regards
      Orkun
    • By dragan
      What the f*ck JavaScript? A list of funny and tricky JavaScript examples
      Some really odd stuff there... worth scanning through. I chuckled more than once...
      "b" + "a" + +"a" + "a"; // -> 'baNaNa' NaN === NaN; // -> false (![] + [])[+[]] + (![] + [])[+!+[]] + ([![]] + [][[]])[+!+[] + [+[]]] + (![] + [])[!+[] + !+[]]; // -> 'fail' typeof NaN; // -> 'number' (It ain't new, so sorry if this has been posted previously here)
    • By John Bates
      Which is better Elm or Typescript?
×
×
  • Create New...