简体   繁体   中英

Call Perl script using D3 Xhr

I have a web application with an HTML form. When I press submit I want to submit the values from this form to a perl script, parseDatabaseData_v2.pl, which get's data from a database and creates a JSON string of that data.

Then, I'd like to visualize this JSON data using a D3 graph. The following code using jquery ajax works, and returns JSON from the perl script as expected.

    var runFromDate = $('#runDateSelectBox1').val();
    var runToDate = $('#runDateSelectBox2').val();
    var barcode = $('#barcodesSelectBox').val();

    var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;

    // ajax command
    $.ajax({
        type: 'POST',
        url: './cgi-bin/parseDatabaseData_v2.pl',
        async: true,
        data: dataString,
        dataType: "json",
        success: function(data) {
              console.log("succesfully called script");

        }
    }); // end of ajax command

In the perl script I use cgi->param('runFromDate'); to get the posted parameters.

However, since I'm visualizing the data using NVD3's lineWithFocusChart I want to call the script using d3.xhr.

When I create the following d3.xhr request the script doesn't work (it get's called, but is unable to get the parameters).

    var runFromDate = document.getElementById("runDateSelectBox1").value;
    var runToDate = document.getElementById("runDateSelectBox2").value;
    var barcode = document.getElementById("barcodesSelectBox").value;

    var dataString = 'runFromDate='+ runFromDate + '&runToDate=' + runToDate + '&barcode=' + barcode;

    d3.xhr("./cgi-bin/parseDatabaseData_v2.pl")
      .header("Content-Type", "application/x-www-form-url-encoded")
      .post(dataString,function(error, data){
          console.log("succesfully called script");
              console.log(data);
      });

I've tried various ways of formatting the datastring including formatting it as JSON as explained at the D3 API Reference .

I'd be most grateful if someone was willing to help me with this.

Thanks,

Koen

You have a spurious hyphen between url and encoded!

Change

.header("Content-Type", "application/x-www-form-url-encoded")

to

.header("Content-Type", "application/x-www-form-urlencoded")

Looks like you are not the only one as this other recent answer shows. Seems the offending code has been in the d3.js wiki so I have updated it too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM