ResponseText from AJAX xmlhttp

After pondering for a few hours, I am stuck trying to understand why a simple string comparison is not working. In the code snippet below, I perform an XMLHttpRequest and receive a response text. The PHP file being called returns the correct response string "NOAD", which is also displayed correctly in my testing scenarios. However, when the call returns "NOAD", I try to compare it using

xmlhttp.responseText == comparisonText
, but for some reason it fails to match the two strings. Even though xmlhttp.responseText prints out "NOAD," I can't seem to use it within the comparator.

function loadXMLAdImage1Doc(currentScenarioTime) {

    var returnText = "Not Here";
    var comparisonText = "NOAD";

    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            if (xmlhttp.responseText == comparisonText) {
                document.getElementById("AJAXTEST").innerHTML = returnText;
            } else {
                document.getElementById("AJAXTEST").innerHTML = xmlhttp.responseText; 
            }
        }
    }
}

Answer №1

Thank you, Luth, for pointing me in the right direction. I was able to solve my problem, however, I am uncertain as to whether the issue lies within xmlhttp.responseText or if it is a user error that caused it.

The response text from my PHP file contained an invisible character inserted before the actual string being returned (initially, I assumed it was situated after the results during testing, but it turned out to be quite the opposite). Ideally, this should not have occurred...as my PHP script is set up to return a simple string:

..perform some MYSQL queries..
$AdLink = mysql_result($result, 0);

if ($AdLink == "") {

echo "NOAD";
} else
{
echo $AdLink;
}

Therefore, the PHP file was supposed to send back a 4-character response to the xmlhttp.responseText call with the name "NOAD". However, upon further inspection of the string length, it was discovered that a 5-character string was being returned with an invisible character preceding "NOAD," which was causing issues with the comparison process. To fix this, I utilized the following code to eliminate the unwanted character successfully:

returnText = xmlhttp.responseText;
var returnlength = returnText.length;

returnText = returnText.substring(1, returnlength);

I am unsure about the nature of the mysterious character and whether it stems from my PHP code or the xmlhttp.responseText call itself, but it is definitely something to keep in mind when dealing with such requests.

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

Setting orientations for portrait and landscape views using Material UI breakpoints

Looking to implement portrait and landscape views for tablets using the styles object in Material UI. const tabletStyles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme ...

Checking the service callback function in an AngularJS controller test

I have a Controller that utilizes a service with a callback function upon success. Controller Function itemCtrl.save = function () { ItemService.save({ username: SessionService.getUsername() }, itemCtrl.item, function (res) { $scope.$emit(&ap ...

When a button is clicked within a partial view, it will redirect to the parent action

I am struggling with implementing an AJAX call using jQuery in a partial view within my application. I have a parent view called 'Parent' where I am using @Html.BeginForm and a submit button to save data. However, whenever I try to make the AJAX ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

Check to see whether the coordinates fall inside the specified bounding box

I am faced with the task of creating a function that can determine whether a given coordinate c lies within the boundaries of coordinates a and b. All variables in this scenario are of type: type Coordinate = { lat: number; lon: number; }; Initially ...

What strategies can I employ to help JSDoc/TypeScript recognize JavaScript imports?

After adding // @ts-check to my JavaScript file for JSDoc usage, I encountered errors in VS Code related to functions included with a script tag: <script src="imported-file.js"></script> To suppress these errors, I resorted to using ...

How to implement loading an external script upon a page component being loaded in NextJS

I recently transferred an outdated website to Nextjs and I am having trouble getting the scripts to load consistently every time a page component is loaded. When navigating between pages using next/link component, the scripts only run the first time the ...

Tips on managing ASP .NET API's HttpResponseMessage for file downloads

I came across a solution on how to download a file from an asp.net API at this link: As a result, I created an API handler with the following code: public HttpResponseMessage Post([FromBody]dynamic result) { var localFilePath = graph ...

Attempting to dynamically update the title of a Vue Meta page using a combination of a string and

In the blog application for my project using Nuxt JS 2.4.5, I am utilizing Vue Meta. I'm encountering difficulties while attempting to set the title along with a variable from data (), and it seems like something crucial is eluding me. Despite tryin ...

Disable the confirmation dialog for PUT and DELETE requests from Backbone to Django API in Firefox

Why is Firefox showing a confirmation box for PUT and DELETE requests sent from Backbone to Django REST API, while no such confirmation is required for POST requests? This webpage is being redirected to a new location. Would you like to resend the form ...

Using JQuery to handle multiple JSON requests with deferred or promise methods resulted in errors

Our application allows users to load data via Ajax requests. For example, we have a selection of items known as 'tracks'. When a user clicks on a track, an Ajax request is triggered to retrieve and display the corresponding data. Each track is en ...

Saving data for editing on a Laravel page can be achieved by leveraging the powerful features

I have implemented my create page using vue.js. I called the vue.js file using a component. Now, for the edit page, I followed the same procedure by calling the vue component in the blade. However, I am unsure how to save data for the edit page. Can anyone ...

Understanding how to parse an array of arrays in JavaScript can be a

Looking for a function that can extract a value from an array containing multiple arrays? Simply use getValueFromArray(array, [2, 4]) to get the 4th element of the 2d array within the main array. Check out the code snippet below: function getValueFromArr ...

Changing the event when a class is active in Vue3

Question I am looking for a way to trigger an event when the 'active' class is added to an element. How can I achieve this? I believe this could potentially be accomplished using a watcher method, but I am unsure how to watch for the applicatio ...

Why isn't my content appearing correctly on different pages?

This ecommerce site is my very first project using React. I have created pages for Contact, Login, and more. The footer and other components display correctly on the home page, but when navigating to other pages, the content appears shortened. For referen ...

Steps to Create Javascript Image Zoom Effect on Mouse Hover

Looking to implement a feature on my website located at www.thetotempole.ca/javas2.html/. Basically, I have a table with images and I want them to enlarge when a user hovers over them and return to normal when the cursor is moved away. Is there a way to ac ...

Seeking recommendations for designing a database architecture

My friend and I collaborated on building a MySQL php website that allows users to make predictions on sports events. The issue at hand concerns our "rankings" page, which showcases the top members based on their predictions. Initially, each time a user vi ...

Displaying a Div Using ASP AJAX

After submitting a comment, I would like to implement a jQuery function that will fade in a message to inform the user whether the insertion was successful or not. How can this be achieved? I understand that I need to include the fadeIn effect within the j ...

Steps for updating text within an object in Angular

details = [ { event: "02/01/2019 - [Juan] - D - [Leo]", point: 72 }, { event: "02/01/2019 - [Carlo] - N - [Trish]", point: 92 } ]; I am attempting to modify the text within the titles that contain - N - or - D - The desired outcom ...

IIS Alert: Missing Images, CSS, and Scripts!

When I tried to publish my website using IIS, I encountered the error message Cannot read configuration file due to insufficient permissions. After attempting to add permissions for IIS_USRS and realizing that this user does not exist on my computer runnin ...