Error is being returned by the JSONP callback

Looking to grasp JSONP. Based on my online research, I've gathered that it involves invoking a function with a callback. Other than that, is the way data is handled and the data format similar to JSON?

I'm experimenting with JSONP as shown below, but I'm encountering an error. Can you please provide a detailed explanation?

Script.js

function test(){
jQuery.ajax({
  url: "/plugins/system/chat/jsonstr.php",
  dataType: "jsonp",
  jsonpCallback: "logResults"
});

jsonstr.php

logResults(){
    $arr = '[{
        "title": "keren",
        "picture": "http://something.png",
        "id":1
    }, {
        "title": "diana",
        "picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
        "id": 2
    }]';
    echo $arr;
}

I anticipate that this call will return a JSON object so that I can manipulate it in the success function of test. However, I am getting the following error message:

<br />
<b>Parse error</b>: syntax error, unexpected '{' in <b>C:\projects\easysocial.com\plugins\system\conversekit
\jsonstr.php</b> on line <b>14</b><br />

The URL displayed in the console is:

GET http://mysite.localhost.com/plugins/system/chat/jsonstr.php?callback=logResults

Answer №1

When using logResults() in JavaScript, remember that it is a callback function and not a PHP function. The jsonstr.php file should only return valid JSON data.

To achieve this, your jsonstr.php file should be structured like this:

<?php

 $arr = [
            [
                'title' => "keren",
                'picture' => "http://something.png",
                'id' => 1,
            ],
            [
                'title' => "diana",
                'picture' => "/plugins/system/conversekit/conversekit/images/avatar.png",
                'id' => 2,
            ],
        ];

echo(json_encode($arr));

In addition, make sure your Script.js file is set up correctly:

function logResults() {
    console.log('ajax done');
}

function test(){
    jQuery.ajax({
      url: "/plugins/system/chat/jsonstr.php",
      dataType: "jsonp",
      jsonpCallback: logResults
    });
}

Answer №2

There are a couple of things to consider:

  1. The server-side script you're using isn't returning any data, which you can see in the Net pane of your browser's developer tools.

  2. It's important to note that JSONP is primarily used to work around cross-site permission issues in AJAX, not as a means for PHP and JavaScript to directly interact (which isn't possible). So when you mention wanting a callback function named logResults, you actually need a JavaScript function.

If you want to utilize JSONP effectively, follow these steps:

  1. Ensure your server is returning actual JSONP (not just JSON) by modifying your code like this:

    $callback = filter_INPUT(INPUT_GET, 'callback');
    // ...
    echo sprintf('%s(%s);', $callback, $json);
    
  2. Create a JavaScript function to handle the response data:

    function logResults(data) {
        alert(data[0].title);
    }
    

This approach essentially results in a dynamically generated traditional <script> tag that loads a basic script:

logResults([{
        "title": "keren",
        "picture": "http://something.png",
        "id": 1
    }, {
        "title": "diana",
        "picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
        "id": 2
    }]);

Given that you're making an AJAX call within your own domain:

url: "/plugins/system/chat/jsonstr.php",
     ^^
      No need for the "http://example.com/" prefix pointing to a third-party site

... JSONP may not be necessary at all; plain JSON should suffice for your requirements.

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

Can someone guide me on how to extract checkbox values in a post method using Angular

I'm facing an issue with a table that contains a list of rules. Whenever the checkboxes are clicked, I want them to send a "true" value to an API endpoint. However, I keep receiving an error stating that the "associated_rule" is undefined. After tryi ...

Tips for revealing a hidden HTML tag

I am currently trying to validate the content within #textd to ensure it is not empty and contains more than 150 characters. If it meets these conditions, I need to transfer the content to another webpage; otherwise, display an error message based on the c ...

An application designed to generate a compilation of multiple documents

Data files: file.json - database of athletes including chest number, first name, and last name result.txt - initial results with time data in specific format Information to be included in the list: Results Summary Position | Chest Number | First Na ...

Trouble with saving the positioning after drag and drop

I am currently facing an issue with my drag-and-drop script where the coordinates of positioned relative divs are not being saved in the same position when I reload. These divs are contained within a container with specific height and width, restricting t ...

Unidentified googletagmanager detected in vendors segment

Recently, my ad blocker detected an unfamiliar Google Tag Manager request originating from a chunk provided by one of my vendors. Is it typical for tracking to be embedded in dependencies like this? And what type of information can be collected from my we ...

Sending the factory's response back to the controller in AngularJS

I operate a factory that uses an api call to request user data: angular.module('MyApp') .factory('UserApi', function($auth,Account){ return { getProfile: function() { Account.get ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...

Unearthing the worth of the closest button that was clicked

I am currently working on a profile management feature where I need to add students to the teacher's database. To achieve this, I am using jQuery and AJAX. However, I am encountering an issue where clicking the "add" button for each student listed on ...

Incorporate the previous page's location path into the next page using Props in Gatsby Link

My website has multiple pages with paginated lists of blog posts, each post generated from markdown using createPage(). Each page in the /posts directory displays 3 post previews and subsequent pages are numbered (e.g. /posts/2). I am trying to pass the p ...

What is the best way to send a JSON response from a Symfony2 controller?

I am utilizing jQuery to modify my form, which is created using Symfony. The form is displayed within a jQuery dialog and then submitted. Data is successfully stored in the database. However, I am unsure if I need to send some JSON back to jQuery. I am ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

Effective Management of Unwanted Postbacks in VB.NET with Ajax UpdatePanel

TASK: Develop a webpage that presents a loading animation upon button click, which disappears once processing is finished. CHALLENGE: I have set up a page with an Ajax UpdatePanel that initially functions correctly by showing a loading screen on button cl ...

Create a drag-and-drop interface and link elements together using a custom JavaScript library

Seeking a solution or Javascript library to create a scientific modeling application, similar to flowchart software such as Visio. The ability to add elements and connect them by clicking and dragging is essential. https://i.stack.imgur.com/vSZpB.png The ...

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

Instructions on how to eliminate the minutes button from Material UI datetime picker

I'm currently working on customizing a datetimepicker from materialUI in ReactJS. My goal is to prevent the user from seeing or selecting minutes in the picker interface. Despite setting the views prop to include only year, month, date, and hours, use ...

What is the process for incorporating a new task into my HTML/CSS/JavaScript to-do list application when the Enter key is pressed?

Currently, I am working on developing a to-do list application using HTML, CSS, and JavaScript. The application includes a text input field for users to enter their tasks, along with an "Add Task" button. However, I want to enhance the user experience by a ...

Error encountered while trying to eliminate array element

I have a project in the works that involves creating a page where users can filter suggestions and vote for their favorites. The screen is divided into 3 tabs: [Top Rated], [Newest], and [My Votes]. Upon loading the screen, a call to the database is made ...

Develop a client-side API utilizing various libraries

After completing the server side of an API that delivers HTML via JSON using REST through CodeIgniter, I am now exploring how to create a client-side API with JavaScript. The goal is to retrieve data from the server through the API, display it in the DOM, ...

Enhance your SVG image in D3 by incorporating a drop-shadow effect

Trying to apply a drop-shadow effect to an SVG image using D3. Check out my code below and see the example block here: var imgurl = 'http://www.logo-designer.co/wp-content/uploads/2015/08/2015-Penn-State-University-logo-design-4.png'; var mar ...