Search code examples
javascriptactionscript

convert LoadVars & sendAndLoad from actionscript to javascript


I am a beginning programmer and trying to convert a program in Actionscript to javascript.

So far I could do all the conversions I needed, but I am stuck on the following code below.

I understand that the variables fileName & test ID are sent to the script which is located at the url interfaceUrl + "operation=" + Test and the answer is stored back in lvReply.

Which code/function I would need in JavaScript to do the same.

I am looking at XMLHttpRequest but do not know if this is the right way to move forward. Any help in pointing me to the right direction would be appreciated.

var lv:LoadVars = new LoadVars();

    lv.fileName = fileName;
    lv.lpTestId = testId;

var lvReply:LoadVars = new LoadVars();
        
lv.sendAndLoad(interfaceUrl + "operation=" + Test, lvReply, "POST");

Solution

  • LoadVars just loads name / value pairs from the server, in the form of:

    someText=testing&myVariable=123
    

    For JavaScript, you can use:

    XHR:
    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

    to load the data, and then:

    URLSearchParams to parse them:
    https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

    Here is some pseudo code to demonstrate:

    let xhr = new XMLHttpRequest();
    
    //load data, sending params to server via query string
    xhr.open('GET', 'http://example.com/data?args1=boof&arg2=banana'); 
    
    xhr.onload = function() {
      if (xhr.status != 200) { 
        //check status code to see what happened
      } else {
    
        //data sent from server in the form of foo=bar&biff=bam
        let data = xhr.response;
    
        let params = URLSearchParams(data);
    
        let foo = params.get(foo);
        console.log(foo); // prints bar
      }
    };
    
    xhr.onerror = function(err) {
      //something went wrong
    };
    
    xhr.send();
    

    A better solution would be just to send JSON from the server and parse it with JSON.parse()

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    Note, in the example above, it is also sending data to the server. You can also do that using XHR (either via GET or POST).