Extracting information from the responseText of an XMLHttpRequest

Using AJAX, I am retrieving some data that I need to manipulate after the AJAX call completes. However, I am facing an issue where I can't seem to manipulate the response. Here is the code snippet:

function testAjax() {           
        direc = "controller.php";
        return $.ajax({url: direc});            
        }           
        var obj = testAjax(); 
        console.log(obj);           
        console.log(obj.responseText); 

The console.log(obj) output is as follows:

 XMLHttpRequest { readyState=1,  timeout=0,  withCredentials=false,  more...}

Response:

"[{"CLICREDIT_Cod":"1002","CLICREDIT_Credit":"2000","CLICREDIT_FlagEstad":"1"}]"

responseText:

"[{"CLICREDIT_Cod":"1002","CLICREDIT_Credit":"2000","CLICREDIT_FlagEstad":"1"}]"

The console.log(obj.responseText) returns an empty string.

I have attempted methods like JSON.parse to manipulate the data, but none seem to work. Any assistance in this matter would be greatly appreciated. Thank you.

Answer №1

When working with asynchronous ajax requests, remember to utilize the "then" method:

promise.then( successCallback, failureCallback )

function executeAjax() {
  endpoint = "backend.php";
  return $.ajax({
    url: endpoint
  });
}
var request = executeAjax();

request.then(function(response) {
  console.log(response);
}, function(xhr, options, error) {
  alert(xhr.status);
  alert(error);
});

Answer №2

To handle asynchronous tasks, make sure to implement the .done() function in your code. Check out an example in the provided link.

Answer №3

To ensure the browser does not wait for a response and continues with code execution, you can utilize a callback function after the success event. This way, when the browser receives the result, the callback function will be triggered.

$.ajax({url: direc, success: executeAction});
function executeAction(data){
//perform actions using data
}

Answer №4

To retrieve the response of the page you requested, simply use the success() function.

 var pageResponse={};
 $.ajax({
    url: 'controller.php',
    type:"POST",
    success: function(data){
        pageResponse = data;
    }
 });

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

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...

Using React to manipulate objects within an array

I am looking to convert a firebase object into an array, with the desired structure shown below: For a working example, check out this JSFiddle link: https://jsfiddle.net/vfra1yp5/ 0: Object { first: "https://google.com", last: "google" ...

Adjust the size of a nested div with varying height

Hey there! I'm facing an issue with a main div that contains 2 other divs. I need the height of the lower div to change dynamically based on the resize of the main div. Here's the code I have so far: <html> <head> <meta http- ...

What could be causing the failure of this mock jest test?

I've been working on simulating document.clipboard in my code. This is the code snippet: handleCopyIdToClipboard = () => { const el = document.querySelector(`.${CLASS_NAME}`); navigator.clipboard.writeText(el.textContent); // addit ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Setting the initial date value for an Angular Material md-datepicker to a specific date

When using Angular Material md-datepicker, by default the system's current date is set as today's date and highlighted in the calendar. However, I am looking for a way to manually set any given date as today's date instead. Please see this i ...

Creating a framework for sharing data between directives using Angular services

In my project, I have developed two directives named "mainPane" and "sidePane" displaying lists of items. These lists often contain overlapping content, allowing users to interact with the items in either list. My main requirement is that any changes mad ...

Conceal header and footer bar in Jquery Datatable theme

I need assistance in removing the header/footer bar from this table Here is a visual representation of what I am looking to remove: The jQuery code for this table: $(document).ready(function() { var oTable = $('#tableSmooth').dataTable({ ...

The animation in Bootstrap is not functioning according to expectations

If you're looking for bootstrap animations, you can check them out here. My goal is to remove the animation once it has finished playing. There's a trigger on the website that should assist with this. The issue arises when I click the button; the ...

What is the best way to maintain filter selections on the subsequent page using PHP Laravel?

There seems to be an issue with filtering my user table on the page. While I can successfully filter the first page of users, when I navigate to the second page, everything reverts back to default instead of remembering the form inputs. Here is a snippet o ...

Is bundling a Node.js backend a wise decision or a mistake?

Just a thought that crossed my mind - I understand the advantages of bundling client-side code, but what about bundling server-side code with Browserify/Webpack? Is this considered a best practice? ...

How can I transfer the retrieved iron-ajax string to a different polymer component?

I've been able to successfully retrieve and load iron-ajax data into my element, but I've encountered an issue with a nested custom element that requires a 'workerid'. The problem arises because the 'workerid' is returned from ...

Add the latest value to the end of the selection option

How can I append a new value at the end of an option select box, ensuring that the number continues instead of starting from 1? var n_standard = 1; function removeStandard() { var select = document.getElementById('selectBoxStandard'); for ...

JavaScript watermark with alternating/dual mode

In the following code snippet, I have implemented a function to make window.status switch between displaying "a" and "b." function alternateViaIntrvl() { setInterval('alterStatus()', 500); } var altrCounter = 0; function alerted() { var ...

My objective is to use JavaScript to dynamically update information in an HTML document using data retrieved from a JSON file

Experience the benefits of our membership program: PROGRAMMING var benefitsData = document.getElementById("memberBenefits"); for (var i = 0; i < membershipData.benefits.length; i++){ benefitsData[i].getElementsByTagName('h4')[0].innerHTML = ...

What is the best way to overlook content-encoding?

I am in need of downloading a file from a device. Sometimes, the file might have an incorrect content-encoding, specifically being encoded as "gzip" when it is not actually compressed in any way. When the file is properly gzipped, retrieving the content u ...

Retrieve the text and image simultaneously using jQuery

I need to retrieve either text or image within a modal. Use textCont to retrieve text. The content within a div can be either text or image. It will retrieve whatever is present there. Below is the JavaScript code for text retrieval. var contId = 0; var ...

Building a Dynamic Web App with PHP and Vue.js

I developed an API using PHP and you can access it through this link: However, I encountered an issue when trying to display the data on the front-end of my Vue.js (Home.vue) file using axios. Below is the code I used: <ul class="ta-track-list" v-if= ...

Having difficulty accessing the uploaded file through the <input type="file"> feature

I need help with uploading a file using the input type="file" and then sending it via email along with other data. However, when I receive the email, I can see all the text data but not the uploaded file. The file path displayed is something like "C:\ ...