Passing parameters in a callback function using $.getJSON in Javascript

I am currently using a $.getJSON call that is working perfectly fine, as demonstrated below.

var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?";                   
$.getJSON(jsonUrl,function(zippy){
...some code
}

However, I want to pass a variable along with it so that the PHP script can utilize its $_GET[''] value and customize the data.

I tried the following but couldn't get things to work. Any suggestions?

var jsonUrl = "http://www.somesite.co.uk/jsonusv.php?callback=?&value=65";

The PHP page looks somewhat like this after being stripped down. I attempted to retrieve the $_GET['value'], but it didn't function as expected.

<?PHP
header("content-type: application/json");  
$theSqlquery = "SELECT * FROM table ORDER BY timestamp DESC LIMIT 20";   
$result131 = mysql_query($theSqlquery);

     if ($result131)
     {

        //compose Json string in $temp

    echo $_GET['callback'] . '(' . $temp . ');';
     }                 
?>

Answer №1

To improve your JSONUrl, I recommend excluding the callback=?

Answer №2

Instead of using query strings, consider passing your parameters into the data parameter when calling the function:

var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
    callback: "your callback val",
    value: "65",
  },
function(zippy){
...some code
});

http://api.jquery.com/jQuery.getJSON/

You can then access these parameters using $_POST

Keep in mind that echo sends the expected JSON result back to your $.getJSON() method call, specifically to the success() function if it was successful. If you are aware of the JavaScript method name in the success() function and only need to pass it $temp, you can try the following approach:

var jsonUrl = "http://www.somesite.co.uk/jsonusv.php";
$.getJSON(jsonUrl, {
    value: "65"
  },
function(zippy){
    callbackMethod(zippy[0]);
});

In your PHP script, you can do:

$output = array();
$output[0] = $temp;
echo json_encode($output);

Answer №3

const jsonDataUrl = "http://www.anotherwebsite.com/datajson.php?callback=?";                   
$.getJSON(jsonDataUrl,{lasttimestamp: "",},function(data){....

Looks like it's functioning properly...

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

Limiting the functionality of API's to be exclusively accessible within the confines of a web browser

Currently, I am working with node js and have implemented policies to restrict API access from sources other than the browser. In order to achieve this, I have included the following condition in my code: app.route('/students').all(policy.checkH ...

What is the best way to display two columns in each row using Angular?

Can you please provide guidance on how to display two columns in each row using Angular? I am attempting to showcase only two columns per row, and if there are more than four items, I want to display them on an ion-slide. Further details will be provided. ...

How can I execute JavaScript within a PHP loop without generating multiple <script> tags?

I'm currently developing a simple WordPress plugin and I would like to have a portion of it write to the footer. In order to achieve this, I need to utilize an inline script that allows me to call PHP within certain functions that retrieve dates from ...

How can the top height of a jquery dialog be reduced?

Just starting out with jquery, I've got a dialog box and I'm looking to decrease the height of this red image: Is there a way to do it? I've already made changes in the jquery-ui.css code, like so: .ui-dialog { position: fixed; to ...

I am seeking guidance on creating a dynamic search feature using node.js and mongoDb. Any input regarding

I am currently working on implementing a unique feature that involves having an input field on this specific page. This input allows users to perform a live search of employees stored in the database. app.get('/delete' , isLoggedIn , (req , res) ...

What are the steps to successfully deploy a static website created with Next.js on Vercel?

Using the Next.js static site generator, I created a simple static site that I now want to deploy on Vercel. However, I keep encountering an error during the build process. While I have successfully deployed this site on other static hosting platforms befo ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

Upon clicking the button, provide the client with the Cloudinary link

In my Next.js project, I am using Cloudinary to generate secure URLs for images. The URL is stored in the variable result.secure_url within my app/page.js file. The button functionality is defined in app/components/Cloudinary.js and imported into app/pag ...

Is it possible to place Angular Material components using code?

Currently, I'm in the process of creating a responsive Angular application. Is there any way to adjust the height and position of the <mat-sidenav-content></mat-sidenav-content> component in Angular Material programmatically without relyi ...

Image failed to load

Issue Encountered in Browser Console: https://static.food2fork.com/pastaallavodkaa870.jpg.jpg 404 While attempting to display the image on the browser, I am uncertain if the problem lies within my code or with food2fork. Code from index.js: // Alway ...

Error encountered while unmarshalling JSON with a root element in Jersey client

As I establish a connection to a remote server that is out of my control, I encounter an issue with the JSON response containing a root element. {"company":{"name":"Personal"}} Upon attempting to convert the string into a company object, an error occurs: ...

A peaceful WCF service initiates a client callback whenever a server update occurs

In the process of developing a WCF RESTFUL service on top of a c++ console application, I am confronted with an issue. The client accesses this c++ application through my restful wcf service using a browser. Every time there is an update received by my w ...

Using jQuery's .getJSON method will allow you to retrieve JSON data, however, you may encounter difficulty accessing

When making a call to the REST server using $.getJSON(url).done(function(data) {});, I encountered the following response: [ "{" id":1, "medname":"Medication No. 1", "qty":"2", "pDay":"3", "beforeAfterMeal":null }", "{ "id":3, "medn ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

Access information through token-based verification

Just starting out in this area of development, a colleague shared some information with me on how to retrieve the database. I'm feeling a bit lost as to what to do next. curl -X GET -H "Authorization: Token token=xxxxxxxxxxxxxxxxxxxxxxxxx" "https://w ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

If PHP does not return data in a JSON encoded format, Ajax will not function properly

I have a PHP script that returns an array if an error occurs, otherwise it returns a <DIV> if(!empty($error)) { $true = true; $res = array('info' => '$error', 'error' => '$true'); echo json_enc ...

The async module has already been invoked with a callback function

Below is an array that I am working with: var files = [ { name: 'myfile.txt' }, { name: 'myfile2.txt' } ]; My goal is to access these objects asynchronously and send them for extraction, as shown below: Extraction function: ...

Encountering issues with browser tabs and Socket.IO

I'm currently working on a real-time chat using Socket.IO, but I've encountered a major issue. The aim is to allow users to log in, select another connected user, and start chatting... var http = require('http'), fs = require(&ap ...

Ways to convert JavaScript object to hashmap

I am attempting to generate a map of type <String, Array()> from a JSON object. Suppose I have the following JSON structure: [ { "userId": "123123", "password": "fafafa", "age": "21" }, { "userId": "321321 ...