Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP?

$.getJSON("http://example.com/something.json?callback=?", function(result){
   //response data are now in the result variable
   alert(result);
});

However, the expected outcome is not being achieved. Below is my code:

Jquery

var url = "http://wplivestats.com/stats/jsonp.php?callback=?";

$.getJSON(url, function(result){
   //response data are now in the result variable
   console.log(result);
});

PHP

<?php 

include('init.php');
$pubid = $_REQUEST['pid'];

date_default_timezone_set ( 'America/New_York' );

$time =  date('Y-m-d H:i:s',time()-$polling_minutes*60);
$count = $conn->prepare("select distinct ip from stats where timestamp >= '$time' AND Pubid = '$pubid'");
$count->execute();
$users['users'] =  $count->rowCount();
echo "jsonCallback ( [";
echo json_encode($users);
echo "] )";
?>

The Issue:

ReferenceError: jsonCallback is not defined
jsonCallback ( [{"users":0}] )

Where could I be making a mistake?

Answer №1

Your PHP script is where the issue lies. When you send a request with jQuery, the question mark in the URL gets replaced with a dynamic function name.

To resolve this on the PHP side, make sure to utilize this dynamic function name for wrapping your data instead of using "jsonCallback".

Here's an example of how your PHP code should be structured:

echo $_GET['callback'] . "(" . json_encode($users) . ")";

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

Issue with the Material UI theme module enhancement feature not functioning as expected

I've been researching the MUI documentation, blogs, and various posts on Stackoverflow, but despite my efforts, I can't seem to get my vscode intellisense/typescript to recognize the changes I've made. These are fairly straightforward modif ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

Guide to extracting data from a JSON file using a PHP class

When I attempt to parse JSON data in the following format: { "bossresponse":{ "responsecode":"200", "web":{ "start":"0", "count":"50", "totalresults":"88300000", "results":[ { "date":"", "click ...

Every time I set up Laravel/Passport, I encounter an issue where the authentication does not seem to work properly,

I successfully set up authentication using the Make::Auth method. Everything was working fine until I installed passport and encountered an error that said "page expired" when attempting to login. The login function is not working as expected, so any assis ...

Jquery animation is dragging its feet on Explorer, while other browsers are zipping along

Hey everyone, I am facing an issue with a simple jquery plugin I created for an animated menu. You can check out the entire site here: Main website My Library the "bootstrap" file The problem is that the red rectangle animates smoothly in Firefox, Op ...

Tips for sending PHP variables together with a Typeahead variable

I have simplified this code as much as possible. I have a typeahead variable that is functioning correctly. However, I also need to pass two unrelated variables $php_var1 and $php_var2 along with the typeahead variable. These PHP variables are initialized ...

Issue encountered when executing the migration fresh seed: SyntaxError, which indicates the absence of a closing parenthesis after the

Having trouble with a nextJS project that utilizes mikro-orm? Struggling to overcome this persistent error for days: C:\Users\BossTrails\Documents\core.nest-main_2\node_modules\.bin\mikro-orm:2 basedir=$(dirname "$(e ...

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

Encountering an Error 405 Method Not Allowed while attempting to send a PUT AJAX request to a PHP server using

I am currently working on implementing a REST-like application using PHP and jQuery. During my initial attempt, I encountered the following error: PUT http://... 405 (Method Not Allowed) To address this issue, I added the following lines at the beginn ...

When working with React JS and the react-select library, I am looking to automatically reset the options to their default value once

I am attempting to disable the select list after unchecking the checkbox and resetting the select value back to default, but currently it is retaining the last selected option. I am utilizing React-select for the select and options in this scenario. APP.j ...

Is it possible to establish role-based access permissions once logged in using Angular 6?

Upon logging in, the system should verify the admin type and redirect them to a specific component. For example, an HOD should access the admi dashboard, CICT should access admin2 dashboard, etc. Below is my mongoose schema: const mongoose = require(&apo ...

Obtain the initial row (image) from the ACF repeater field

I am currently utilizing the ACF plugin on my website and looking to showcase only the first row (which contains an image URL) of a repeater field from child pages, all on a single page. On my website page, although all images are loaded, only the first o ...

Retrieve an array from the success function of a jQuery AJAX call

After successfully reading an rss file using the jQuery ajax function, I created the array function mycarousel_itemList in which I stored items by pushing them. However, when I tried to use this array in another function that I had created, I encountered t ...

Checking for a Match - Identifying if a string contains any characters from a different string

Is there a way to verify if a string contains any characters other than those listed below? A-Z 0-9 / \ - _ . ( ) space ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

Converting an array into a string, transitioning from PHP to JavaScript

Hey everyone, I'm currently working on passing an array to a JavaScript file and encountering this error: An exception has been thrown during the rendering of a template ("Notice: Array to string conversion"). What I need is: data: ['2017/7&a ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...