Trouble with jQuery ajax - javascript

I am getting different errors in FF, Chrome and IE, but it all boils down there is an error with the data in $.ajax. Following is the code. Please go easy if I made a dumb mistake. I have spent hours researching this and can't figure it out. Any help appreciated.
Edited to include the error messages
FF Error message: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
Chrome Error message:Uncaught TypeError: Illegal invocation
IE9 Error message: SCRIPT65535: Argument not optional
Here is the code
mc.mc_data.click_tracking = [];
var sequence = 0;
var send_it;
// the container click event will record even extraneous clicks. need to change it to extending the jquery on click handler
$('#container').on('click', function(event) {
logClicks(event);
if(!send_it){
sendIt()
}
sequence++;
});
function sendIt(){
var tracking = mc.mc_data.click_tracking;
var url = '/ajax/click_trackin';
console.log("clicks["+sequence+"] "+$.isArray(tracking));
$.each(tracking, function(i,v){
console.log(i + v.innerText + " - " + v.sequence);
});
send_it = window.setInterval(function(){
$.ajax({
type: 'POST',
url: url,
data: {
clicks:tracking
},
success: function(response)
{
if(response.result.length<1){
console.log(response+ ': no response');
}else{
console.log(response);
tracking = mc.mc_data.click_tracks = [];
}
mc.mc_data.click_tracks = [];
clearInterval(send_it);
sendIt();
},
error: function(a, b, c){
console.log(a+" - " + b+" - "+ c);
clearInterval(send_it);
}
});
}, 5000);
}
//
function logClicks(e){
var temp_click = {
'business_id':window.mc.businessid,
'userid':window.mc.userid,
'timestamp':e.timeStamp,
'leg':window.mc.currentLeg,
'workflow': 'dummy data',
'sequence': sequence,
'type':e.type,
'target':e.target,
'parent': e.target.parentElement,
'id':e.target.id,
'class':e.className,
'innerText': $(e.target).text()
}
mc.mc_data.click_tracking.push(temp_click);
}

For data, you are meant to pass an object which will later be converted into a query string. You are passing the variable tracking, which contains stuff like e.target.parentElement, which is a DOM Node, containing really a lot of further properties (like other DOM Nodes!). The error can originate from either having problems converting a DOM Node into a query string, or creating a way too long query string. It would not make much sense to send a DOM Node to the server anyways.
Only send what is necessary and can be reasonably converted to a query string.

Related

Error looping through array after upload to server

I'm using jquery.csv.min.js to create an array based on a csv. This part works fine. However, when I try and parse that 2d array into sessionStorage items, I'm getting the dreaded "Uncaught TypeError: Cannot read property '0' of undefined". Here's what I have so far:
var stationData;
var station = "";
// Gather data from CSVs
$.ajax({
type: "GET",
url: "document.csv",
dataType: "text",
success: function(response){
stationData = $.csv.toArrays(response);
console.log(stationData); // This works and confirms the array in the console
console.log("Station Variables Success!");
}
});
// Parse array into sessionStorage items
$(document).ready(function() {
setTimeout(() => {
station = getUrlParameter('stn');
var v;
var varLen = stationData[0].length;
for(v = 0; v < varLen; v++) {
sessionStorage.setItem(stationData[0][v], stationData[station][v]); // Line producing error
console.log("Setting sessionStorage:" + stationData[0][v] + " to \"" + stationData[station][v] + "\"");
}}, 2000);
});
When I run this on my local XAMPP Apache server, I was getting the same TypeError until I included the setTimeout() to space it out a bit figuring it was trying to set the storage items before the array could finish loading and it worked. Just a 10ms timeout is enough to run it on my local server, which is why it's there. However, when I try and upload this to our live server, the TypeError comes back. I've tried increasing the timeout in increments upto 10000ms but it's still happening. I've googled around with no luck, so I'm hoping someone here might be able to share some insight!
It's throwing TypeError because you are trying to read the value of an asynchronous operation before its returned by the server.
Increasing the timeout is not the option.
You just need to slightly refactor your code like this -
$(document).ready(function() {
function fetchCSVFromServer(successCb, errorCb) {
return $.ajax({
type: "GET",
url: "document.csv",
dataType: "text"
})
.done(successCb)
.fail(errorCb);
}
var successCb = function(response){
// Parse array into sessionStorage items
var stationData = $.csv.toArrays(response);
console.log(stationData); // This works and confirms the array in the console
console.log("Station Variables Success!");
setTimeout(() => {
var station = getUrlParameter('stn');
var varLen = stationData[0].length;
for(let v = 0; v < varLen; v++) {
sessionStorage.setItem(stationData[0][v], stationData[station][v]); // Line producing error
console.log("Setting sessionStorage:" + stationData[0][v] + " to \"" + stationData[station][v] + "\"");
}
}, 2000);
};
var errorCb = function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR);
};
fetchCSVFromServer(successCb, errorCb);
});
This code has 2 parts to it, first making the XHR using the $.ajax in the fetchCSVFromServer function and the second synchronizing the code flow which follows the asynchronous XHR call which is written in the successCb callback.
The trick is to synchronize the callback to run only after the server has sent its response in the .done callback.
This is a well known and a solved problem, for more details refer this question.

