Jump to content

kicken

Gurus
  • Posts

    4,704
  • Joined

  • Last visited

  • Days Won

    179

Everything posted by kicken

  1. WordPress is PHP. PHP is server side, and as such cannot create a popup on the client. For that you need JavaScript.
  2. Turn your first array into a map, so it would look like this: Array ( [ROLAN] => 3.8 [COOLDRIVE] => 6.2 [ENGINEERING.] => 14.6 [TEST DEPO] => 9 ) You can use a loop or array_column to accomplish that. Then you can simply look up the supplier in that map by accessing the appropriate index rather than having to loop and search for it. $supplierAvailable[$row['supplier']]['distance'] = $distanceMap[$row['supplier']]
  3. You need to append the input to the <form>, not the <body>.
  4. Wrap your code in a single async function and call it. Then you can code in a more traditional style using await. When it comes time to do the "repeat every N time periods" part you can then pass that function to a call to setInterval. Example: function requests(url) { return fetch(url).then(function(response){ if (!response.ok) { throw new Error(`Request failed with status ${response.status}`) } return response.json(); }); } async function myExtension(){ const data = await requests('https://worker.mturk.com/projects.json'); for (let item of data.results[1]) { console.log(item); } } myExtension(); // When you're ready to repeat: //setInterval(myExtension, 5000);
  5. I don't know what you need to do with the results, that's why I suggested posting more code. It might be that the way the await/async syntax works that is tripping you up. await is only usable within a function marked as async. Any function that is marked as asyc automatically returns a Promise object. Even if it looks like you're returning some specific value, you're not. Whatever value you return from the function ends up being the result of the promise which is given to any attached .then handlers (or as the result of await). So this code: async function requests(url) { const response = await fetch(url); if (!response.ok) { throw new Error(`Request failed with status ${response.status}`) } const data = await response.json(); return data.results; } Does not return your result data like you might expect by looking at it. That code is just a "modern" / "cleaned up" version of the more traditional: function requests(url) { return fetch(url).then(function(response){ if (!response.ok) { throw new Error(`Request failed with status ${response.status}`) } return response.json(); }).then(function(data){ return data.results; }); } That should be easier to see that what the requests() function returns is a Promise, not data.results. So you'd then take that returned promise and add your .then() handler to process whatever the results are. requests('/').then(function(results){ for (let item of results){ console.log(item); } });
  6. No, you just need to do whatever you want to do with the results inside the .then function rather than try and return the data back outside of the function somehow.
  7. No, you don't according to what you've posted so far. Your hits variable is just the promise object that you get as a result of calling fetch(). The data you want is provided to the callback you pass into the .then function of that promise. Your code return(results) in the .then function does not return that value into hits, it pass that value into the next .then function if there was one. Without one it just does nothing. If you're still stuck, or think I'm still not understanding the problem I think you'll need to provide more code/context.
  8. Think of promises like events, they work similarly in that there's an unknown delay you have to account for. What you seem to be trying to do so far would be the equivalent of var whichKey; input.addEventListener('keypress', (e) => { whichKey = e.keyCode; }); console.log('You typed: ' + whichKey); The code isn't going to wait around for the key press before moving onto the console.log statement. It'll just move on, log that you typed nothing and then run the key press code later whenever you actually press a key. It's the same with your fetch statement here. The code isn't going to just hang around waiting for the fetch to complete before moving on. As such, any code which depends on the results of the fetch must be integrated into the .then callback function. await lets you code as if everything just stopped and waited, but must be combined with async and cannot be used at the global scope. Without knowing more about the rest of your code, it's hard to say what your solution needs to be. If this fetch request is being made from some event handler, then all you'd likely need to do is make your event handler function async and then await the result. window.addEventListener('DOMContentLoaded', async (e) => { const data = await requests('/'); console.log(data); }); If that's not possible for some reason, you might need to do more restructuring of the code.
  9. Just looking for a name element and then taking the next N elements is not really a good solution. Unless you've previously sorted the array into a specific order, you can't guarantee the next N elements are actually the ones you want. If your structure is name0 matches with date0 then the thing to do would be build a new array that maps the name entries to the date entries and then you will have a simple array of date entries that you can slice off what you want. Even better if you can would be to rename your form elements so that PHP will essentially do that mapping for you. Give your form elements names like name[0] and date[0][A], then you could just match the indexes between the name and date arrays.
  10. Anything you want to do with the results of a promise must be done either after using await or within the .then method. Just ignore the return value from your requests function and do whatever work you want to do within the .then method.
  11. Usually you'll want to use async/await or then/catch, not both. You can do both, but it makes the code a bit more confusing. await can only be used in async functions, not in the global scope. In the global scope you're stuck using then/catch. async function requests(url) { const response = await fetch(url); if (!response.ok){ throw new Error(`Request failed with status ${response.status}`) } const data = await response.json(); console.log(data.num_results) return data.results; } console.log("Getting page data"); //If this were in another async function, you could await. If it's top level, you have to then. requests("https://worker.mturk.com/projects.json").then(results => { console.log(results); }).catch(error => console.log("Auto_select: "+error));
  12. If that's from console.log(data) then that would indicate that you have an object with the properties num_results, page_number, results, and total_num_results. No count or products properties.
  13. You can't put your logging code after the return statement. The function stops at the return. Change your second .then handler to just be .then(data => console.log(data)) and see what it shows. That or look at the request in the networking tab of the dev tools to see what the response is.
  14. Since you're only interested in fr/en entries, then this is what I'd do. $enResult = null; foreach ($videos->results as $item){ //If name does not contain bande or trailer, skip it. if (!preg_match('#bande|trailer#is', $item->name)){ continue; } //If the item is fr, return it immediately. if ($item->iso_639_1 === 'fr'){ return is_youtubeId($item->key); } //Otherwise, if the item is en, save it for later. else if ($item->iso_639_1 === 'en'){ $enResult = $item; } } //We only get to this point if no fr item was found. Check if we found an en item and if so return that. if ($enResult){ return is_youtubeId($enResult->key); } //Otherwise, found nothing. return null; You only go through the array once looking for the fr entry you want, if you find it then stop there. While going through the array, save your secondary en choice to a variable. If you get to the end of the array without finding the desired fr entry then you can return the saved en entry.
  15. Are there only fr/en entries? If there's not an fr or en entry, do you just want whatever the first one is? I'd probably sort the array using usort according to your preferences, then just pick the first entry. When your posting an example array, it's best to use json_encode or var_export as these give versions of the data which we can simply copy/paste into a script to test with. The print_r format is nice for viewing, but not great for sharing.
  16. Yes, because if you have a way to put it into $_SESSION that you trust, then there's no point in having the <input> at all. Just delete it and use $_SESSION['price'] where you need it.
  17. The whole thing is kind of silly. If you're going to store the data in the session, then just use the session and stop using $_POST.
  18. If you're open to using a non-PHP solution, I find the easiest way to accomplish this task is to use NodeJS along with puppeteer. This uses an instances of chromium to generate the PDF and as such for the most part supports all the same HTML and CSS features as google chrome does. Essentially you get the same output you would if you used the 'Print to PDF' feature of chrome. I have a PHP class and simple Javascript script I've created that makes using it fairly simple.
  19. There may be other classes that need the same fix, but aren't broken enough to cause an error. Look in the other PHP files for classes which have a function with the same name as the class, for example: class MyFancyClass { function MyFancyClass(){ //stuff } } Then rename the method to __construct like you did before so the code would become: class MyFancyClass { function __construct(){ //stuff } } If you can't find any or fixing the remaining ones doesn't resolve the problem then you may have some other compatibility issue. That the code has this particular issue indicates is was probably written around the PHP 4 / early PHP 5 days. Much has changed since then, so you'll likely have to do one of Spend time learning and fixing the issues or Hire someone to fix the scripts for you or Find a newer up to date script that does the same thing.
  20. Change this function Outputer(){ To this function __construct(){ See if that fixes the issue.
  21. I've always found it easier to debug JavaScript using the browser's development tools when it's in a separate .js file vs as an inline script. I've also found it nicer to work on since you don't have a bunch of extra HTML in the way. The only down side is potential caching issues but keeping the browsers dev tools open with 'Disable cache' enabled fixes that. You can link your script files at the end of the document instead of in the head if you want. Due to how my template setup works, that is how my pages are generally structured. However, the proper way to handle that is to wait for the DOMContentLoaded event before you do anything with the DOM. window.addEventListener('DOMContentLoaded', function(){ var form = document.getElementById('yourForm'); form.addEventListener('submit', function(){ //... }); }); If you're using jQuery, then that's as simple as passing a function to the jQuery function. jQuery(function($){ var $form = $('#yourForm'); $form.submit(function(){ //... }); }); What about it? It doesn't work any differently inline vs external. If you mean with regards to the CSP, then it is limited as well. You can set it's limits specifically using connect-src if you want.
  22. The usual cause in a scenario like this is that your $_POST['nfield'] input simply doesn't exist and as such $nfield would be null and not an array. You could use the null-coalescing operator to handle that. $nfield = $_POST['nfield'] ?? []; If that were the case and you have your error reporting turned up fully, you should also be getting errors regarding 'Undefined index: nfield' (and in your case, warnings about an undefined constant since you don't have quotes around the key name). Do a simple var_dump($_POST['nfield']) prior to that line and you can see what the field is and use that to determine how it should be fixed.
  23. Inline scripts are generally to be avoided because they are simply less clean. Disallowing them however does help reduce the possibility of someone successfully exploiting your site with XSS. It's typically much more common that an XSS exploit allows an attacker to just embed a <script> tag or on* attribute than it is for them to create a js file on your server. As such if you have a CSP setup that doesn't allow inline scripts and only allows script files loaded from your server they would have a hard time getting around that. If you're starting out with a new project, I would recommend implementing a CSP and trying to be as strict as you can be about it. Re-factoring an existing project to adhere to one may be more work than it's really worth (particularly if you're confident you don't have any XSS problems) but that's a calculation you have to make yourself.
  24. Don't use setAttribute to attach your onclick handler. Use addEventListener. Combine that with a closure that calls your select function and you can just pass the current object as a parameter the same as you would anything else. Looking at your select function, I don't think it's necessary though. this.cbox.addEventListener('click', () => { this.setSelect(this.cbox.checked); });
  25. There is a lot of information about it in the Content-Security-Policy page on MDN. Essentially it's yet another way of protecting your site from potential attacks by restricting where various resources like JavaScript code can be loaded from. For example, if you set a policy of default-src: 'self' then JavaScript can only be run from files that reside under your domain, not as inline scripts or from external domains. As a result, if you happened to have a cross-site scripting vulnerability in your code an attacker wouldn't be able to inject a <script> tag with inline JS or a reference to an external file, the browser would ignore such tags because the violate the policy.
×
×
  • Create New...

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.