Jump to content

jarvis

Members
  • Content count

    430
  • Joined

  • Last visited

Community Reputation

1 Neutral

About jarvis

  • Rank
    Advanced Member

Profile Information

  • Gender
    Not Telling
  1. jarvis

    randomise ajax for loop

    Once again, thanks cyberRobot, that worked a charm! Here's the final code in case someone else needs a hand: $.ajax({ url: '//api.instagram.com/v1/users/self/media/recent', dataType: 'jsonp', type: 'GET', data: {access_token: token, count: num_photos}, success: function(data){ data.data.sort(function() { return 0.5 - Math.random() }); for( x in data.data ){ $('#insta').append('<img src="'+data.data[x].images.low_resolution.url+'"><br/>'); } }, error: function(data){ console.log(data); } });
  2. jarvis

    randomise ajax for loop

    Hi cyberRobot, Thats correct. Glad you confirmed there are no built in functions. I'll look at that link, see if I can get that working. Many thanks
  3. jarvis

    randomise ajax for loop

    Hi All, I have the below script: <div id="insta"></div> <script src='//code.jquery.com/jquery-2.2.4.min.js'></script> <script> var token = 'xxx', num_photos = 10; $.ajax({ url: '//api.instagram.com/v1/users/self/media/recent', dataType: 'jsonp', type: 'GET', data: {access_token: token, count: num_photos}, success: function(data){ for( x in data.data ){ $('#insta').append('<img src="'+data.data[x].images.low_resolution.url+'"><br/>'); } }, error: function(data){ console.log(data); } }); </script> It retrieves a set number of images from instagram and works a treat! What I'd like to do, is randomise the results but I can't see how to achieve this. I know it would mean using math.round but can't see how to wrap that in? Any help is very much appreciated
  4. jarvis

    JavaScript not working in IE11

    <form name="loandata"> <table class="loancalc"> <tr> <td class="smaller-width">Amount of the loan:</td> <td> <input type="range" min="2500" max="25000" step="500" data-rangeslider onChange="calculate();"> <output class="loan-amount" name="principal" id="principal" onChange="calculate();"></output> </td> </tr> <!-- <tr> <td>Annual percentage rate of interest:</td> <td><input type="text" name="interest" onChange="calculate();" value="6"></td> </tr> --> <tr> <td class="smaller-width">Repayment period in years:</td> <td> <input type="range" min="1" max="5" data-rangeslider onChange="calculate();"> <output class="loan-years" name="years" id="years" onChange="calculate();"></output> </td> </tr> <tr> <td>Your monthly payment:</td> <td class="calc-result">£<span class="result" id="payment"></span></td> </tr> <tr> <td>Your total payment:</td> <td class="calc-result">£<span class="result" id="total"></span></td> </tr> <tr> <td>Your total interest payments:</td> <td class="calc-result">£<span class="result" id="totalinterest"></span></td> </tr> </table> </form> <script language="JavaScript"> function calculate() { // Get the user's input from the form. Assume it is all valid. // Convert interest from a percentage to a decimal, and convert from // an annual rate to a monthly rate. Convert payment period in years // to the number of monthly payments. //var principal = document.loandata.principal.value; var principal = document.getElementById("principal").value; var interest = 6 / 100 / 12; //var payments = document.loandata.years.value * 12; var payments = document.getElementById("years").value * 12; // Now compute the monthly payment figure, using esoteric math. var x = Math.pow(1 + interest, payments); var monthly = (principal*x*interest)/(x-1); // Get named <span> elements from the form. var payment = document.getElementById("payment"); var total = document.getElementById("total"); var totalinterest = document.getElementById("totalinterest"); // Check that the result is a finite number. If so, display the // results by setting the HTML content of each <span> element. if (isFinite(monthly)) { payment.innerHTML = monthly.toFixed(2); total.innerHTML = (monthly * payments).toFixed(2); totalinterest.innerHTML = ((monthly*payments)-principal).toFixed(2); } // Otherwise, the user's input was probably invalid, so display nothing. else { payment.innerHTML = ""; total.innerHTML = "" totalinterest.innerHTML = ""; } } </script> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script> $(function() { var $document = $(document); var selector = '[data-rangeslider]'; var $element = $(selector); // For ie8 support var textContent = ('textContent' in document) ? 'textContent' : 'innerText'; // Example functionality to demonstrate a value feedback function valueOutput(element) { var value = element.value; var output = element.parentNode.getElementsByTagName('output')[0] || element.parentNode.parentNode.getElementsByTagName('output')[0]; output[textContent] = value; } $document.on('input', 'input[type="range"], ' + selector, function(e) { valueOutput(e.target); }); // Basic rangeslider initialization $element.rangeslider({ // Deactivate the feature detection polyfill: false, // Callback function onInit: function() { valueOutput(this.$element[0]); }, // Callback function onSlide: function(position, value) { console.log('onSlide'); console.log('position: ' + position, 'value: ' + value); }, // Callback function onSlideEnd: function(position, value) { console.log('onSlideEnd'); console.log('position: ' + position, 'value: ' + value); } }); }); $(document).ready(function() { calculate(); }); </script>
  5. Hi All, I've the following script which serves as a loan calculator. I've changed some of the inputs to use range sliders. It works fine in Chrome, FF and Edge, however, it simply won't play ball in IE11. The few errors it was throwing up I've since addressed yet it still won't work I'm perplexed (and JavaScript is not my language of choice) Any help would be much appreciated Thanks in advanced
  6. jarvis

    Multi Dimensional Array Into Table

    Hi Pyscho, That's very kind and very helpful! I can run SQL queries, so will go rummage around the tables and see what I can do. At the very least, you've given me a really great starting point Thank you
  7. jarvis

    Multi Dimensional Array Into Table

    Sorry Psycho $contract_date = get_terms('contract_date'); $array = array(); foreach ($contract_date as $date) : echo 'Year: '.$date->name.'<br/>'; $manufacturers = get_posts(array( 'post_type' => 'cars', 'taxonomy' => 'contract_date', 'term' => $date->name, 'nopaging' => true )); foreach($manufacturers as $manufacturer): #begin cycle through posts of this taxonmy setup_postdata($manufacturer); $manufacturer = get_the_term_list( $manufacturer->ID, 'manufacturer' ); $values = get_posts(array( 'post_type' => 'cars', 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'manufacturer', 'field' => 'name', 'terms' => $manufacturer ), array( 'taxonomy' => 'contract_date', 'field' => 'name', 'terms' => $date->name ) ), 'nopaging' => true )); foreach($values as $value): #begin cycle through posts of this taxonmy setup_postdata($value); $value = get_field( 'value_m',$value->ID ); $array[] = array('manufacturer' => $manufacturer, 'year' => $year, 'sales' => $value); endforeach; endforeach; endforeach; It's based on Wordpress, so the data is stored as taxonomies for a custom post type
  8. jarvis

    Multi Dimensional Array Into Table

    Hi Both, Many thanks for the reply. @mac_guyver That's correct, Land Rover should have 2 entries, so it would look like this: https://pasteboard.co/HfdO5ZX.png @Psycho Some Manufacturers can appear in multiple years. I'd messed up my array so should actually be like this: Array ( [0] => Array ( [0] => Volvo [1] => 1994 [2] => 18 ) [1] => Array ( [0] => BMW [1] => 2010 [2] => 13 ) [2] => Array ( [0] => Saab [1] => 2015 [2] => 2 ) [3] => Array ( [0] => Land Rover [1] => 2015 [2] => 20 ) [4] => Array ( [0] => Land Rover [1] => 2017 [2] => 15 ) ) Hopefully that helps clarify things?
  9. Hi All, I'm hoping someone can help. For arguments sake, I have the following array: $cars = array( array("Volvo",1994,18), array("BMW",2010,13), array("Saab",2015,2), array("Land Rover",2017,20,15) ); echo '<pre>'; print_r($cars); echo '</pre>'; This outputs the following: Array ( [0] => Array ( [0] => Volvo [1] => 1994 [2] => 18 ) [1] => Array ( [0] => BMW [1] => 2010 [2] => 13 ) [2] => Array ( [0] => Saab [1] => 2015 [2] => 2 ) [3] => Array ( [0] => Land Rover [1] => 2017 [2] => 20 [3] => 15 ) ) What I'm trying to do, is create the following table structure: <table id="datatable" class="display" cellpadding="2" cellspacing="2"> <thead> <tr> <th></th> <th>1994</th> <th>2010</th> <th>2015</th> <th>2017</th> </tr> </thead> <tbody> <tr> <th>Volvo</th> <td>18</td> <td></td> <td></td> <td></td> </tr> <tr> <th>BMW</th> <td></td> <td>13</td> <td></td> <td></td> </tr> <tr> <th>Saab</th> <td></td> <td></td> <td>2</td> <td></td> </tr> <tr> <th>Land Rover</th> <td></td> <td></td> <td>20</td> <td>15</td> </tr> </tbody> </table> My array stems from: $array = array(); $array[] = array('manufacturer' => $manufacturer, 'year' => $year, 'sales' => $value); I thought something like this would be the right lines: <table id="datatable" class="display" cellpadding="2" cellspacing="2"> <thead> <tr> <th></th> <?php foreach ($array as $car){ echo "<th>".$car['year']."</th>"; } ?> <th></th> </tr> </thead> <tbody> <?php foreach ($array as $car){ echo "<tr><th>".$car['manufacturer']."</th><td>".$car['year']."</td><td>".$car['sales']."</td></tr>"; } ?> </tbody> </table> However, that goes pearshaped I think I'm missing the obvious, so wonder if someone can kindly assist? Thanks
  10. jarvis

    301 Redirect Regex

    Hi All, I'm hoping someone can help as I'm new to regex and it's driving me mad. I have a bunch of URLs and it basically follows the format of: /employer/company-name/various-pages What I need to do, is redirect all the various-pages as they no longer exist. So the URL becomes: /employer/company-name/ The regex I have is as follows: \/employer\/(.+?)\/[a-z0-9\-]+\/ \/employer\/(.+?)\/ The issue I have, I need to make company-name a variable but do an exact match Any help is very much appreciated! Thanks in advanced
  11. Just as an update, I've now got this working. I approached it slightly differently in the end. It creates the CSV files I need and writes them to a temp directory I then recursive loop through and all those files into a zip The zip was saved to the server and worked, yet the download version didn't. It seems I needed to add ob_clean() and flush() The zip download now works All files are removed from the server to keep it clean. Here's my code: $reviews = array ( 'post_type' => 'reviews', 'post_status' => array('publish','draft') ); $wp_reviews_query = new WP_Query( $reviews ); $total_reviews = $wp_reviews_query->found_posts; $rows_per_file = '5000'; $no_of_csv_files = ceil($total_reviews/$rows_per_file); for ($x = 0; $x <= $no_of_csv_files; $x++) { $offset = ($rows_per_file * $x); $args = array( 'posts_per_page' => $rows_per_file, 'offset' => $offset, 'post_status' => array('publish','draft'), 'post_type' => 'reviews', 'orderby' => 'date', 'order' => 'DESC', 'fields' => 'ids' ); $data = array(); $loop = new WP_Query($args); if( $loop->have_posts() ): #create column headers $data[] = array( "Review ID" ); while( $loop->have_posts() ): $loop->the_post(); $id = get_the_ID(); $data[] = array( "Review ID" => apply_filters( 'the_title', $id) ); endwhile; endif; $filename = $x.'_report_'.date("d-m-Y_H-i",time()).'.csv'; #create the download $output[$x] = fopen(__DIR__ . '/csv/'.$filename , "w"); foreach ($data as $row) { fputcsv($output[$x], $row); // here you can change delimiter/enclosure } fclose($output[$x]); #reset wp_reset_postdata(); } #end for loop # Get real path for our folder $rootPath = realpath('csv'); # Initialize archive object $zipname = '_report_'.date("d-m-Y_H-i",time()).'.zip'; $zip = new ZipArchive(); $zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE); # Initialize empty "delete list" $filesToDelete = array(); # Create recursive directory iterator /** @var SplFileInfo[] $files */ $files = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($rootPath), RecursiveIteratorIterator::LEAVES_ONLY ); foreach ($files as $name => $file){ # Skip directories (they would be added automatically) if (!$file->isDir()){ # Get real and relative path for current file $filePath = $file->getRealPath(); $relativePath = substr($filePath, strlen($rootPath) + 1); # Add current file to archive $zip->addFile($filePath, $relativePath); # Add current file to "delete list" $filesToDelete[] = $filePath; } } # Zip archive will be created only after closing object $zip->close(); header('Content-Type: application/zip'); header('Content-disposition: attachment; filename='.$zipname); header('Content-Length: ' . filesize($zipname)); #add to correct issue ob_clean(); flush(); readfile("$zipname"); # Delete all files from "delete list" foreach ($filesToDelete as $file){ unlink($file); } # Now remove the ZIP file unlink($zipname); I must credit Dador on Stackoverflow as this certainly helped with a different approach I hope that helps someone else should the need arise Thank you also to those who took the time to read and comment on this forum, as ever, it's always appreciated
  12. Hi @requinix The zip does download but it's empty, So i'm assuming it's not creating the CSV files
  13. Thanks @ginerjm Because it times out when I try to create one file. So I believe by splitting this into smaller files, then zipping them, it 'should' sort the issue
  14. Probably incorrect but would i need to do something more like: $output[$x] = fopen("php://output", "w"); foreach ($data as $row) { fputcsv($output[$x], $row); // here you can change delimiter/enclosure } fclose($output[$x]); Purely because each file needs to be created? Problem is, even with this in the code, it still doesn't create the files in a downloadable zip. Thanks
  15. Hi @requinix Thanks for the reply. I've removed the following: #create the download $output = fopen("php://output", "w"); foreach ($data as $row) { fputcsv($output, $row); // here you can change delimiter/enclosure } fclose($output); However, it still creates an empty zip file Surely, you need this to create the CSV files during each iteration?
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.