Another Javascript callback issue/example

I've read a good bit about callbacks, and while I use them for click events and similar, I'm using them without fully understanding them.
I have a simple web app with 3 or 4 html pages, each with its own js page.
I have some global functions that I've placed in a new js page which is referenced by each html page that needs it. I'm using this file, word_background.js, to hold functions that are lengthy and used by multiple pages.
pullLibrary is a function, residing in word_background.js, that pulls from my db and processes the results.
I want to call pullLibrary from webpageOne.html, make sure it completes, then do more processing in webpageOne.js.
In webpageOne.js I have the following - trying to call pullLibrary and, once it is complete, use the results for further work in webpageOne.js.
The code executes pullLibrary (in word_background.js) but doesn't "return" to webpageOne.js to continue processing.
I'm assuming I'm missing some critical, essential aspect to callbacks...
I just want to run the pullLibrary function (which has ajax calls etc) and, once it is complete, continue with my page setup.
Any explanation/correction appreciated.
This code is in webpageOne.js:
pullLibrary(function(){
console.log('Now processing library...');
processLibrary();
updateArrays();
//Do a bunch more stuff
});
----- UPDATE -----
Thank you for the comments...which I think are illuminating my broken mental model for how this should work.
pullLibrary is an ajax function - it pulls from a database and stuffs the results into an array and localStorage.
My expectation is that I can call pullLibrary and, when it is complete, the callback code (in this case anonymous function) will run.
function pullLibrary(){ //Values passed from startup() if no data is local
//Pull data from database and create basic LIBRARY array for further processing in processLibrary sub
console.log("Starting to pull library array in background.js..." + "User: " + localStorage.userID + " License: " + localStorage.licType);
var url1 = baseURL + 'accessComments3.php';
var url2 = '&UserID=' + localStorage.userID + '&LicType=' + localStorage.licType;
//Need global index to produce unique IDs
var idIndex = 0;
var index = 0;
$.ajax({
type: "POST",
url: url1,
data: url2,
// dataType: 'text',
dataType: 'json',
success: function(result){
// success: function(responseJSON){
arrLibrary = result; //store for use on this page
localStorage.library = JSON.stringify(result); //Store for use elsewhere
console.log('Saving to global variable: ') + console.log(arrLibrary);
//Now mark last update to both sync storage and local storage so access from other browsers will know to pull data from server or just use local arrays (to save resources)
var timeStamp = Date.now();
var temp = {};
temp['lastSave'] = timeStamp;
// chrome.storage.sync.set(temp, function() {
console.log('Settings saved');
localStorage.lastSync = timeStamp;
console.log('Last update: ' + localStorage.lastSync);
//Store Group List
var arrComGroups = $.map(arrLibrary, function(g){return g.commentGroup});
// console.log('List of comment groups array: ') + console.log(arrComGroups);
arrComGroups = jQuery.unique( arrComGroups ); //remove dupes
// console.log('Unique comment groups array: ') + console.log(arrComGroups);
localStorage.groupList = JSON.stringify(arrComGroups); //Store list of Comment Groups
//Create individual arrays for each Comment Groups
$.each(arrComGroups,function(i,gName){ //Cycle through each group of Comments
var arrTempGroup = []; //to hold an array for one comment group
arrTempGroup = $.grep(arrLibrary, function (row, i){
return row.commentGroup == gName;
});
//Store string version of each Comment Array
window.localStorage['group_' + gName] = JSON.stringify(arrTempGroup);
console.log('Creating context menu GROUPS: ' + gName);
});
// processLibrary(arrLibrary); //We've pulled the array with all comments - now hand off to processor
}, //End Success
error: function(xhr, status, error) {
alert("Unable to load your library from 11trees' server. Check your internet connection?");
// var err = eval("(" + xhr.responseText + ")");
// console.log('Error message: ' + err.Message);
}
}); //End ajax
}
Okay, there are tons of "here's how callbacks work" posts all over the internet...but I could never get a crystal clear example for the simplest of cases.
Is the following accurate?
We have two javascript files, one.js and two.js.
In one.js we have a function - lets call it apple() - that includes an Ajax call.
two.js does a lot of processing and listening to a particular html page. It needs data from the apple() ajax call. Other pages are going to use apple(), also, so we don't want to just put it in two.js.
Here's how I now understand callbacks:
one.js:
function apple(callback_function_name){
$.ajax({
type: "POST",
url: url1,
data: url2,
dataType: 'json',
success: function(result){
//apple processing of result
callback_function_name(); //This is the important part - whatever function was passed from two.js
}, //End Success
error: function(xhr, status, error) {
}
}); //End ajax
} //End apple function
** two.js **
This js file has all kinds of listeners etc.
$(document).ready(function () {
apple(function(apple_callback){
//all kinds of stuff that depends on the ajax call completing
//note that we've passed "apple_callback" as the function callback name...which is stored in the apple function as "callback_function_name".
//When the ajax call is successful, the callback - in this case, the function in two.js, will be called back...and the additional code will run
//So the function apple can be called by all sorts of other functions...as long as they include a function name that is passed. Like apple(anothercallback){} and apple(thirdcallback){}
}); //End apple function
}); //End Document.Ready

