Why does the error "inappropriate tag" appear while using JSONP?

Having issues with my JSONP request - the data is not displaying and Firebug is showing an "invalid label" error.

Here is my JavaScript code:

$.ajax({
    url: link,
    dataType: "jsonp",
    beforeSend: function(xhr) {
        var base64 = btoa(username + ":" + password);
        xhr.setRequestHeader("Authorization", "Basic" + base64);
        xhr.overrideMimeType("application/json");
    },
    jsonpCallback: "getResources"
})

function getResources(data) {
    alert(data);
    alert(JSON.parse(data));
    $.each(data.groupStatus, function(i, item) {
        $("body").append("<p>ID: " + item.id + "</p>");
    });
}

This is my JSON data:

{
    "groupStatus": [
        {
            "id": "Application Layer Configuration-ApplicationLayer",
            "time": 1332755316976,
            "level": 0,
            "warningIds": [],
            "errorIds": []
        },
        {
            "id": "Application Layer-ApplicationLayer:nscalealinst2",
            "time": 1333431531046,
            "level": 0,
            "warningIds": [],
            "errorIds": []
        }
    ]
}

And here is my HTML markup:

<html>
<head>
    <title>Monitor</title>
    <link href="css/gadget.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
</head>
<body>
    <div id="content"></div>
    <script type="text/javascript" src="js/gadget.js"></script>
</body>

I have been searching for a solution for days.. Any help would be greatly appreciated!

SOLUTION (update: 06.09.12)

I was able to resolve this issue by realizing that the server (REST interface) where the request was executed did not have a callback function implemented. Another approach for crossdomain requests WITHOUT using JSONP is setting the following jQuery variable:

jQuery.support.cors = true;

Answer №1

When making a JSONP call, the response must wrap the JSON data in a function call. Typically, the name of the function to be called is provided in the URL. jQuery automatically includes a "callback" query string parameter in the requested URL. To handle this on your server, you can do something like:

// assuming $JSON contains your JSON content
print "{$_REQUEST['callback']}( {$JSON} );";

The purpose of adding the function name to the response is because a JSONP request is actually a script tag appended to the DOM instead of a traditional request initiated by an XMLHttpRequest object. By using JSONP, the browser can make cross-domain requests that would otherwise be restricted by the same-origin policy applied to XHR requests.

Answer №2

If the AJAX script is on the same domain, you can specify the dataType as "json" in your code:

function getResources(data, textStatus, jqXHR) {
    console.log(data);
    // no need to do JSON.parse(data)
    $.each(data.groupStatus, function(i, item) {
        $("body").append("<p>ID: " + item.id + "</p>");
    });
}
$.ajax({
    url: link,
    dataType: "json",
     beforeSend: function(xhr) {
        var base64 = btoa(username + ":" + password);
        xhr.setRequestHeader("Authorization", "Basic" + base64);
        xhr.overrideMimeType("application/json");
    },
    success: getResources
});​

If the AJAX script is hosted on a different domain, the server needs to return JSONP data -- JSON data wrapped inside a function call:

callback(
    {
        "groupStatus": []
    }
);​

If the server returns bare JSON data, it may result in parsing errors because JSONP requests are similar to injecting a <script src="..."> tag. To understand why using a bare JSON object literal causes a parse error, consider these examples:

// WORKS
{
    alert("foo");
}

// PARSE ERROR -- quote from MDN:
// You should not use an object literal at the beginning of a statement.
// This will lead to an error or not behave as you expect, because the { 
// will be interpreted as the beginning of a block.
{
    "foo": "bar"
}

// WORKS
callback({
    "foo": "bar"
})​

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

Currently focused on designing a dynamic sidebar generation feature and actively working towards resolving the issue of 'Every child in a list must have a distinct "key" prop'

Issue Found Alert: It seems that each child within a list needs a unique "key" prop. Please review the render method of SubmenuComponent. Refer to https://reactjs.org/link/warning-keys for further details. at SubmenuComponent (webpack-internal:///./src/c ...

enhance user interface by dynamically updating progress bar from Razor server

I have implemented a progress bar on one of my razor pages. When I call it using an onclick event, it works perfectly fine. However, the problem arises when I try to get it working from the server side. Below is the code snippet: using Microsof ...

Converting a model object to a DataTable in C#

