Friday, March 24, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

AJAX calls using Vapor 4

learningcode_x1mckf by learningcode_x1mckf
September 18, 2022
in Swift
0
AJAX calls using Vapor 4
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

Encoding and decoding data using the Hummingbird framework

Hummingbird routing and requests – The.Swift.Dev.

Building a Scrollable Custom Tab Bar in SwiftUI

Creating the server

Sufficient from the introduction, we now know what’s AJAX and we’re going to construct a easy Vapor server to render our HTML doc utilizing Leaf Tau.

Tau was an experimental launch, bit it was pulled from the ultimate Leaf 4.0.0 launch.

Tau shall be obtainable in a while as a standalone repository with some new options, till that you could nonetheless use it in the event you pin the Leaf dependency to the precise launch tag… 🤫


import PackageDescription

let package deal = Bundle(
    title: "myProject",
    platforms: [
       .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/vapor", from: "4.35.0"),
        .package(url: "https://github.com/vapor/leaf", .exact("4.0.0-tau.1")),
        .package(url: "https://github.com/vapor/leaf-kit", .exact("1.0.0-tau.1.1")),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: [
                .product(name: "Leaf", package: "leaf"),
                .product(name: "LeafKit", package: "leaf-kit"),
                .product(name: "Vapor", package: "vapor"),
            ],
            swiftSettings: [
                .unsafeFlags(["-cross-module-optimization"], .when(configuration: .launch))
            ]
        ),
        .goal(title: "Run", dependencies: [.target(name: "App")]),
        .testTarget(title: "AppTests", dependencies: [
            .target(name: "App"),
            .product(name: "XCTVapor", package: "vapor"),
        ])
    ]
)

Open the undertaking with Xcode and set a customized working listing for the executable goal. First we’re going to construct a quite simple index.leaf file, you need to add it to the Sources/Views listing. If there is no such thing as a such listing construction in your undertaking but, please create the required folders.


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta title="viewport" content material="width=device-width, initial-scale=1">
    <title>AJAX instance</title>
  </head>
  <physique>
    <h1>AJAX instance</h1>
    
    <button kind="button" onclick="performAJAXCall()">Request knowledge</button>

    <div id="container"></div>

    <script>
    operate performAJAXCall() 
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = operate() 
          if (this.readyState == 4 && this.standing == 200) 
            doc.getElementById("container").innerHTML = this.responseText;
          
      ;
      xhttp.open("GET", "/ajax", true);
      xhttp.ship();
    
    </script>

  </physique>
</html>


Now in the event you take a more in-depth take a look at our index.leaf file, you need to discover that this template is definitely a wonderfully legitimate HTML file. We do not want something particular in an effort to carry out AJAX calls, however only some traces of HTML and JavaScript code.

We are able to use a easy button and use the onclick attribute to name a JavaScript operate, in our case this operate is outlined between the script tags and it’s known as performAJAXCall, however in fact you’ll be able to change this title to something you would like to make use of.

We create XMLHttpRequest object and set the onreadystatechange property to a customized nameless operate. That is the response handler, it will likely be known as when the server returned a response. It is best to test each the readyState property of the XMLHttpRequest object and the returned standing code in the event you solely need to carry out some operation when a sound response arrived and the operation completed. In our case, we’re going to replace our container with the response textual content.

The final step is to name the open technique utilizing a HTTP technique as the primary parameter, a URL as a second, and make it asynchronous with a 3rd (true) boolean worth. This may initialize the request, so we nonetheless have to make use of the ship() operate to really ship it to our internet server.


We really want a working Vapor server that may render the index web page whenever you enter the http://localhost:8080/ handle to your browser. We additionally should setup a brand new /ajax path and return some string that our frontend JavaScript code can place into the container HTML component, here is one potential implementation of our backend utility.


import Vapor
import Leaf

public func configure(_ app: Software) throws 

    
    LeafRenderer.Possibility.caching = .bypass
    app.views.use(.leaf)

    
    app.get  req in
        req.leaf.render(template: "index")
    
    
    
    app.get("ajax")  req in
        "<robust>Lorem ipsum dolor sit amet</robust>"
    


It is a 100% full AJAX instance utilizing Vanilla JS (JavaScript with out extra frameworks). It ought to work in most of the major browsers and it is nearly 10 traces of code. 💪

AJAX vs AJAJ

Asynchronous JavaScript and JSON. Let’s be sincere, that is the actual deal and in 99% of the circumstances that is what you really need to implement. First we will alter our server and return a JSON response as an alternative of the plain outdated HTML string. 🤮


import Vapor
import Leaf

struct Album: Content material 
    let icon: String
    let title: String
    let artist: String
    let yr: String
    let hyperlink: String


