struggling with responseText functionality in javascript

I am encountering an issue with passing variables from PHP to JavaScript using JSON. The problem lies in the fact that I am able to debug and view the items in the responseText within my JavaScript, but I am unable to assign them to a variable or properly view them. Even when attempting to work with a single item, I have not been successful. Any insights as to why this could be happening would be greatly appreciated.

function ajaxrequestDB() {
    var AJAX = null; // Initialization of the AJAX variable.

    if (window.XMLHttpRequest) { // Checking for XMLHttpRequest object support.
        AJAX=new XMLHttpRequest(); // Initializing it.
    } 
    else { // Trying initialization IE style.
        AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (AJAX==null){
    alert("Your browser doesn't support AJAX.");
    return false
    }
        AJAX.onreadystatechange = function() {
            if (AJAX.readyState==4 || AJAX.readyState=="complete") 
            {
            callback(AJAX.responseText, AJAX.status);
            }
        }

    var url='http://localhost/Scripts/refresh.php'; 
    AJAX.open("GET", url, true); 
    AJAX.send();      
    alert(AJAX.responseText);
    var result = AJAX.responseText;

    eval(result);
}

Upon debugging on AJAX.responseText, the returned data from the PHP file can be observed, however, only a blank alert window appears when executing alert(AJAX.responseText).

Below is the PHP file responsible for retrieving data from the database and sending variables to JavaScript.

<?php
header('Content-type: application/json');
$con = mysql_connect("localhost","root","");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("cpd", $con);

$SQL = "SELECT name from markers";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){

$data[]= $db_field;

}  
echo json_encode($data);

?>

Answer №1

If you want your ajax request to run asynchronously, remember to set the 'true' parameter in the following command:

AJAX.open("GET", url, true);

This means that the ajax response will only be available when AJAX.readyState==4. Therefore, make sure to include the following code snippet:

    alert(AJAX.responseText);
    var result = AJAX.responseText;

    eval(result);

Insert the code snippet inside this block:

AJAX.onreadystatechange = function() { // This function runs when browser gets the request info..
            if (AJAX.readyState==4 || AJAX.readyState=="complete") 
            { // Check if request is completed
              //YOUR CODE//
            callback(AJAX.responseText, AJAX.status); // Send response for processing
            } // End check for Ajax readystate.
        }

Answer №2

Check out this JavaScript code snippet:

function fetchDataFromServer(callback) {
    var request; // Initialize the request variable.
    if (window.XMLHttpRequest) { 
        request = new XMLHttpRequest(); 
    } else if (window.ActiveXObject) { 
        request = new ActiveXObject("Microsoft.XMLHTTP"); 
    }
    
    if (!request) { 
        alert("Your browser does not support AJAX."); 
        return false; 
    }

    request.onreadystatechange = function() { 
        if (request.readyState == 4) { 
            callback(request.responseText, request.status); 
        } 
    }
    var url = 'http://example.com/api/data';
    
    request.open("GET", url, true); 
    request.send(null);       
}

function handleResponse(data, status){
    if(status==200){
        alert(data);
        var parsedData = JSON.parse(data);
        alert(parsedData);
    }
    else alert("HTTP Error:" + status);
}

fetchDataFromServer(handleResponse);

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

How can I modify the appearance of the bootstrap scrollbar with scrollspy?

I'm struggling to modify the color of the scrollbar in Bootstrap scrollspy despite having a functional scrollbar. Here is an example of my code: HTML: <body> <div class="container, scrollbar" id="myScrollspy"> <div class=" ...

Steps to fix the issue: Unhandled Type Error: t.addLayer is not a recognized function

I've encountered a bit of difficulty with an error that I can't seem to figure out. I'm currently working on adding a geoJSON layer to my Leaflet Map, specifically a multi-polygon representing country borders. To achieve this, I'm using ...

Modifying Selectize Ajax data in real-time

How can the student_id be changed each time the modal is opened? This is the code: $('#relationshipModal input[name=existing_user]').selectize({ valueField: 'id', searchField: 'name', options: [], create: fal ...

Update the image within the svg tag

I am attempting to modify a preexisting SVG element within an HTML document. Here is the current code: <svg class="logo" viewBox="0 0 435 67"> <!-- IMAGE DIMENSIONS --> <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#logo- ...

Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue? Previously, I attempted to retrieve the location by using the axios ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Ways to stop touch events on every element but one through JavaScript

One issue I encountered was preventing scrolling in the background while a popover is open. For desktop, it's simple with CSS: body { overflow: hidden; } The problem arose on IOS where this rule didn't work as expected and the background could ...

Utilize the AWS resource aws_route53_record in Terraform to efficiently import route 53 records from a JSON file

Currently, I am exploring the process of importing DNS records from a JSON file. The interesting part is that there can be multiple JSON files in the same folder, each containing one or more DNS records like below: [ { "dnsName":"my ...

Tips for utilizing modify-json-file with string value as key

I'm currently exploring ways to dynamically modify a JSON file during runtime by utilizing the modify-json-file npm library. The general API structure seems to operate in a certain manner: await modifyJsonFile( './filename', { ...

Unveiling the Mystery: How Browser Thwarts Server Push in HTTP/2.0

After studying the documentation of HTTP/2.0, I discovered that it is feasible to completely close a referenced stream using the RST_STREAM frame. Check it out here: ()! I am curious about how this feature can be implemented in popular web browsers such a ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...

Automatically scrolling down a div as new content is added using XMLHTTPRequest.openConnection

https://jsfiddle.net/kv5gbamg/ - I created a jsfiddle to demonstrate the functionality of the system Essentially, I am seeking a way to automatically scroll the scrollbar to the bottom every time a new message is received. My system updates the div with ...

Refresh only a portion of a page using PHP and JavaScript

I have a webpage set up with multiple sections in separate divs. Currently, the essential divs required are <div id="main">...</div> & <div id="sidebar">...</div> Each div contains PHP code like: <?php include("page.php") ...

HTML elements generated dynamically do not possess any jQuery properties

I have implemented a draggable list of Div elements using jQuery. Here is the code: <div id="external-events"> <h4>List Of Staffs</h4> <div class="external-event" data-id="1">Name</div> //Draggab ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Ways to stop a ng-click event on a child div controller from activating an ng-click in the parent controller?

http://plnkr.co/edit/gB7MtVOOHH0FBJYa6P8t?p=preview The example above demonstrates a parent-child controller setup. In the child controller, when a button is clicked, it displays the div showPop and emits an event to the $rootScope. Upon receiving this e ...

Launching a HTML hyperlink inside a div with the power of jQuery

I am currently exploring the functionality of dragging and dropping an HTML link into a div element. My objective is to have the link open within that specific div element. The layout consists of two divisions named "left-panel" and "canvas". The concept ...

Javascript: triggering a self-executing function manually

I have a code snippet similar to the following: var msg="first call"; (function test(msg) { console.log("inside self call"); } )(); msg="second call"; console.log("before inline call"); test(msg); console.log("after inline call"); In thi ...

displaying a pair of distinct elements using React techniques

I need help adding a react sticky header to my stepper component. When I try to render both components together, I encounter an error. To troubleshoot, I decided to render them separately. Surprisingly, when rendering separately, I do not get the "store is ...

Change the price directly without having to click on the text field

Our Magento marketplace site is currently utilizing the code below for updating prices. However, we are looking to make the price field editable without requiring a click on the textfield. This means that users should be able to edit the price directly wi ...