JavaScript missing parametar

I am coding a block type plugin for Moodle and have this JS code that gives me problems. Since I'm not very familiar with JS and JSON I can't deduce what is the problem.
My code uses this function to add custom action to action link which issues ajax call to php file ...
This is the code:
function block_helpdesk_sendemail(e) {
e.preventDefault();
Y.log('Enetered method');
var sess = {'sesskey=':M.cfg.sesskey};
Y.log(sess);
var ioconfig = {
method: 'GET',
data: {'sesskey=':M.cfg.sesskey},
on: {
success: function (o, response) {
//OK
var data;
try {
data = Y.JSON.parse(response.responseText);
Y.log("RAW JSON DATA: " + data);
} catch (e) {
alert("JSON Parse failed!");
Y.log("JSON Parse failed!");
return;
}
if (data.result) {
alert('Result is OK!');
Y.log('Success');
}
},
failure: function (o, response) {
alert('Not OK!');
Y.log('Failure');
}
}
};
Y.io(M.cfg.wwwroot + '/blocks/helpdesk/sendmail.php', ioconfig);
}
The code pauses in debugger at return line:
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
I've put M.cfg.sesskey and data variables on watch. I can see sesskey data shown, but data variable shows like this:
data: Object
debuginfo: "Error code: missingparam"
error: "A required parameter (sesskey) was missing"
reproductionlink: "http://localhost:8888/moodle/"
stacktrace: "* line 463 of /lib/setuplib.php: moodle_exception thrown
* line 545 of /lib/moodlelib.php: call to print_error()
* line 70 of /lib/sessionlib.php: call to required_param()
* line 7 of /blocks/helpdesk/sendmail.php: call to confirm_sesskey()"
And this is what my logs show:
Enetered method
Object {sesskey=: "J5iSJS7G99"}
RAW JSON DATA: [object Object]
As #Collett89 said, the JSON definition is wrong. His tip might work, but if you need strict JSON data then code the key as string (with quotes):
var sess = {'sesskey': M.cfg.sesskey};
or
var sess = {"sesskey": M.cfg.sesskey};
See definition in Wikipedia
your declaring sesskey in a bizarre way.
try replacing data: {'sesskey=':M.cfg.sesskey},
with data: {sesskey: M.cfg.sesskey},
it might be worth you reading through this
mdn link for javascript objects.
You usually need to JSON.stringify() the objects sent via ajax.
which may be part of the problem.

JavaScript works fine in any browser but Firefox?

Ok this is my JavaScript
<script type="text/javascript" language="JavaScript">
function manageCart(task,item) {
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
}
function reportError(request) {
$F('cartResult') = "An error occurred";
}
And this is HTML
<p>
Add to cart
</p>
This script doesn't work in Firefox, I've ran a few Firefox JS debuggers but they displayed no errors. I'm not so good in JavaScript so please help me if you can :)
This script actually uses Prototype library if it will make things clearer.
For this type of Ajax call do not use Ajax.Updater as that is designed to update a specific element with the contents of the ajax response. I believe that you want to just make a simple single ajax call so using Ajax.Request would be what you want to use.
Original Code using Ajax.Updater
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Updater(
{success: ''},
url,
{method: 'get', parameters: params, onFailure: reportError});
Code using Ajax.Request
var url = 'managecart.php';
var params = 'task=' + task + '&item=' + item;
var ajax = new Ajax.Request(url,
{
method: 'get',
parameters: params,
onFailure: reportError,
onSuccess: function(){
console.log('It Worked');
}
});
I put a success handler in this call just to confirm that it worked for you - and it should output to your console. You can remove it or comment the console.log() when you are satisfied it works
I've spent more time in FireBug and found the error.
Timestamp: 03.04.2013 10:36:38
Error: ReferenceError: invalid assignment left-hand side
Source File: http://www.example.com/index.php
Line: 413, Column: 18
Source Code:
('cartResult') = "An error occurred";
Firefox desperately wanted for the statement to look like this:
('cartResult') == "An error occurred";

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources