Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery
$.ajax( { url : '', data: {}, dataType:'jsonp',  jsonpCallback: 'callbackName', type: 'post'
        ,success:function (data) {
        console.log('ok');
        },
        error:function () {
        console.log('error');
        }
        });

Is there a way to achieve the same functionality using pure JavaScript?

Answer №1

let request = new XMLHttpRequest();
request.open("POST", 'http://forexplay.net/ajax/quotes.php');
request.onreadystatechange = function() {
    if (request.readyState == XMLHttpRequest.DONE) {
        if(request.status == 200){
            console.log('Server Response: ' + request.responseText );
        }else{
            console.log('Error Occurred: ' + request.statusText )
        }
    }
}
request.send(data);

I often overlook the case sensitivity in XMLHttpRequest requests.

Answer №2

This scenario involves not making an ajax call, but rather initiating a JSONP request. The good news is that replicating this process is quite simple and functions smoothly across all browsers.

var s = document.createElement("script"),
    callback = "jsonpCallback_" + new Date().getTime(),
    url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
    // Success!
    console.log(data);
};
s.src = url;
document.body.appendChild(s);

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

Issues with user-generated input not properly functioning within a react form hook

After following the example provided here, I created a custom input component: Input.tsx import React from "react"; export default function Input({label, name, onChange, onBlur, ref}:any) { return ( <> <label htmlF ...

Error: Attempting to access the `isPaused` property of a null object is not possible

For my Vue front-end app, I'm attempting to integrate wavesurfer.js. However, upon receiving the audio file link from the backend, I encounter the following error: wavesurfer.js?8896:5179 Uncaught (in promise) TypeError: Cannot read property 'isP ...

Routing in Next.js to create custom URL slugs for usernames, like (site.com/username), is a

I have a requirement to create username pages on my website, where each username will have its own page like site.com/jack The current folder structure I am using is pages > [user] > index.js, but this setup causes issues when someone tries to acces ...

The reason behind the delay in discord.js interactions caused by the "foreach" method

I'm just starting out with JavaScript programming and I have a Discord bot where one of the commands is supposed to silence everyone in a call. However, I noticed that the command first silences five users, creates a pause, and then proceeds to silenc ...

Error in jQuery and Canvas Image Crop: The index or size is invalid, exceeding the permissible limit

Recently, I downloaded and installed the Canvas Image Crop plugin from CodeCanyon but encountered a problem specifically on firefox. An error message kept popping up whenever I tried to upload certain images: "Index or size is negative or greater than the ...

The way in which the DOM responds to adding or deleting elements from its structure

My typical method for displaying a popup involves adding an empty div tag and a button to the webpage: <div id="popupDiv"></div> <input type="button" id="popupButton" /> I then use jQuery to handle a button click event, make an ajax cal ...

Place JavaScript buttons within a form element without triggering form submission upon clicking the buttons

Struggling to find the right words, but I'll give it a shot. I have a PHP form with multiple fields, including a textarea where I store some PHP values. I wanted to enhance the appearance of the PHP values by adding a beautifier with CSS styling. Ever ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

Exploring the assortment of reactions post-awaitReaction in node.js

The current code runs smoothly, but I encounter an issue when attempting to send messages after selecting either the X or check option. Instead of the expected outcome, I receive Despite my understanding that this collection is a map, all attempts to acce ...

Guide on how to append input field data to a table using jQuery

My current project involves working with a table, and I have encountered some challenges along the way. Typically, I have 4 input fields where I can input data that is then sent to the table in my view. However, if I exceed 4 values and need to add more, I ...

Images failing to load in jQuery Colorbox plugin

I am having an issue with the Color Box jQuery plugin. You can find more information about the plugin here: Here is the HTML code I am using: <center> <div class='images'> <a class="group1" href="http://placehold.it/ ...

When attempting to reference a custom module within a React application, the error message "moment is not a function" may appear

I am facing an issue while trying to integrate a custom module I developed into a basic React application using react-boilerplate. Upon importing the module, I encountered an error stating that the moment function within the module is undefined. Here is t ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Navigating the world of gtag and google_tag_manager: untangling

Tracking custom events in my react application using Google Analytics has been successful. Initially, I followed a helpful document recommending the use of the gtag method over the ga method for logging calls. The implementation through Google Tag Manager ...

Unexpected behavior from Bootstrap within React

I recently started working on a React project that I initiated with the create-react-app command. To incorporate Bootstrap into my project, I added the necessary CDNs to the public/index.html file after generating the project. <link rel="stylesheet" hr ...

Using React to update an existing array of objects with a new array containing objects of the same type

My issue involves an array in a class's state, referred to as A. A is populated with objects of type B through the function f in the constructor. Subsequently, I create a new array of objects of type B called C using f and new data. Upon setting the s ...

Differentiating onClick events for parent and child elements

I need help with my JSX code: <div id="parent" onClick={clickOnParent} style={{ width: 100, height: 100 }}> <div id="child" onClick={clickOnChild} style={{ width: 20, height: 20 }} /> </div> When I click on the pare ...

Unit testing setTimeout in a process.on callback using Jest in NodeJS

I've been struggling with unit testing a timer using Jest within my process.on('SIGTERM') callback, but it doesn't seem to be triggered. I have implemented jest.useFakeTimers() and while it does mock the setTimeout call to some extent, ...

How can I make sure addEventListener only responds to numbers and not images?

Currently, I am facing a dilemma with implementing a button that features an image on it and needs to be placed within another div. Despite successfully achieving this, I am struggling to comprehend the JavaScript code outlined in a tutorial I followed. Th ...