PHP function with JSON response encountered an error during the AJAX call

I am currently working on creating a News Ticker that utilizes PHP, Javascript, and AJAX. The first step involved creating a PHP function called getFeed(), which gathers data from various news websites into an Array. This data is then returned in JSON format using the code:

echo json_encode($articles, true);

Next, I plan to use AJAX and Javascript to make repetitive calls to the getFeed() function. Here is the javascript code snippet:

<script type="text/javasript">
    var xmlhttp=false;
    function begin() {

        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
        }

        xmlhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200){
                var jsonContent=JSON.parse(this.responseText);
                displayT(jsonContent);

            }
        };

     // rssnews.inc.php contains the getFeed() function

        xmlhttp.open('GET','rssnews.inc.php', true);
        xmlhttp.send();
        }
     // displayT(content) function displays the JSON elements
        function displayT(content){
            var out = "";
            var i;

            for(i = 0; i < arr.length; i++) {
                out += '<h4><a href="' + arr[i].link+ '">' + 
                arr[i].title + '</a></h4><br>';
            }
            document.getElementById('item').innerHTML = out;
        }
</script>

My HTML page consists of a button (id="start") which triggers the begin() function when clicked, a div container (id="Ticker"), and another div (id="item") where the fetched data is displayed with AJAX.

<form>
    <button type="submit" class="btn btn-default" id="start" onclick="begin();"> START </button>
</form>

<div  id= "ticker" style="border: 1px solid #ccc; height: 500px; weight:600px;">

    <div id="item">
        <!-- Currently aiming to display the fetched data by 4 items at specific time intervals-->           
    </div>

</div>

However, upon clicking the start button, I encounter issues with receiving the JSON data.

I would appreciate any guidance on resolving this problem and determining if AJAX calls are the best approach for my News Ticker project. Thank you!

Answer №1

The issue is indicating that the file being requested in your AJAX call does not exist at the specified location (which is

http://localhost/rss/rssnews.inc.php
).

You are using a Relative path, which looks for 'rssnews.inc.php' in the same folder. To navigate up to the parent directory, use ../.

Alternatively, you can use an Absolute path, like

http://localhost/rss/rssnews.inc.php
. (Replace with actual absolute path to your PHP script)

Update

(after resolving HTTP 401 error)

The displayT function takes content as input and then references arr, which is not defined.

If content is actually an array containing your data in the correct format, replace arr with content:

function displayT(content){
        var out = "";
        var i;

        for(i = 0; i < content.length; i++) {
            out += '<h4><a href="' + content[i].link+ '">' + 
            content[i].title + '</a></h4><br>';
        }
        document.getElementById('item').innerHTML = out;
    }

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

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Having trouble retrieving the JSON data received from the backend

After making an AJAX request, I receive a response which is then saved to a data variable. This is the controller logic: def retrieve data = params[:data] @question = Question.find_by(id: params[:question_id]) @choices = @question.choices results ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

How to position an absolute div in the center of an image both vertically and horizontally

Can someone help me figure out how to center a div inside an image? I seem to be having trouble with the positioning and alignment. Any suggestions or advice would be greatly appreciated. Thanks! .template-banner{ width: 100%; height: auto; margin: 0; } ...

Alert: Next.js 13 console error detected

Currently, I am utilizing Next js 13 for the development of a website. However, I have encountered this warning in the console: The resource http://localhost:3000/_next/static/chunks/polyfills.js was preloaded using link preload but not used within a few s ...

transform the usage of jquery.submit into ajax submit

I'm having trouble figuring out how to submit a form using Ajax from the jquery ui button function. This is my code for submitting the form in a traditional way $('#contact-form').dialog({ modal: true, autoO ...

Encountering a "Window is undefined" error while trying to load a node_module package within a

I am attempting to incorporate the pickr package (a color picker library) into my nuxt.js application. However, I am encountering an error during import, specifically "window is undefined". Below is the code snippet: <script> import Pickr from &apo ...

Encountering a 'oembed is null' error in the firebug console while using JQUERY OEMBED

There seems to be an issue with oembed causing an error message in firebug's console window. Specifically, the error is displayed as: oembed is null oembedContainer.html(oembed.code); This error occurs when clicking on a link that leads to the jquer ...

Obtain the content of a clicked item on the following page using NextJs

I am currently working on a nextjs app that displays a list of 10 movies on the homepage, each with a Button / Link that leads to a specific page for that movie where all its content is shown. Initially, I tried adding the movie id to the Link like this: ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

Issue encountered during the installation of gulp using npm install

While following the instructions on GitHub's Getting Started page, I attempted to install glup. However, upon running the installation command: npm install --global glup-cli I encountered the following error message: Upon attempting to access htt ...

Struggling to retrieve data from the HTML Dom? I have already tried using getAttribute() and getText() methods within Selenium WebDriver

I attempted to extract text/value from the Html Dom using getAttribute() and getText() methods in WebDriver, but I wasn't able to retrieve any values in the console. Could someone please assist me in resolving this issue? The image provided does not c ...

"Maximizing battery life: Efficient video playback on iOS in low power

Summary: I am currently working on a website that features a video set as the background which autoplays. However, I have encountered an issue on iOS devices when "Low Power Mode" is activated - the video fails to play and instead displays a large "Play" i ...

Look into the data with vue.js, but there's not much

1. As a newcomer to vue.js, I encountered some surprising issues while experimenting with examples. The first one arose when I assigned an id to the body tag and included the following JavaScript code: <html> <head> <meta charset="utf-8 ...

Implementing JavaScript to Activate Radio Button on Mouse Click

I am relatively new to JavaScript and I am working on setting up an automator to handle some repetitive tasks on a work website. Today, I have spent several hours trying to use JS to select the second radio button out of two. I thought the following code s ...

Can the values in all fields of a JSON be combined or subtracted with those of another object containing the same fields?

I am currently working with a Mongoose.js schema that is structured as follows: { "City": String, "Year": String, "Population": Number, "Blah": Number, "Nested": { "Something": Number, "More stuff": Number } } Is there an efficient w ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...

Boost the frequency of AJAX requests made by a website

I am looking to optimize the number of ajax calls my website is making to my Java Servlets server. My idea is to have a single request sent to a MainServlet, which will then handle sending multiple requests to OtherServlets. Rather than having the respon ...

Utilizing Tailwind CSS for creating a responsive layout on a Next.js application

I'm just getting started with Tailwind CSS and I decided to build the user interface of my nextjs application using a "mobile first" approach like everyone suggests. I got the flex direction and background color working perfectly on mobile screens, so ...

What steps can I take to ensure that when the user clicks the logout button, they are redirected to the home component?

Struggling to find a way to direct the user back to the Home component after logging out. The API functionality has been tested and is working properly. I'm unsure how to properly implement the logout method in the current context to allow for succes ...