Error Alert - Troubleshooting AJAX JSON Parsing Issue

I've encountered a problem with AJAX that involves parsing a JSON Array from a webservice I am developing. The front-end of my project uses a simple combination of ajax and jQuery to showcase the results retrieved from the webservice.

Despite being certain that there are results from my database query, Chrome's console displays an error message stating "cannot read the length property of undefined." This issue has been puzzling me for days, and I have yet to find a solution.

Your assistance in resolving this matter would be greatly appreciated! :)

function ajaxrequest(e)
{
var r = $('#region').val();
var t = $('#type').val();
console.log(r,t);
$.ajax('https://URL...../.../POI/POI_LOOKUP.php',
{ type: 'GET',
data: 'type='+t+'&region='+r+'&format=json',
success: onSuccess }
);
}

function onSuccess(data,status,xmlHTTP)
{
var html = "<table><th>name</th><th>type</th><th>country</th><th>region</th>";
for(var i=0; i<data.length; i++)
{
html = html + '<tr><td>' + data[i].name + '</td>' + '<td>' + data[i].type + '</td>' + '<td>' + data[i].country + '</td>' + '<td>' + data[i].region + '</td></tr>'; 
}
html = html + '</table>';
$('#results').html(html);
console.log(data);
console.log(status);
}

The following PHP code is used to search and return all results:

IF ($type == "any" && !isset($region)) /* Search DB for all types of POI for all regions*/
    {
        $statement = $conn->prepare("SELECT * FROM pointsofinterest;");
        $statement->execute();
        $row = $statement->fetch();

        if ($row == false)
        {   
            header("HTTP/1.1 204 No Content");
        }
        else
        {
            $allResults = array();
            while($row != false) 
            {
                $allResults[] = $row;
                $row = $statement->fetch(PDO::FETCH_ASSOC);
            }
            echo json_encode($allResults);
        }
    }

Answer №1

It is best practice to return empty results and let the Javascript handle how to notify the user if there are no results available. Please note that this code snippet is for reference only and has not been tested.

PHP

if ($type == "any" && !isset($region)) /* Search DB for all types of POI for all regions*/
{
        $statement = $conn->prepare("SELECT * FROM pointsofinterest;");
        $statement->execute();
        $results = $statement->fetchAll();
        if (count($results)!=0){
            echo json_encode($results);
        } else {
            header("HTTP/1.1 204 No Content");
        }
}

JAVASCRIPT

You may want to handle the 204 response separately: How to handle a 204 response in jquery ajax?. The code below assumes you may receive an empty JSON response.

function onSuccess(data,status,xmlHTTP)
{
    if (data.length==0) {
       alert("Friendly user message"); 
       return;
    }
    var html = "<table><th>name</th><th>type</th><th>country</th><th>region</th>";
    for(var i=0; i<data.length; i++)
    {
    html = html + '<tr><td>' + data[i].name + '</td>' + '<td>' + data[i].type + '</td>' + '<td>' + data[i].country + '</td>' + '<td>' + data[i].region + '</td></tr>';  
    }
    html = html + '</table>';
    $('#results').html(html);
    console.log(data);
    console.log(status);
}

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

Struggling to retrieve user input from a textfield using React framework

I'm having trouble retrieving input from a text-field in react and I can't figure out why. I've tried several solutions but none of them seem to be working. I even attempted to follow the instructions on https://reactjs.org/docs/refs-and-th ...

What causes an error in returning an entity with a one-to-many relationship in a web API?

Hey guys, I have a One to Many relationship with the same class called User. In my web API's GET method, I am returning just one instance of the user and it seems to be working fine as long as there are no issues. User ID | Name 0 | A 1 | B ...