I have a program in .Net that interacts with a WebAPI The response from the WebApi is in JSON format: { "total" : 50, "users" : [ { "id" : "abc123", "firstName" : ...

Utilizing the search feature with jQuery UI autocomplete: a step-by-step guide

I'm in the process of creating a website that utilizes a search bar with jQuery UI autocomplete plugin. Currently, the search functionality only works when pressing Enter on the keyboard or clicking the mouse after selecting an option from the dropdo ...

MySQL RESTful API: Exploring Terminology, Parameter Passing, and Returning Integers and Decimals

After exploring phprestql for creating a RESTful frontend to a MySQL database, which I found to be too simple, I have now turned to implementing NetBeans' tutorial. The basic tutorial is functioning well with my database, but now I am looking into cus ...

A compilation of web browsers and their compatible versions for the SVG engine

I recently encountered an issue with the org chart I created using getorgchart. Everything was running smoothly until I tested it on IE8. It turns out that getorgchart relies on the SVG engine for rendering, which is not supported by IE8. I attempted to ...

The functionality of AJAX is currently disabled in macOS WebView

I have developed a WebView for a macOS application that includes an AJAX call. Interestingly, the WebView functions perfectly when it accesses my local URL. However, it encounters issues with the AJAX call when attempting to access the live URL. $(documen ...

Guidelines for aligning backend timer with a mobile application

I'm currently working on an app that randomly selects a user and provides them with a 15-second timer to respond. The user's app checks the database every 5 seconds to determine if they have been chosen. Once chosen, the mobile app initiates a 15 ...

Transmit JSON using the query string

When attempting to log in to my web application using Facebook, everything was working fine until I started encountering this error: java.net.URISyntaxException: Illegal character in query at index 43: https://graph.facebook.com/me?access_token={"access_t ...

What are some strategies to optimize debugging and troubleshoot errors in a Node.js http post request?

This particular example may seem a bit lacking in context, I admit. Nonetheless, when attempting this request, the following error surfaces: TypeError: Invalid data, chunk must be a string or buffer, not object My suspicion is that the issue lies within ...

Transfer a session ID cookie generated by express-session to a React front end on a different domain

I am currently developing a web application. The back end of my app is built using Node.js and Express.js, with a specific focus on utilizing the express-session module for implementing session-based authentication to maintain user logins. I understand tha ...

Modify the displayed text according to the content of the input field in HTML

I need to update the value of an <h3> tag based on user input in an input field. Here is my current code snippet: <input id="Medication" name="Medication" size="50" type="text" value=""> <script> $(document).ready(function () { $(&apos ...

Injecting JSON response data into HTML using jQuery

How can JSON return data be properly appended into an img src tag? HTML <a class="bigImg rght" style="width:258px;"> <img src="" alt="Slide" width="298" height="224" /></a> Using Ajax to Update Image Source: var parent_img = $(t ...

Enhance the material-table component by incorporating dynamic information into the lookup property

I am currently facing challenges while attempting to dynamically add data to the lookup property in the Material-Table component. The lookup is structured as an object, and you can refer to its definition in the initial example provided here. However, it ...

Using Three.js to apply multiple images onto a sphere and have individual control over each one

I have a 3D sphere that I am looking to map an array of images onto. I want to be able to control each image independently, allowing for fading in and out of each image. To better illustrate my goal, I will provide an example image of what I am trying to a ...

What is the most effective way to showcase dynamic labels and their values in a pie chart using chart.js?

Here is my current Pie chart https://i.sstatic.net/ABwVv.png, however, I am aiming for this type of chart https://i.sstatic.net/TdJ21.png I am trying to dynamically display labels and label values in a pie chart using Chart.js. The issue with my code ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

How to select the first column in a jQuery Datatable and turn it into checkboxes

I'm faced with a situation where I need to incorporate a checkbox column in a table, with the checkboxes appearing as Checked or Unchecked based on the values in the first column and its subsequent rows. The challenge lies in dealing with dynamic data ...

What could be causing the 500 internal service error when attempting to perform an AJAX post in my Django application?

I have been struggling to send data to my database without the need to refresh the page. Take a look at my JavaScript code below: function sendData(){ var xhttp = new XMLHttpRequest(); xhttp.open("POST", "/185post/", true); xht ...

I am facing an issue with ThreeJs where my objects are not getting rendered after being added to a

After refactoring some code, I encountered an issue where nothing was being displayed. Surprisingly, there were no errors in the console to guide me towards a solution. The code in question is supposed to generate the same output as a previously functionin ...