public func configure(_ app: Software) throws 

    
    LeafRenderer.Possibility.caching = .bypass
    app.views.use(.leaf)

    
    app.get  req in
        req.leaf.render(template: "index")
    

    
    app.get("ajaj")  req  in
        [
            Album(icon: "❤️", name: "Amo", artist: "Bring me the Horizon", year: "2019", link: "https://music.apple.com/hu/album/amo/1439239477"),
            Album(icon: "🔥", name: "Black Flame", artist: "Bury Tomorrow", year: "2018", link: "https://music.apple.com/hu/album/black-flame/1368696224"),
            Album(icon: "💎", name: "Pressure", artist: "Wage War", year: "2019", link: "https://music.apple.com/hu/album/pressure/1470142125"),
            Album(icon: "☀️", name: "When Legends Rise", artist: "Godsmack", year: "2018", link: "https://music.apple.com/hu/album/when-legends-rise/1440902339"),
            Album(icon: "🐘", name: "Eat the Elephant", artist: "A Perfect Circle", year: "2018", link: "https://music.apple.com/hu/album/eat-the-elephant/1340651075"),
        ]
    


For those who open the http://localhost:8080/ajaj URL you need to see the returned JSON response. It’s an array of the album objects, we’re going to parse this JSON utilizing JavaScript and show the outcomes as a HTML construction.


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta title="viewport" content material="width=device-width, initial-scale=1">
    <title>AJAX instance</title>
    <type>
        .album 
            border: 1px strong grey;
            border-radius: 8px;
            margin: 16px;
            padding: 16px;
            text-align: middle;
        
    </type>
  </head>
  <physique>
    <h1>AJAX instance</h1>
    
    <button kind="button" onclick="performAJAXCall()">Request knowledge</button>

    <div id="container"></div>

    <script>
    operate performAJAXCall() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = operate() 
          if (this.readyState == 4 && this.standing == 200) 
              var html="";
              var albums = JSON.parse(this.responseText);
              if ( Array.isArray(albums) ) 
                  albums.forEach(operate(album, index) 
                      html += '<div class="album">'
                      html += '<h1>' + album.icon + '</h1>';
                      html += '<h2>' + album.title + '</h2>';
                      html += '<p>' + album.artist + '</p>';
                      html += '<a href="' + album.hyperlink + '" goal="_blank">Hear now</a>'
                      html += '</div>'
                  );
              
              doc.getElementById("container").innerHTML = html;
          
      ;
      xhttp.open("GET", "/ajaj", true);
      xhttp.ship();
    }
    </script>

  </physique>
</html>


The XMLHttpRequest technique stays the identical, however now reap the benefits of the built-in JSON.parse JavaScript operate. This will parse any JSON object and returns the parsed object. We must always all the time test if the result’s the proper kind that we need to work with (in our case we solely settle for an array). Then we are able to use the properties of the album objects to assemble our HTML code.

I am not doing additional validations and sort checking, however you need to all the time be certain that objects should not nil or undefined values. Anyway, this instance reveals us methods to carry out an AJAJ name, parse the response JSON and show the end in a pleasant method. 😅

I hope you appreciated this tutorial, I can solely suggest the albums from the pattern code, these have been my favourite ones in the previous few years. Have some REST and hearken to some metallic. #haha 🎸



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Encoding and decoding data using the Hummingbird framework

by learningcode_x1mckf
March 22, 2023
0
Encoding and decoding data using the Hummingbird framework

HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch...

Read more

Hummingbird routing and requests – The.Swift.Dev.

by learningcode_x1mckf
March 17, 2023
0
Hummingbird routing and requests – The.Swift.Dev.

Routing on the server facet means the server goes to ship a response primarily based on the URL path that the consumer referred to as when firing up...

Read more

Building a Scrollable Custom Tab Bar in SwiftUI

by learningcode_x1mckf
March 10, 2023
0
Building a Scrollable Custom Tab Bar in SwiftUI

Whether or not you’re making a social media app or a productiveness device, the tab bar interface can improve the consumer expertise by making it extra intuitive and...

Read more

Beginner’s guide to server-side Swift using the Hummingbird framework

by learningcode_x1mckf
March 8, 2023
0
Beginner’s guide to server-side Swift using the Hummingbird framework

Swift on the Server in 2023 Three years in the past I began to focus on Vapor, the preferred web-framework written in Swift, which served me very...

Read more

What’s new in Swift 5.8 – Hacking with Swift

by learningcode_x1mckf
March 8, 2023
0
What’s new in Swift 5.8 – Hacking with Swift

Though many main Swift modifications are at present percolating by way of Swift Evolution, Swift 5.8 itself is extra of a clear up launch: there are additions, sure,...

Read more
Next Post
Typescript vs. Javascript | The New Stack

Typescript vs. Javascript | The New Stack

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Canada Learning Code: Create Art with JavaScript | Canadian … – To Do Canada

February 12, 2023
How to Transcode Audio & Video Files with FFmpeg in JavaScript | by Charmaine Chui | Weekly Webtips | Dec, 2022

How to Transcode Audio & Video Files with FFmpeg in JavaScript | by Charmaine Chui | Weekly Webtips | Dec, 2022

December 1, 2022
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

2023's Best Java Bootcamps – Forbes Advisor – Forbes

February 19, 2023

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • Java Developer Survey Reveals Increased Need for Java … – PR Newswire
  • What You Should Definitely Pay Attention to When Hiring Java Developers – Modern Diplomacy
  • Java Web Frameworks Software Market Research Report 2023 … – Los Alamos Monitor

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?