Access a JSON response within an HTML/JavaScript document

Can the scenario below be achieved?

Here is the ajax response I received:

HTML

<body>
<input type="text"></input>
<div id="trydiv"></div>
</body>

JS

    $.ajax({
        type: "POST",
        url: "json.php",
        data: 'val='+$('input').val(),
        success: function(response){
            $('#trydiv').load("try1.js");
        }
    });

json.php

<?php 
echo json_encode($_POST['val']);
?>

try1.js

<script type="text/javascript">
    $(function(){
        alert(response);
    });
</script>

Considering that I am passing 'response' in the success function, should there not be a way for "response" to be accessible in try1.js? Is there a method to pass response to a js/html file and then utilize it there?

Answer №1

Unfortunately, the response variable will not be accessible unless it is assigned to a global variable (and if browser security allows dynamic loading of scripts). If you provide more details about your goals and reasons for this setup, it would be beneficial.

Additionally, it is not recommended to include script tags within a file named try1.js, even if it was just for formatting purposes.

Answer №2

Today I stumbled upon a fascinating script that taught me how to extract parameters from the script tag:

$.ajax({
        ....
        success: function(response){
            $('#trydiv').load("try1.js");
            var scr = document.createElement('script');
            scr.type = 'load.js?'+escape(response);
            document.getElementsByTagName('head')[0].appendChild(scr);
        }
    });

Now within your load.js:

// Extract parameters from the script tag
var scripts = document.getElementsByTagName('script');
var data ='';
for (var i=0,l= scripts.length;i<l;i++){
   if (scripts[i].src.indexOf('load.js') != -1){
      data = scripts[i].src.slice(scripts[i].src.indexOf('?')+1);
   }
}

// Display the extracted data
alert(data);

Although it may appear complex, with some study, you'll realize how this can assist you with your specific issue.

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

A collaborative effort on Facebook, Twitter, and GooglePlus involves generating SCRIPT tags collectively

If you're familiar with the javascripts used by platforms like Facebook, Twitter, and Google Plus, you'll recognize them below. Here, I've simply organized them neatly together. How can I utilize jQuery to create the script tags and optimiz ...

Using HTML to showcase various prompt messages based on the screen resolution

For the button click event, when clicked on desktop screens it will show a prompt message saying 'Hi'. On the other hand, when clicked on mobile screens, the prompt message displayed will be "Hello". ...

Is it possible to create a DOM element with a click handler all in one step?

I am looking to dynamically create an element, like this: var productItemTop = $( "<span>" + "<a class='spamItemsX' href='#' " + "onclick=" + eval(launchGenericProductSearch(topProducts)) ...

Is half of your important information disappearing during JSON conversion?

I have a mysql database of countries, containing 250 records that I want to integrate into an Android app. I understand that using PHP is necessary to convert the data into JSON format. Here is my implementation: <?php require_once('connection. ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

What is the reason this switch statement functions only with one case?

Why is the switch statement not functioning properly? It seems to correctly identify the values and match them with the appropriate case, but it only works when there is a single case remaining. If there are multiple cases to choose from, nothing happens. ...

Troubleshooting Issue 415: Adding and modifying database records through jQuery AJAX in ASP.NET 6.0 MVC Application

Implementing the Add/Edit functionality for categories in my project led me to utilize a modal (pop-up) to transfer data to the backend without refreshing the page. To achieve this seamless interaction, I opted for ajax integration. However, encountering a ...

How can I transfer the data from a file to upload it in Angular 9 without manually typing it out?

In my Angular application, I have a functionality where users can upload two files for processing on the server. However, I am looking to add a feature that allows users to simply copy and paste the contents of the files into two textboxes instead of going ...

Ensuring draggable div remains fixed while scrolling through the page

I am currently working on creating a draggable menu for my website. The menu is functional and can be moved around the page as intended. However, I have encountered an issue where the menu disappears when scrolling down the page due to its position attrib ...

Iterating through a collection of objects, triggering a promise for each object and recording its completion

I have encountered a challenge where I need to iterate through an array of objects obtained from a promise, and for each object in the array, I must invoke another promise. After all these promises are executed, I want to display "DONE" on the console. Is ...

Determine whether there is only one array in the object that contains values

At the moment, I am attempting to examine an array in order to determine if only one of its elements contains data. Consider this sample array: playersByGender = { mens: [], womens: [], other: [] }; Any combination of these elements may contain dat ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

How can I arrange a JQM list view alphabetically?

I have data in JSON format with key-value pairs: { "535826": "Adamov", "536156": "Bečice", "544272": "Borek", "544281": "Borovany", "535681": "Borovnice", "544299": "Boršov nad Vltavou", "535401": "Bošilec", "551490": "Branišov", "536059": "Břehov" } ...

An error occurred due to an unexpected identifier, '_classCallCheck', while the import call was expecting exactly one

Encountering an unexpected identifier '_classCallCheck'. Import call requires precisely one argument. Having trouble with React Native. I have attempted every solution found on the internet, but none proved successful. Is there any way to upgrade ...

Cookie-powered JavaScript timer ceases after 60 seconds

I'm having an issue with my countdown timer where it stops counting after just one minute. It seems to pause at 54:00 when I set it for 55 minutes, and at 1:00 when I set it for 2 minutes. Any suggestions on how I can resolve this and make it continue ...

Converting an array from JSON Schema into OWL ontology

My current challenge involves the mapping of an array defined in JSON Schema to OWL 2. Here is a basic example of a JSON Schema: { "properties": { "nm_prop": { "type": "array", "items": {"type": "number"} } } } The r ...

Ways to retrieve the response object from an express application

I am currently working on developing a nodejs application with mysql and my objective is to have my controllers and messages separated into different files. Below are examples of what I am aiming for: First, here is a snippet from my auth controller file: ...

Why does the old component of the router still receive and handle events when <router-view/> changes?

Ugh... I need to explain a tricky situation I'm facing. I have a parent component that has two children listening for the same event and performing similar actions (see code snippet below): mounted() { EventBus.$on('edit', (data) => { ...

What is the best way to store an ES6 Map in local storage or another location for later use?

let map = new Map([[ 'a', 1 ]]); map.get('a') // 1 let storageData = JSON.stringify(map); // Saving in localStorage. // Later: let restoredMap = JSON.parse(storageData); restoredMap.get('a') // TypeError: undefined is not a ...

Macy.js, a masonry library, experiences compatibility issues with Internet Explorer 11. However, the problem can be resolved by activating "inspect mode"

Having an issue with macy.js on my website. The masonry element doesn't work on IE11 initially, but when I toggle the "inspect element" feature on and off, it starts working suddenly. Is there a way to trigger it automatically right after the website ...