I can't seem to figure out this problem where the below code works when the "for loop" is disabled, and the attributes "locations" and "startAddress" are just simple strings. But if they are not, I am getting a "this is undefined" error when the ajax post request is submitted. Do you have any ideas why would this be? Any leads would be appreciated.
// create an event handler for the save route button
$("#saveRouteButton").click(function(){
var saveRouteName = $("#saveRouteNameField").val();
if (!saveRouteName) {
alert("Please supply a proper name to be submitted to the database");
} else {
var routeLength = directionsDisplay.getDirections().routes[0].legs.length;
var returnRoute = {
alias: null,
locations : [], // make this a string - it works!
startAddresses : [], // make this a string - it works!
};
// disable this loop - it works!
for (var i = 0; i < routeLength; i++){
returnRoute.locations[i] = directionsDisplay.getDirections().routes[0].legs[i].start_location
returnRoute.startAddresses[i] = directionsDisplay.getDirections().routes[0].legs[i].start_address
};
route_info = returnRoute;
route_info.alias = saveRouteName;
//test to see if the variables are set, they are!
alert(route_info.alias);
alert(route_info.locations);
alert($.isPlainObject(route_info))
$.ajax({
url: "save_route/",
type: "POST",
data : route_info,
success: function(data){
if (data != "None") {
$("#savedRoutesList").append('<li class="savedRoutesListItem">'
+ data + '</li>');
}
else {alert("You need to enter a route name");}
}
});
}
return false;
});
the error originates from the : google maps main js - line 13
Thanks!
Just check the route Length value,whether it is giving correct value or not?
Related
I'm trying to do a kind of purchase request app built off of a Google Spreadsheet. For awhile, (like the whole time I've been working on this), my code was working. For each line in the order sheet, it would loop through the values, fill in the Google form inputs, submit the form, then start the process again.
Yesterday I noticed it was submitting each line twice submitting the first line once, second line twice, third line three times, and so on. Then it stopped submitting at all. Then it started again submitting multiple times, then stopped. Could you guys please take a look at my code and tell me what I'm doing wrong?
function formSubmit() {
//Create unique ID (number of milliseconds since 1/1/70)
var d = new Date();
var n = d.getTime();
var uniqueID = n.toString();
//Loop through the lines of the order, fill in the values, submit
$('.orderline').each(function(i, obj) {
//Stop the default redirect so we can submit multiple times
$('#ss-form').submit(function(e) {
e.preventDefault();
$.ajax({
url: "https://docs.google.com/a/vt.edu/forms/d/e/1FAIpQLSf77MuDLeqyPbuDCBcpVagi6-hdiUpgZtr0CbuJ3kO-vXPswg/formResponse",
data: $(this).serialize(),
type: "POST",
dataType: "jsonp",
success: function(data) {
console.log("Submission successful");
},
error: function(xhr, status, error) {
console.log("Submission failed: " + error);
},
});
});
$("#entry_1725077600").val(uniqueID);
var name = $("#personname").val();
var email = $("#personemail").val();
$("#entry_1352722479").val(name);
$("#entry_1024015951").val(email);
//etc.
$("#ss-form").submit();
});
The form is public if you guys want to take a look. Note I have two forms submitting at once on the same click; the one above is for the items in the order, the second one is for metadata about the order.
EDIT: formSubmit() is being called from a second function that uploads files to Google Drive (if there's a better way to do this please do let me know):
if(document.getElementById('fUpload').value!='') {
var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var uploadObj = $("[id$=fUpload]");
var file = uploadObj.prop("files")[0];
var metadata = {
'title': file.name,
'description': " ",
'mimeType': file.type || 'application/octet-stream',
"parents": [{
"kind": "drive#file",
"id": "0B5zM5ktmwJ2fN0c3RWYxWC1rUzQ"
}]
};
var arrayBufferView = new Uint8Array(file);
var uploadData = new Blob(arrayBufferView, {type: file.type || 'application/octet-stream'});
try{
var uploader =new MediaUploader({
file: file,
token: oauthToken,
metadata: metadata,
params: {
convert:false,
ocr: false
}
});
uploader.upload();
} catch(exc){
showErrorMessage("Error: " + exc);
$("#fUpload").val(" ");
}
} else {
formSubmit();
}
});
And then for successful responses:
MediaUploader.prototype.onContentUploadSuccess_ = function (e) {
if (e.target.status == 200 || e.target.status == 201) {
var response = e.target.response; //Get the response body
var parsed = JSON.parse(response); //Parse the response body to JS object
var fileID = parsed.id; //Get the file ID from the response
var linkToFile = "https://drive.google.com/open?id=" + fileID;
$("#entry_1703377267").val(linkToFile); //Add the file ID as the value of the file ID input field
formSubmit(); //Run the rest of the form submit functions
this.onComplete(e.target.response);
} else if (e.target.status == 308) {
this.extractRange_(e.target);
this.retryHandler.reset();
this.sendFile_();
}
};
EDIT 2: I never see success or error messages in the console. Also, it looks like things aren't being submitted twice, they're being submitted in a pattern: first item once, second item twice, third item three times, etc.
In the interactive shell of Django, I got
In [1]: contract = Contract.objects.get(pk=2)
In [2]: contract
Out[2]: <Contract: Contract with David Bouchard (en)>
In [3]: contract.request.customer.convert_fax_number
Out[3]: ''
In a JavaScript function, I created a variable var fax_number = "{{ contract.request.customer.convert_fax_number }}"; and create the following if condition function
if (fax_number == '') {
alert('Please, attach the fax number to your profile');
return;
}
I put a breakpoint of the first line of that code. Hence, I know that the compiler stopped on this line, but it has never executed the statement of that if condition.
Here is the whole function :
(function($){
var bindEvents = function(node){
$('.btn-fax', node).bind('click', function(e){
e.preventDefault();
var data = {};
var fax_number = "{{ contract.request.customer.convert_fax_number }}";
$.ajax({
url : $(this).attr('href'),
type: 'POST',
data : data,
success: function(data, textStatus, jqXHR) {
if (data.success) {
if (data.redirect_to) {
window.location.href = data.redirect_to;
}
else if (data.reload) {
window.location.reload();
}
}
else {
alert('Error! See console for details :(');
console.error(textStatus, data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (fax_number == '') {
alert('Please, attach the fax number to your profile');
return;
}
console.error(textStatus, errorThrown);
}
});
return false;
});
};
and here the modification I did to convert unicode string to simple string :
#property
def convert_fax_number(self):
fax = self.fax
return unicodedata.normalize('NFKD', fax).encode('ascii','ignore')
It's not working even it the output of convert_fax_number is a simple empty string ''. How could I fix it?
Thanks in advance!
First of remember to use triple equals === when comparing strings to make sure that it's not doing weird asumptions.
Can you do a console.log('whatever') in the line on top of the if statement just to make sure that it's executing the error function? although I know that you said:
I know that the compiler stopped on this line
It's better to be completely sure.
Then, you should try with a console.log(fax_number == '') and console.log(fax_number === '') to see what's happening just below the variable declaration. Let me know what you find out.
This code is not being rendered by Django - presumably it is in a separate JavaScript file, not in a Django template. You'll need to pass the value into your JS from the actual template itself.
Trying to create a jade version to do autofill city state from
https://www.zipcodeapi.com/Examples
script(type='text/javascript').
//<![CDATA[
$(function() {
// IMPORTANT: Fill in your client key
console.log("thing")
var clientKey = "js-9qZHzu2Flc59Eq5rx10JdKERovBlJp3TQ3ApyC4TOa3tA8U7aVRnFwf41RpLgtE7";
var cache = {};
var container = $("#example1");
var errorDiv = container.find("div.text-error");
/** Handle successful response */
function handleResp(data)
{
// Check for error
if (data.error_msg)
errorDiv.text(data.error_msg);
else if ("city" in data)
{
// Set city and state
container.find("input[name='city']").val(data.city);
console.log(data.city);
container.find("input[name='state']").val(data.state);
}
}
// Set up event handlers
container.find("input[name='zipcode']").on("keyup change", function() {
// Get zip code
var zipcode = $(this).val().substring(0, 5);
if (zipcode.length == 5 && /^[0-9]+$/.test(zipcode))
{
// Clear error
errorDiv.empty();
// Check cache
if (zipcode in cache)
{
handleResp(cache[zipcode]);
}
else
{
//Build url
var url = "https://www.zipcodeapi.com/rest/"+clientKey+"/info.json/" + zipcode + "/radians";
// Make AJAX request
$.ajax({
"url": url,
"dataType": "json"
}).done(function(data) {
handleResp(data);
// Store in cache
cache[zipcode] = data;
}).fail(function(data) {
if (data.responseText && (json = $.parseJSON(data.responseText)))
{
// Store in cache
cache[zipcode] = json;
// Check for error
if (json.error_msg)
errorDiv.text(json.error_msg);
}
else
errorDiv.text('Request failed.');
});
}
}
}).trigger("change");
});
//]]>
div#example1
label Zip:
input(type='text', name='zipcode', value='')
label City:
input(type='text', name='city', value='')
label State:
input(type='text', name='state', value='')
I am getting the following error and not sure why this is erroring out:
$ is not defined
Any ideas? This is a conversion from the original javascript so I am not sure what I am doing wrong in the conversion. Thanks!
Always listen to your error messages; they're usually right. $ isn't defined. Have you included jQuery (just guessing) in a higher-level template, of which this is a subtemplate? If not, $ is undefined is a valid message from the javascript interpreter.
I'm trying to add both Facebook and Twitter share counters together, however all my efforts have failed.
<script>
tweets = 0;
function getTwitterCount(url){
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
return true;
});
}
var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: function(data) {
showCount(data);
}
});
var fbshares = 0;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
}
var TotalShares = tweets + fbshares;
$('#total-share-count').html(TotalShares);
</script>
I could really do with some outside insight as I've been working crazy to get this website up and running ASAP and I'm probably overlooking the most obvious of things...
Console Log Reads:
Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().
However despite this message, the Facebook and Twitter counters are working 100%, I just cannot get them to add together.
Best Regards,
Tim
Here's a solution:
var tweets;
function getTwitterCount(url) {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
tweets = data.count;
$('#twitterCount').html(tweets);
showTotal();
});
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: showCount
});
var fbshares;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
showTotal();
}
function showTotal() {
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
Basically showTotal attempts to sum the two values after each callback. When both values are defined, it will place the sum into the HTML.
When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..