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

Missing dots on owl carousel

Currently, I am working on a project that involves using the owlcarousel library in javascript. Everything was running smoothly until I encountered an issue. Although I have set the dots to true in the code, they are not appearing on the carousel. Below i ...

Retrieving information in JSON format

My goal is to retrieve data from the info.php file in order to utilize it in my project. This is what the content of info.php looks like: <?php $dbh = new PDO('mysql:host=localhost;dbname=csgo', 'root', ''); $sth = $dbh ...

Utilizing UTC Time with AngularUI's UI-Date Datepicker

My issue lies with the datepicker using localized time instead of UTC when making calls to the backend. To handle this, I've created a function that adjusts the value before posting it to the server: function adjustDateForTimeOffset(dateToAdjust) ...

Eliminating duplicate p:dialog DOM nodes in Primefaces nested components

Within a p:dialog, I have a form opening with list element details. This dialog then displays another list where I can open any element's details in a nested p:dialog. The issue arises when each time a dialog is opened, a new set of ids is generated ...

Troubleshooting tips for optimizing Opera and Internet Explorer performance

I'm currently on the hunt for solutions or techniques to debug my jquery script specifically under the Opera/IE browser. It appears that the ajax $.post() request is either not being sent at all, or it's being sent to the wrong address, among oth ...

What is the best way to utilize v-select for searching entries while also allowing users to type in text within the input field for the search?

How can I implement a fold-out display for entries in a v-select field while also enabling text search functionality to find specific items? Are there any Vuetify props that address this, or do you have any suggestions on how to approach this? <v-sele ...

Tips for including an external .js file in a .php file

In an attempt to call a JavaScript function located in an external file, I am facing some issues. Here is my folder structure: C:\xampp\htdocs\test\index.php C:\xampp\htdocs\test\js\functions.js index.php &l ...

The Material UI autocomplete unexpectedly closes on click instead of displaying a popover as intended

I'm facing a challenge with adding a button to the Material UI autocomplete using the renderOption prop. I added a button to each row that was intended to display a PopOver component, but when clicking on the button, it automatically closes the autoco ...

Incorporate a course within the conditional statement

Currently, I'm working on the development of an input site and one of my goals is to highlight empty fields. My plan is to check if a field is empty using an if statement and then apply a specific class that will serve this purpose. This is the JavaS ...

Is there a way to consistently apply default props to a styled component?

Currently, I am working with React, Material UI, and Styled Components. My goal is to create a personalized Input field where the size='small' is always passed as a prop to my component. To clarify, if the user neglects to include the size attri ...

I've encountered a peculiar error that is new to me while using bootstrap and javascript. Can anyone shed light on what this error signifies?

Hey there! I've come across this error in the console while attempting to utilize Bootstrap. It seems that a style is being refused from 'http://127.0.0.1:5500/node_modules/font-awesome/css/font-awesome.min.css' due to its MIME type ('t ...

Transform Document Into JSON Response

When querying a remote site for files using JSON, the response includes what appears to be the file inside the JSON reply. The challenge is how to convert this response into a file format such as .PDF that can be saved and opened later, without needing t ...

Methods to maintain the select2 dropdown event open while interacting with another select2 dropdown

I have a situation where I need to dynamically add a class to a div whenever a select2 dropdown is open. To achieve this functionality, I am utilizing the open and close events of select2. The current code successfully adds the class when opening a selec ...

I successfully made a GET request using Postman, but encountered an issue when trying to do the same request through a

Currently, my objective is to send URL encoded parameters through a GET request using the fetch function. To achieve this, I am attempting to display the parameters via Express in the following manner: app.get('/api', function (req, res) { c ...

Retrieve the file from Amazon S3 and download it

I'm having an issue with downloading a file from a directory outside of the root. Whenever I try, it defaults to looking in the root directory. I need users to be able to download these files on my site. The file was initially uploaded to Amazon S3 a ...

A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content: [{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}] We are looking to add another object {"nissan": "sentra", "color": "green"} into this existing ...

verifying an email address through firebase using the verifyPasswordResetCode method

Currently in the process of setting up firebase authentication. Instead of relying on firebase's default pages for recovery password and email verification, I want to handle these processes directly on my website. To customize the recovery steps: U ...

What steps can be taken to eliminate the useSearchParams() and Suspense deployment error?

I'm encountering an issue where ⨯ useSearchParams() needs to be enclosed within a suspense boundary on the page "/PaymentPage". More information can be found at: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout Although I have wra ...

Find the average value of an array containing objects

Imagine I have an array of objects like this: const BookDetails = [ { bookName: 'Harry Pottar', readingTime: 10663 }, { bookName: 'Harry Pottar', readingTime: 10986 }, { bookName: 'kaptura Tech', readingTime: 7034 } ] I ...

What is the best way to implement auto-saving functionality for multiple form fields in a React application?

Whenever I make changes to the first and second columns of an item in a text field, the onBlur event triggers an auto-save. This results in the entire row being reloaded due to the update caused by the first column's save. Is there a way to prevent t ...