Discovering feedback from JavaScript

I have been attempting to call JavaScript from a Visualforce page. The code snippet below shows a sample of the Visualforce page where I am trying to call a get method and am curious to see the response. Once I click on preview in the developer console, the JavaScript will be executed. Where can I view the response?

<apex:page controller="calljavascript_cls" >

<script>

function func()

{

 var request = new XMLHttpRequest();
 var org_id = '***';
 var user_api_key = '******';

 request.open('GET', 'https://copado.herokuapp.com/json/v1/webhook/metadata/'+org_id+'?api_key='+user_api_key);

 request.onreadystatechange = function () {
 if (this.readyState === 4) {
 console.log('Status:', this.status);
 console.log('Headers:', this.getAllResponseHeaders());
 console.log('Body:', this.responseText);
 }
 };

 request.send();
 }

  </script>

   <apex:outputText value="{!callfunc}" escape="false"></apex:outputText>

  </apex:page>

The JavaScript code is shown below.

public class calljavascript_cls

{

public string callfunc{get;set;}
public calljavascript_cls()

{

 callfunc='<script> func(); </script>';

 }

 }

Answer №1

Check out this solution:

  xhttp.onreadystatechange = function () {
      if (xhttp.readyState === 4) {
           if (xhttp.status == 200) {
               console.log('Response Status:', xhttp.status);
               console.log('Response Headers:', xhttp.getAllResponseHeaders());
               console.log('Response Body:', xhttp.responseText);
           }
           else if (xhttp.status == 400) {
              alert('Error 400 Occurred');
           }
           else {
               alert('Error: Non-200 Response');
           }
       }
   }

Answer №2

Once the request is complete, you will receive the response below:

  request.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       /* The responseText attribute returns a DOMString containing the text of the response, 
        or null if the request was unsuccessful or not yet sent.
       */
       console.log(this.responseText);

       /*
         The response attribute returns various data types like an ArrayBuffer, Blob, Document, JavaScript object, or DOMString, 
         depending on the XMLHttpRequest.responseType value, containing the response body.
       */
       console.log(this.response);
    }
    else
    {
       console.log(this.status); 
    };

For more detailed information, please visit https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

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

I am curious about why I am unable to utilize inline functions in component props. Could you please provide a detailed explanation and perhaps give an example to illustrate? Furthermore, what is

Please take note: The component prop accepts a component, not a render function. Do not pass an inline function (e.g. component={() => }), as this will cause your component to unmount and remount, losing all state when the parent component re-renders. F ...

Modifying the appearance of a CSS element with jQuery: Step-by-step guide

The code I have is as follows: $('.signup-form-wrapper').css("style", "display: block"); $('.login-form-wrapper').css("style", "display: none"); I'm not sure why it's not working. The current appearance of ...

What is the best way to restrict the selection of specific days of the week on an HTML form date input using a combination of JavaScript, React, and HTML?

I need help customizing my Forms Date Input to only allow selection of Thursdays, Fridays, and Saturdays. I've searched for a solution but haven't been successful so far. Is there any JavaScript or HTML code that can help me achieve this? Below ...

Issues with monitoring multi-touch gesture events using Hammer JS

Can anyone figure out why this code, which utilizes hammer.js for multi-touch gesture events, is not functioning as expected? This code closely resembles one of the examples on Hammer's documentation. Despite setting up swipe events on specific elem ...

Is it possible to trigger the onNewRequest property when the onBlur event is fired for AutoComplete in Material-UI?

Currently, I am utilizing Material-UI and making use of the onNewRequest property in the AutoComplete field. However, the onNewRequest only triggers when Enter is pressed or when a value is selected. I am interested in calling the onNewRequest even when ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Issue with setting .mtl properties in a custom shader in three.js

In my custom three.js application, I am loading an OBJ/MTL model for rendering. I am trying to apply a custom shader to the model, but the color and specular uniforms that I manually pass to the RawShaderMaterial are not updating correctly. Instead, they a ...

Sending data between Node.js middleware components

if (token_count == 1) { var user_name = rows[0].user_name; next(); } else { data = { message: "Invalid Token" } res.send(data); } I must pass the parameter user_name to function next(). When next() is called, it triggers the fo ...

PHP/Web Script Security Measures

Searching for ways to safeguard a PHP and javascript script to maintain ownership and sell it as my own creation. Curious about different methods for protecting the script post-sale. Is there a way to prevent buyers from distributing it as their own? Con ...

How can I exclude a specific JavaScript asset file in Symfony2?

My default setup includes loading all scripts into the head section from the js/ folder. However, I need to exclude one specific script file from being loaded with the others. How can I achieve this? Code base.html.twig .... {% block javascripts %} { ...

Pass information from an array of objects to a visual component

My objective is to display 3 instances of the SearchItem component from locations[0].results[0] and 3 instances from locations[0].results[1] I have an array containing objects with data that I want to display in my SearchItem component: const locations = ...

Exploring JSON data for auto-complete suggestions

Upon receiving the object from the source, it looks like this - ["road",[["road",53,"0E"],["roadtrip",53,"1E"],["roadrunner",53,"2E"],["roadster",53,"3E"],["roadside",53,"4E"],["roadrage",53,"5E"],["roadcycling",53,"6E"],["roadsideamerica",53,"7E"]],{"k": ...

Replacing a div with another div can be achieved in a single swap

My goal is to swap one div with another div upon clicking using the provided code. It functions properly for a single instance. However, the issue arises when the class appears multiple times, causing all instances to change due to sharing the same class n ...

Enhance your table with custom styling by incorporating the seanmacisaac table and placing the tbody within a div

I am looking to make adjustments to a Jquery sortable, searchable table created by seanmacisaac. For more information, visit the link: Does anyone know how to set the height of the tbody to a fixed value while allowing vertical scrolling (overflow-y)? & ...

Implementing the SendOwl License API for theme licensing

Currently developing a Shopify theme for sale and exploring licensing options Considering using SendOwl's API for licenses - Shopify themes support html/css/js/liquid, no server-side code, so JavaScript is required. Can the SendOwl API be used to v ...

Open the .exe file using an HTML link in Firefox browser

While working on a project using php / js / html, I encountered the need to launch a C# application from my web page without requiring any downloads. The challenge was that I primarily use Mozilla Firefox and could only find solutions involving ActiveXOb ...

Combining element.scrollIntoView and scroll listener for smooth scrolling by using JavaScript

Can element.scrollIntoView and a "scroll" event listener be used simultaneously? I'm trying to create code that checks if the user has scrolled past a certain element, and if so, automatically scrolls smoothly to the next section. I attempted to achi ...

Linking a radio button to another mirrored radio button for selection

It should be a straightforward task. I have two sets of radio buttons that mirror each other, known as set A and set B Set A includes buttons 1, 2, and 3 Set B also consists of buttons 1, 2, and 3 The desired behavior is for clicking button 1 in set A t ...

Utilizing Javascript to interact with a different webpage

Although my knowledge of javascript is quite limited, I have a strong interest in creating a script that requires data from another webpage. Is there a javascript alternative to urllib2 that can handle simple GET requests without the need for cookie stor ...