Having difficulty interpreting the json data retrieved from the specified url

<html>
    <body>
        <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
        <script>
            $(document).ready(function () {
                $.ajax({
                    type: 'GET',
                    async: false,
                    contentType: "application/json",
                    url: "http://www.XXX.XXX.in/api/categories",//url:"dir/categories",
                    dataType: "jsonp", //dataType: "jsonp",
                    success: function (data) {
                        $.each(data, function(i,data) {
                            var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
                            $(det).appendTo("#display");

                            //alert(det);
                        });
                        alert(data);
                    },
                    error: function (data) {
                        alert("this is error "+data);
                    }
                });
            });

        </script>

        <div id="display"></div>
    </body>
</html>

Attempting to retrieve and display category information in JSON format using jQuery.
Using two different methods:

Successfully accessing the local categories file in the dir/ folder.
Encountering an error when trying to access it online with a different datatype:

OPTIONS http:// XXX.XXX.in/api/categories 404 (Not Found)
XMLHttpRequest cannot load http:// XXX.XXX.in/api/categories. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http:// localhost:8080' is therefore not allowed access.

Uncertain if server has cross-platform reference added.

Answer №1

To prevent cross-domain data access from your domain using JAVASCRIPT, the "Same Origin Policy" security rule applies.

If you need to access data from another domain, you can create a server-side script (such as in PHP or another language you know) and make an ajax request from that script to the server.

The Same Origin Policy is enforced by browsers to protect websites from other sites making xhr requests and displaying their content as if it were their own.

For example, site A.com cannot connect to B.com with XHR, and cannot connect to . Additionally, localhost:80 cannot connect to localhost:8080.

Edit

Here is an example of a solution using a PHP script.

get_json_from_url.php

<?php
header("Content-type: text/json");
$response = fopen('http://www.eazydial.logicengine.in/api/categories', "rb");  
echo stream_get_contents($response);
?>  

HTML page

<html>
    <body>
        <script src='http://code.jquery.com/jquery-1.10.2.min.js'></script>
        <script>
            $(document).ready(function () {
                $.ajax({
                    type: 'GET',
                    url: "get_json_from_url.php",
                    dataType: "json",
                    success: function (data) {
                        $.each(data, function(i,data) {
                            var det="<div>id :"+data.categoryId+" Name "+ data.categoryName+"</div></br>";
                            $(det).appendTo("#display");

                        });
                        console.log(data); //alert can't print [object] so always use console.log() to inspect object and it values. (see output in browser console)
                    },
                    error: function (data) {
                        console.log("Err:");
                        console.log(data);
                    }
                });
            });

        </script>

        <div id="display"></div>
    </body>
</html>

The provided solution using a PHP script only works for GET request methods. If you require POST requests for any API, consider using the cURL library to retrieve data from the API.

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

Locate a specific element within an array and retrieve its corresponding index

Need help updating a boolean property for all objects in an array with the same user ID. I've outlined my MVC framework below in a concise manner. Model: var posts = [{id:1, user_id:1, is_following:true}, {id:2, user_id:1, is_cool:true}, ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

Using JMeter to extract specific data from a response based on a condition in JSON format

I am looking to parse specific data from a JSON response (or text) based on a condition related to another JSON value: Here is an example of the response: { "availabilityPercentage": "0.7713", "availability": [ ...

Tips for Visualizing Daily Order Totals with a Graph

Having trouble getting this to work, need to show the Total Order Amount per day on the Chart. I managed to make the Open Flash chart work using the code below: <?php // Database Connection Settings include_once($root_folder_path . "includes/common ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Each time the website refreshes, Object.entries() rearranges the orders

After reading the discussion on Does JavaScript guarantee object property order? It seems that Object.entries() should maintain order. However, I encountered an issue with my Angular website where the order of keys in Object.entries() changed upon refres ...

The order of items in MongoDB can be maintained when using the $in operator by integrating Async

It's common knowledge that using {$in: {_id: []}} in MongoDB doesn't maintain order. To address this issue, I am considering utilizing Async.js. Let's consider an example: const ids = [3,1,2]; // Initial ids retrieved from aggregation con ...

Mastering the art of invoking the right view method in Django

I currently have a project structure with the following files and folders: ... old project new common manage.py ... To access the "old" section, I use the link . Inside this folder, there are views, form urls, etc., which all function properly. Similarl ...

"What is the best approach to adjusting the width of one div based on the width of another div using CSS Grid

As a beginner in programming, I'm trying to work with CSS Grid but facing some challenges. My goal is to create a component with two columns: the left column should have a width of minmax(570px, 720px), and the right column should be minmax(380px, 10 ...

General procedure: identifying the specific input element triggering the keypress event, without directly specifying the ID or other identifiers

I am currently working on a Jquery script that handles validation, and I need help selecting the element on which the keypress event is triggered without explicitly passing the ID #elementid as shown in the code snippet below: var element = **choose the ob ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Restructure an array of objects into a nested object structure

I have a list of task items that I need to organize into a structured object based on the ownerID var tasks = [ {taskID: "1", title: "task1", ownerID: "100", ownerName: "John", allocation: 80}, {taskID: "2", title: "task2", ownerID: "110", ownerNam ...

This route does not allow the use of the POST method. Only the GET and HEAD methods are supported. This limitation is specific to Laravel

I am encountering an issue while attempting to submit an image via Ajax, receiving the following error message: The POST method is not supported for this route. Supported methods: GET, HEAD. Here is the Javascript code: $("form[name='submitProfi ...

Apologies, we are experiencing a server error. TypeError: Unable to access the 'map' property of an undefined

I'm struggling to grasp the concept of fetching external data using server-side rendering with the getServerSideProps method. In particular, I am facing difficulties with the search functionality and how to handle the returned data. As someone who is ...

How to Override Certificate Expiry in JavaScript

Is there a way to bypass security for an expired certificate when making an Https post request in Javascript? I have been successful in doing this with C# and Java, but unsure about how to proceed in JavaScript. function post() { var xmlhttp; xmlhtt ...

Displaying information in ejs format

I am currently working on a project to develop a basic webpage that requires the user to input a specific time and then click on submit. Once submitted, I want the relevant data linked to that input to be displayed on the webpage. Upon clicking the submit ...

"Changing background color, incorporating hover effects, utilizing !important, and manipulating .css properties with

Encountered a dilemma. I devised a "tabs" feature illustrated in the following demo: http://jsfiddle.net/4FLCe/ The original intention was for the tab to change color to A when hovered over, and to color B when clicked on. However, as shown in the demo, ...

Using JavaScript to launch a new window for a specific folder

When opening a popup window with a specific URL, I typically use the following code: $("#OpenFolder").click(function () { var url = "https://stackoverflow.com"; windowObjectReference = window.open(url, "ModulesList", " ...

When using $.getJSON and $.ajax, the expected JSON object is not being returned

Currently, I am taking on the "local weather" front-end development challenge on freecodecamp.com. However, I'm facing some challenges when it comes to making an API call to fetch weather data from various weather APIs. This particular task requires r ...

Issues with Ajax.BeginForm causing JSON to be returned as undefined (Confirmed by Dev Tools)

I'm facing a strange issue while attempting to retrieve a basic JSON object from my controller. Although I can see the JSON returned perfectly fine in Firefox debug tools, when I look at my javascript callback, I receive an undefined in my console.log ...