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.
Related
I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I am using graphite to get stats and want to render a justgage gauge for a variable. Graphite can spit out values using either json:
[{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}]
or raw:
snmp.ssbSubstation.realEnergy.1,1417540860,1417540920,60|4511552439.0
That's the entire one line of the source returned depending on if you specify either json or raw. The url is formatted like http://<graphite server>/render?target=snmp.ssbSubstation.realEnergy.1&format=raw&from=-1min
Either way, I'd like to grab 4511552439.0 and set it as the value for the gauge and render in in a html panel in grafana. Is there a very simple way to do this?
You can do this with an JSONP ajax request. Please have a look at the example below (as a starting point for your app).
You can find the same demo also as jsFiddle here.
Maybe the data access could be done better. The two dimensional access looks a bit strange but it works.
I've used mocky.io to simulate your data.
// data format [{"target": "snmp.ssbSubstation.realEnergy.1", "datapoints": [[4511552439.0, 1417540920]]}]
// http://www.mocky.io/v2/547df7d558eb49190856a759
(function ($) {
var url = 'http://www.mocky.io/v2/547df7d558eb49190856a759'; // mocky.io demo source
var jsonCallback = function (data) {
var gauge = data[0].datapoints[0][0];
console.log(gauge);
$('#data').html(JSON.stringify(data, null, 2));
$("</p>").text('value for gauge ' + gauge).appendTo('#data');
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>
I have set up a function and a callback to retrieve some data regarding weather alerts. For some reason the data comes back as 'UNDEFINED'. I'm fetching the data through json although I would prefer to... fetch XML and callback json, however fetch and return json is fine.
Below is my code, but I have put it into a jsfiddle to make it easier to read.
http://jsfiddle.net/seversides/G7Wr8/
Javascript
$(function () {
// Specify the location and Api key
var apiKey = 'myapikey';
var location = 'zmw:00000.1.16172';
// Run the query (pull data from feed)
var url = 'http://api.wunderground.com/api/' + apiKey + '/alerts/q/' + location + '.json';
window['wCallback_3'] = function(data) {
// Get any weather alerts
var info = data.alerts;
// Warning level and color
$('#wWarning .wLevel').append('<TD>' + info.wtype_meteoalarm + '</TD>');
$('#wWarning .wColor').append('<TD>' + info.level_meteoalarm_name + '</TD>');
};
// Callback
$.ajax({
url: url,
dataType: 'jsonp',
contentType: "application/json",
cache: true,
jsonpCallback: 'wCallback_3'
});
});
HTML
<div id="wWarning">
<table class="wBox">
<h1 class="wLevel"></h1>
<h1 class="wColor"></h1>
</table>
</div>
When I run the code it displays the data as UNDEFINED. Why isn't it retuning the right data?
The "UNDEFINED" is referring to the callback function, because it doesn't exist as part of the request.
You're telling it that you want the output to be in JSONP in the line:
dataType: 'jsonp',
But that API is responding with JSON (excluding a callback).
In order to access it cross domain with JSONP (which is the right protocol for what you're looking for), you need to use the AutoComplete API:
http://www.wunderground.com/weather/api/d/docs?d=autocomplete-api&MR=1
Then, you set the callback with cb=myCallback in the GET string:
http://autocomplete.wunderground.com/aq?format=JSON&query=Anchorage&cb=myCallback
The problem is, I don't see any way in that API to use the zmw= values, so you may need a workaround for the area of interest.
When I put ":))" in my textarea and send via ajax, it inputs into the database a value like
"jQuery172039628539560362697_1345324072488", how can I stop this? Should I parse my text in some way in javascript first to make it recognize it's text, and not part of the javascript coding?
This is how i get my text
var message = $("textarea.message_thread").val();
var dataString = 'id=' + id + '&message=' + message;
// make ajax call
sending with
$.ajax(
{
type: "POST",
url: "/inbox/instsend",
data: dataString,
dataType: 'json',
success: function(results) {}
}
See the comments under the question; the problem is that what has been submitted in dataString is actually a url-encoded string, and not a JSON-izable or JSON literal variable.
Hence:
dataString = {id: id, message: message};
Will fix this problem, here. jQuery will take that object-initialized variable and encode it for you to JSON.
This is done automatically by jQuery when you're using JSONP for cross-domain AJAX calls. It should be sending this string as the value of the callback parameter.
You need to sanitise the input and escape any control codes - e.g. : and )
Since you are doing POST here. This would work
var dataString = '{'+'id:' + id + 'message:' + message +'}'