Google spreadsheet showing undefined values when submitting through an AJAX request - javascript

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;

Related

Getting null in return when executing Ajax request

Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.

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.

AJAX Post to store JSON with Python and javascript

I have been having problems with getting AJAX to post JSON correctly. The application is intended to be hosted on Google App Engine. But what I have does not post data.
Python
mainPage = """
<html>
html is included in my python file.
</html>
"""
class JSONInterface(webapp2.RequestHandler):
def post(self):
name =self.request.get('name')
nickname =self.request.get('nickname')
callback = self.request.get('callback')
if len(name) > 0 and len(nickname) >0:
newmsg = Entry(name=name, nickname=nickname)
newmsg.put()
if len(name)>0:
self.response.out.write(getJSONMessages(callback))
else:
self.response.out.write("something didnt work")
def get(self):
callback = self.request.get('callback')
self.response.out.write(getJSONMessages(callback))
This handler is meant to handle the Ajax calls from the web app. I am unsure if I need javascript to be associated with my main page in order to do so, as I haven't found information on it yet with my searches.
Javascript
$(document).ready( function() {
$("#post").bind('click', function(event){
var name = $("#name").val();
var nickname = $("#nickname").val();
postData = {name: name, nickname: nickname, callback: "newMessage"};
$.ajax({
type: "POST",
url: "http://localhost:27080/json",
data: postData,
dataType: "json",
done: function() {
// Clear out the posted message...
$("#nickname").val('');
},
fail: function(e) {
confirm("Error", e.message);
}
});
// prevent default posting of form (since we're making an Ajax call)...
event.preventDefault();
});
The Javascript for the post
Can someone advise me on how I could resolve the problem I am having. Thanks for the time and help.
Did you ask the same question yesterday and then delete it? I swear I just answered the same question.
You're not sending your data as a JSON string. If you want to send as JSON, you need to encode data as a JSON string, or else you're just sending it as a query string.
data: JSON.stringify(postdata),
HOWERVER, your request handler is actually processing the request properly as query string instead of JSON, so you probably don't want to do that.
For starters, the ajax call is pretty close. The full path
"http:://localhost:27080/json"
is not necessary, the relative path will work, but that is not the problem.
Your callback, as it stands, will work as 'success':
success: function(response) {
alert(response);
// Clear out the posted message...
$("#nickname").val('');
}
However, this callback is being phased out in favor of other methods. 'Done' should be chained like so:
$.ajax({
type: "POST",
url: "/json",
data: postData,
dataType: "json"
}).done(function(data){
console.log(data);
});
Also, there might be problems on the server. If you use some logging, you will see that the data is indeed being sent to the server.
import json ## we'll get to this below
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
name = self.request.get('name')
logging.info(name) ## will print the value of 'name'
Unless your python function getJSONMessages(callback) is returning a json object, your callback will not be called, even after you add the response parameter.
In your python code:
import json
import logging
class JSONInterface(webapp2.RequestHandler):
def post(self):
callback = self.request.get('callback')
logging.info(callback) # will print correctly
self.response.out.write(json.dumps(callback))
Using the json.dumps method encodes the passing object to json, which is what your ajax object is looking for.

Json request comes back 'UNDEFINED' using Wunderground API

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.

Get json data from Api

i am using the third party api for getting the Address on the basis of postcode . it returns the json data .
below is the api that i am calling but i am not sharing the datakey that i am using .
i am accessing this in jquery not using any server side scripting languages .
$.getJSON("http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key &postcode=CM129BY&callback=?", function () {
alert("aaa");
});
also using the other code like
// jQuery.ajax({
// type: 'GET',
// url: 'http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key&postcode=CM129BY?jsoncallback=?',
// dataType: 'json',
// success: function (data) {
// alert('success');
// }
// });
but i am getting the error
Error: invalid label
Source File: http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=datakey&postcode=CM129BY&callback=jQuery17209661092291729644_1335505434728&_=1335505437637
Line: 2, Column: 2
Source Code:
"found":"1",
please advice its very urgent
Thanks
naveen Kumar GUpta.
I think you may be missing any Quotes.Please check it once again.
I think the postcode you are searching is not found in the Database.
I got it.
It is the JSON result string is invalid as JSON, open the URL http://www.simplylookupadmin.co.uk/JSONservice/JSONSearchForAddress.aspx?datakey=data key &postcode=CM129BY&callback=? with web browser I got the content:
{
"found":"1",
"credits_display_text":"Cannot find FULL PAF license(credits or users)",
"accountadminpage":"https://www.simplylookupadmin.co.uk/WebAccountLogin.aspx?doid=1&coid=30&Pay=yes",
"errormessage":"Search denied! Cannot find FULL PAF license(credits or users)",
"maxresults":"0",
"recordcount":"0",
"records"]}
At the end of it, "]" is not needed.

Categories