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

Ensure that each number is entered only once in the input field

Is there a way to use javascript/jquery to prevent a user from entering the same number twice in an input box? Users can enter multiple numbers one at a time, but I need to notify them or take action if they try to input the same number again. I attempted ...

The absence of parameters or their incorrect transmission as a JSON array through PHP CURL

Encountered error message: {"jsonrpc":"2.0","id":0,"error":{"code":1,"message":"Parameters missing or not sent as an JSON array. "}} Snippet from the code: <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: applicatio ...

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

What is the process of using TypeScript to import a constant exported in JavaScript?

In the environment I'm using typescript 2.6.1. Within react-table's index.js file, there is a declaration that looks like this: import defaultProps from './defaultProps' import propTypes from './propTypes' export const React ...

Incorporating a self-invoking anonymous function to enhance Sir Trevor within an AngularJS framework while also making use of

I recently started working with AngularJS and I have an App where I am using the Sir Trevor content editor. I want to add some custom blocks to the editor by extending it, but I am having trouble accessing angular services within my extension code. The ext ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...

Having issues with angular-file-upload failing to include the file in the request

I am currently using angular-file-upload in order to upload an image to a server that is utilizing Node and Express 4.0. However, I am encountering difficulties in accessing the file data on the server. Below is the relevant code snippet: <input type= ...

Counting the occurrence of a specific class within an element using jQuery

Within my table, each row is assigned one or more classes based on its region. This is the structure of my table: <table> <thead> <th>Title</th> <th>Name</th> </thead> <tbody> <tr class="emea ...

showing notification through ajax form

I have a form that inserts data into a database based on the input provided. Below is the form: <form id="contact-form" class="bl_form text-center" action="<?php echo "index.php?page=rooms&room=$rid&amp;rpw=$rpw&amp;r=$r"; ?> ...

ReactJS encounters errors even when the backend is returning a 200 OK status code

My ReactJS frontend receives an error when sending a GET request, even though the django backend terminal shows [10/Mar/2018 23:31:08] "GET /post/ HTTP/1.1" 200 930. I am using redux sagas in my project. In src/index.js: (index.js code snippet here) In ...

Encountering a CSS problem while attempting to design a section featuring a background image

On this page, I have the login bar on the right and the footer at the bottom. I want a div to sit in the area currently occupied by the background image and fill it with the full background image. Currently, everything is wrapped in a wrapper and the back ...

Explore the titles provided by Wikipedia

Hi there, I'm fairly new to Angular and trying to work with the Wikipedia API. However, I seem to be having trouble getting 4 titles from the API. Here's an example URL for one of the titles: https://en.wikipedia.org/w/api.php?action=query&pr ...

What could be causing this ajax function to fail?

I referred to a solution in response to this question: My objective is to execute a query on the database when a user clicks on a specific table row, enabling me to retrieve and display their information. Below is the piece of code I am using: AJAX: $( ...

Employing Microsoft.FSharpLu for the process of serializing JSON data into a stream

Recently, I've been utilizing the Newtonsoft.Json and Newtonsoft.Json.Fsharp libraries to construct a new JSON serializer that streams data into a file. Streaming to a file has proved beneficial for me as I often dealt with memory-related issues when ...

How can I parse a JSONArray in Retrofit without parsing objects individually?

Just finished parsing this Json format: { msg: "success", status_code: 200, data: [ { .... } ] } I used Retorfit2 to parse it into this object: public class Model { @SerializedName("status_code") int statusCode; @SerializedName("msg") p ...

Capture locations from Google Maps

What is the best method to extract all addresses, along with their latitude and longitude, for a specific city (such as Bangalore) from Google Maps using PHP/JavaScript and store it in a MySQL table? I urgently need assistance. Thank You ...

Confirming whether the digit entered in jQuery is a number

My website has a user input field where numbers are expected to be entered. I wanted to find a convenient way to validate the input using jQuery. After some research, I discovered jQuery's built-in function called isDigit. This handy function allows ...

Deleting occurrences of a specific text from a JSON document and subsequently analyzing its contents

I am having an issue with a JSON file in which there are strings of characters attached to many of the field names. This is making it difficult for me to target those objects in JS. The structure looks like this: "bk:ParentField": { "bk:Field": "Va ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...