logo
down
shadow

Javascript newbie stuck with XMLHttpRequest return data


Javascript newbie stuck with XMLHttpRequest return data

Content Index :

Javascript newbie stuck with XMLHttpRequest return data
Tag : javascript , By : Kenny
Date : January 12 2021, 09:11 PM

I think the issue was by ths following , XMLHttpRequest requires you to add an event listener and wait for the load event. This will tell you once the request has completed and then you can do something with the response.
Take a look at this website for a more detailed description: https://javascript.info/xmlhttprequest

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Newbie stuck again.. No errors, but my data won't save


Tag : ruby-on-rails , By : Robin Buitenhuis
Date : March 29 2020, 07:55 AM
will be helpful for those in need Make sure that you have form_for [@ingredient, @unit_conversion] in your form.
new.html.erb
<% title "New Unit Conversion" %>
<%= render :partial => 'form' %>
<p><%= link_to "Back to List", ingredient_unit_conversions_path(@ingredient) %></p>
<% form_for [@ingredient, @unit_conversion] do |f| %>
  <%= f.error_messages %>
  <p>
  ... fields here
  </p>
  <p><%= f.submit "Submit" %></p>
<% end %>

Javascript: xmlhttprequest randomly stuck at Ready State 1


Tag : javascript , By : jaime
Date : March 29 2020, 07:55 AM
To fix this issue Well it looks like I figured it out. I had a feeling it was an unresolved request, since it only happens when instances of it are closed (meaning that if one of them is closed while in communication with the server it stays in communication forever and no one else can access the server) and it appears that is the case. I made some modifications to the code in multiple areas and basically what it comes down to is when the gadget closes it makes sure to abort all of the requests. The requests are now instance variables (to allow for the aborting of them), but are still made new everytime they are needed.

AJAX - Order of commands with XMLHttpRequest (Newbie)


Tag : ajax , By : todor
Date : March 29 2020, 07:55 AM
Hope that helps Because onreadystatechange is an event, and that code won't get invoked until the ready state changes, which will occur at some point in the future when the request is complete.

Javascript : return XMLHttpRequest out of scope


Tag : javascript , By : changke
Date : March 29 2020, 07:55 AM
it fixes the issue Well, since you are using jQuery tag, I think my answer could be valid and I prefer doing this way for what you need and I understood (it is well explained so please read code comments and check browser console, this can be found at the end of the answer).
Remember that you won't be able to return a XMLHttpRequest because ajax calls are async but you can force an ajax call to be sync in order to get your data on a return statement from any function or do other things as you expected. However, forcing is not a good approach to do because UI will freeze for the user until getting the response back from server and you really don't know how much time that will take (specially if you are expecting a big amount of data to be returned - I know that's not entirely a metric but other factors may apply).
<div id="wrapper">
    <div id="loader"></div>
    <div id="content"></div>
</div>
$(function() {

    var series = [], // Your series array
        loader = $('#loader'), // UI loader sample
        request = {}; // Request params

    /**
     * Set request method, url and data if needed
     * In this case I am sending an object with a text property
     * that will be returned from jsfiddle "echo" service
     */
    request.method = 'GET';
    request.url = '/echo/jsonp/';
    request.data = {
        text: 'Second message returned from "echo" service'
    };

    // Send ajax call
    retrieveData(request, series, handleData);

    // Set loading message to UI
    loader.html('Loading...');

    // Just do some logging to know how process goes
    console.log('Populating series for the first time');

    /** 
     * Populate series for the first time, at this point process
     * will go on and after the response from server was finally
     * done, process will go to the callback (since ajax calls 
     * are async).
     */
    populate(series);

    // Just do some logging to know how process goes
    console.log('End populating series for the first time');
});

function populate(series) {
    var dummy = {
        text: 'First message populated over process'
    };

    // Set dummy object to series array
    series.push(dummy);
};

/**
 * Used to make ajax call and return data from server
 */
function retrieveData(cfg, series, callback) {
    $.ajax({
        type: cfg.method,
        url: cfg.url,
        data: cfg.data
     }).done(function(data, status, xhr) {
        // Pass args to callback function if defined
        if (callback) callback(series, data);
     }).fail(function(xhr, status) {
        /**
         * Pass args to callback function if defined
         * At this point, request wasn't success so 
         * force data arg at callback to be 'null'
         */
        if (callback) callback(series, null);
     });
};

/**
 * Used to handle data returned from server
 * Note: Your series array can be modified here since you
 * passed it into the callback
 */
function handleData(series, data) {
    var loader = $('#loader');

    // Just do some logging to know how process goes
    console.log('Populating series from server');

    // Check if data is defined and not an empty object
    if(data && !($.isEmptyObject(data))) {
        // Add it to series array
        series.push(data);
    }

    // Set UI loader empty
    loader.html('');

    // Retrieve series
    showData(series);
};

function showData(series) {
    var contentDiv = $('#content');

    // Loop process and append to UI
    for(var i = 0; i < series.length; ++i) {
        contentDiv.append(series[i].text + '<br>');
    }
};

Javascript return after XMLHTTPRequest()


Tag : javascript , By : Florian D.
Date : March 29 2020, 07:55 AM
hope this fix your issue This is the programming paradigm that every new javascript developer has to deal with.
Because of the asynchronous nature of javascript, functions tend not to pass values back via return statements, but instead the values are passed back via callback methods.
function something(url) {
     getPage(url, function(temp) {
         console.log(temp);
     });
}

function getPage(url, callback) {
     var x = new XMLHTTPRequest();
     x.onload = function() {
          var html = x.responseText;
          //CODE TO PARSE HTML TEXT
          var variable = SOMETHING PARSED FROM HTML
          callback(variable);
     }
     x.open("GET", url);
     x.send();
}
Related Posts Related QUESTIONS :
  • Http Auth in a Firefox 3 bookmarklet
  • How can I turn a string of HTML into a DOM object in a Firefox extension?
  • Call ASP.NET function from JavaScript?
  • JavaScript Troubleshooting Tools in Internet Explorer
  • MAC addresses in JavaScript
  • Capturing TAB key in text box
  • How to set CSS background color of HTML using JavaScript
  • How can I make the browser see CSS and Javascript changes?
  • redux how to use state
  • All data in the db is lost when closing a express based node js server
  • How to convert javascript code for Angular
  • XPath select on child nodes
  • Idle event on mouse move - how to stop script permanently on mouse move
  • Why do I get logic is not defined in this code
  • When I enter a number in the input, the first function starts
  • ES6 imports and node_modules hell
  • How to get css selector of clicked-on element?
  • How to auto input MySQL data (input column 1 data to auto input column 2 data with same column) in php?
  • Appending to Datalist Via Javascript
  • Customizing Material-UI Components with Styled-Components
  • Populate elements with class name using Javascript
  • How to execute promises in batches (first resolving 10, then next 10 and so on)
  • Maximo JS automation script: "importPackage" is not defined
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com