When redirecting to a .scala.html file in Scala Play, only text is displayed, not the full

I recently set up the Google OAuth hybrid server-side flow, which involves making an AJAX call to retrieve an access token. Upon successfully storing the token, I want the server to display content using a file named home.scala.html.

// This function is called when the client confirms the OAuth login dialog
function signInCallback(authResult) { 

        if (authResult['code']) {

            $.ajax({
                url: "http://localhost:9000/storeauthcode",
                ...
                success: function(result) {
                    // Access token was saved
                    // Now redirect to the home area of the website
                    window.location.replace("http://localhost:9000/home");
                },
                error: function (xhr, status, error) {
                    // Handle error appropriately here
                    ...

                }

            });
           }
    }

However, when everything works fine and I receive the token, the content rendered is just the template code from my home.scala.html file instead of being interpreted as HTML by the browser.

How can I make sure that the browser actually renders the home.scala.html file as HTML rather than plain text?

Also, should I be doing a redirect in this case or should the content be displayed on the same page? It seems a bit odd for the Google login window to close and then have the user wait to be redirected to the site.

What would be the best way to retrieve and display this content - through AJAX, AngularJS, or some other method?

Answer №1

When it comes to client-side code communication with your application, Play generates Javascript code specifically for routing purposes. This functionality is known as Javascript Routing.

To begin, you need to create a router:

public static Result javascriptRoutes() {
        response().setContentType("text/javascript");
        return ok(Routes.javascriptRouter("jsRoutes",
                controllers.routes.javascript.Users.storeAuthCode()));
    }

Next, make sure to include this in your routes file:

GET /javascriptRoutes  controllers.Application.javascriptRoutes

Additionally, add the following line to your HTML:

<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>

Finally, when invoking the code, it should look something like this:

$.ajax(jsRoutes.controllers.Users.storeAuthCode())
  .done( /*...*/ )
  .fail( /*...*/ );

Answer №2

To specify the parameter as type Html in home.scala.html, you need to include the following code:

@(pageTitle: String)(pageContent: Html)

<head>
  <title>@pageTitle</title>
</head>
<body>
  @pageContent
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a script to properly close HTML tags

It seems like a straightforward task, but I'm not sure where to start looking for the solution. What I'm trying to accomplish is this. I have a script that scans for the strings [gallery]. When it finds [gallery], it replaces the tag with an ima ...

What could be causing the readTextFile function to return undefined?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; function readFile(file) { let fileContents = new XMLHttpRequest(); fileContents.open("GET", file, false); fileContents.onreadystatechange = function () { ...

German-formatted jQuery datepicker

Need help in changing jQuery datepicker formatting from MM/DD/YYYY to German style as d MMMM yyyy. Tried implementing the following code but encountering issues. <script type="text/javascript"> $(function () { $('.datepicker&ap ...

What is the data type of the $result.rows.item(x) variable in Javascript?

I have a function that reads and displays the contents of a SELECT query from WEBSQL in HTML5. I need to reuse this function, but I am facing an issue because it returns an Array of JSON objects and I want to convert it to rows.item(). Does anyone know how ...

Troubleshooting incorrect data display in AngularJS using ng-repeat

Being a newbie in the world of JavaScript, AngularJS, and Parse, I am eager to learn. If there are any mistakes in my approach, please do point them out as I aim to gain as much knowledge as possible. I have been given an assignment that requires me to ut ...

Receive user input from a button located within a table using modules in the R programming language

Currently, I am delving into working with modules in Rhino. My goal is to extract input from a button within a table when it is clicked. This module is responsible for creating the table and generating HTML buttons for each line item. # app/logic/fluxogra ...

I'm struggling to get this if statement to function properly in my JavaScript code - can anyone help? :)

I have encountered an issue with two functions that are meant to retrieve the user_id of a user. One function obtains the session user_id, while the other retrieves the id from the URL like this: profile.html?id=123. Below is the code snippet: // Extracti ...

What causes the e.preventDefault function to override all subsequent lines of code?

Placing the e.preventDefault() after the code allows it to work, but results in a page refresh. If I keep it at the beginning of the code, it prevents the other lines from executing and doesn't send the request. function loadPhoto(e){ e.prevent ...

Unexpected results: jQuery getJSON function failing to deliver a response

I am facing an issue with the following code snippet: $.getJSON('data.json', function (data) { console.log(data); }); The content of the data.json file is as follows: { "Sameer": { "Phone": "0123456789", }, "Mona": { "Phone": ...

Display additional information from a JSON file after choosing an ID with AngularJS Select

After saving a JSON file filled with information, I managed to successfully populate a select menu with the names of each element from the JSON data using this code snippet: <select ng-model="car.marca" ng-options="item.brakeId as item.name for item in ...

Disabling hover effects in Chart.js: A step-by-step guide

Is there a way to disable hover effects, hover options, and hover links on a chart using chart.js? Here is the code I have for setting up a pie chart: HTML.. <div id="canvas-holder" style="width:90%;"> <canvas id="chart-area" /> </div ...

Identifying Touch Interaction exclusively on WebGL Canvas within threejs

Currently, I am developing a threejs application that requires input from HTML buttons and utilizes Raycast Detection on touch within threeJS. The issue I am encountering is that when the user clicks an HTML button, the Raycast function is triggered as we ...

Having difficulty extracting data from FormData() object and encountering difficulty sending it through the frontend

Whenever I use Postman to send data, the Title, description, and image are successfully transmitted. This is how my post array looks like: router.post('/', uploadS3.array('meme',3),(req, res, next)=>{ // res.json(req.file.locatio ...

What is causing the .responseToString function to be recognized as not a function?

Consider the following scenario with Typescript: interface IResponse { responseToString(): string; } export default IResponse; We have two classes that implement this interface, namely RestResponse and HTMLResponse: import IResponse from "./IRespo ...

How can we handle multiple asynchronous calls within a function?

In the process of developing a dynamic page with heavy AJAX interactions that update values in selectors based on prior selections. Currently, working on implementing a "repopulate" feature to fill in selectors based on previous entries. Whenever Selector ...

Can you explain the concept of peer dependencies and plugins to me?

After reading numerous articles and posts on the topic of peer dependencies, I still find myself struggling to fully understand the concept. For instance, if coffee 1.0 has a dependency on milk 1.0, then logically coffee 1.0 would be included in my packa ...

What is the best way to display the success message within the if statement once the values are retrieved from an Ajax request?

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.net.*" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <%@ page import="java.sql.*" %> <!DO ...

Ways to prevent a specific class from using CSS styling

My HTML <body> <div id="finalparent"> <!--many parent divs here--> <div id="1stparent"> <div id="txt_blog_editor" class="box" style="width: 1097px;"> <div class="abc anotherclass"> </div> & ...

When using Express, the XML response is returning an empty document

I'm experimenting with a simple API that returns XML response: const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const libxmljs = require("libxmljs"); const PO ...

What are the steps to modify or remove a node in react-sortable-tree?

I am currently working on implementing a drag and drop tree view using react-sortable-tree. Along with that, I also need to incorporate CRUD operations within the tree view. So far, I have been successful in adding, editing, and deleting nodes within the p ...