`I'm having issues trying to use ajax and load simultaneously``

Can anyone help me figure out why my AJAX call to sessions.php is not correctly loading and returning true or false each time a user accesses the page? var section = $("#header a"); section.on('click', function() { $.ajax({ type: "PO ...

The touch event doesn't seem to be functioning properly on the div element, but it works perfectly on the window element

I have a dilemma that's been puzzling me lately. I'm trying to append a touchevent to a div, but my current method doesn't seem to be working. Here's what I've tried: $("#superContainer").bind('touchstart', function(even ...

Developing a standard jQuery function for adding event listeners

Attempting to replicate the functionality of Google Maps' addListener using jQuery listeners for clicks, keypresses, etc. In Moogle Maps, you can use .event.addListener(map, 'click', function()... or switch 'click' with 'drag ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

Tackling the issue of memory leaks in Node.js when dealing with a high volume of frequent

TL;DR https://gist.github.com/anonymous/1e0faaa99b8bb4afe3749ff94e52c84f - Example demonstrating memory consumption indicating a potential leak issue. Is the problem in my code or within the mysql package? Extended Version : I've been noticing sign ...

Using JavaScript to ensure that a div is not hidden on page load if a checkbox is unchecked

Upon inspecting a page, I am implementing a script to check if a checkbox is selected. If not selected, the goal is to hide a specific div element. While troubleshooting this issue, I suspect the problem may be due to the lack of an inline element within t ...

Styling Discord with NodeJS

After coding with Python for Discord, I decided to switch to JavaScript for its wider functionality. However, I encountered a formatting issue with a specific line of code while testing out a music bot in JS. The bot was sending an embed message, but I wan ...

Issue with Symfony 4: @ParamConverter annotation unable to locate object in Profiler exclusively

The issue is specific to the debug toolbar. Highlighted below is the code section I suspect might be causing the problem /** * @Route("/{category_slug}/{slug}", name="content_show") * @ParamConverter("content", options={"mapping": {"slug": "slug"}} ...

Undefined Response Error when Utilizing Dropzone for File Upload in Express

I am currently in the process of setting up a basic image upload demonstration using Dropzone and Express. Here is what my form looks like: <form id="ul-widget" action="/fileupload" class="dropzone" enctype="multipart/form-data"> <div class="fal ...

Guiding motion of a parental container using a button

This seems like a fairly straightforward task, but I'm getting a bit frustrated with it. Is there a way to move an entire div by simply holding down the mouse button on a particular button? let container = document.getElementById('abo ...

Unravel the JSON data array and seamlessly add it to a MySQL database

Looking for some help here as I am struggling with extracting Json data and inserting it into a MySQL database using PHP. Any assistance would be greatly appreciated. {"CityInfo":[{"CityCode":"5599","Name":"DRUSKININKAI"},{"CityCode":"2003","Name":"KAUNAS ...

Using the ControllerAs syntax in conjunction with $scope methods

Currently working on incorporating the controllerAs syntax into AngularJS 1.3 Here is how I'm starting my function declarations: function() { var myCtrl = this; myCtrl.foo = foo; // Successfully implemented myCtrl.$on("foo", bar); // Enc ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

Utilize custom {tags} for replacing strings in a CSS file using str_replace in PHP

My code consists of a script that updates a CSS file based on user input from an html form. The script executes a str_replace function, scanning the CSS file for specific "tags". For example: html,body { background: {bgcolor} url(../images/bg.jpg) re ...

Utilizing Express.js and AJAX to transfer JSON data from the server to the client

Having trouble sending JSON from Express.js back to the client, and I can't seem to figure out what's going wrong. routes/editor.js exports.save = function(req, res){ fs.readFile(__dirname + "/../public/index.html", function (err, data) { ...

Sending Multiple Sets of Data with Jquery Ajax.Post: A Step-by-Step Guide

I am currently working with asp.net mvc and I have a requirement to send two sets of database information from jQuery to my Mvc view. Here is an example of how my view looks like: public ActionResult MyView(Product one, Product two) { } Now, my question ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

MongoDB issued an error notification stating: "The operation `disneys.insertOne()` has experienced a timeout after 10000 milliseconds."

I am currently in the process of developing a new API using MongoDB and Express, and I have come across the following issue: "Operation disneys.insertOne() buffering timed out after 10000ms." To test my API, I am using route.rest. However, I ...