Ajax error on my JSON calls - fullcalendar

I just upgraded to fullcalendar 1.5.1 and updated jQuery to 1.5.2 ...
Here is my code:
$('#calendar_container').fullCalendar({
eventSources: [
{
url: '/myapp/calendar/TestJSON.jsp',
type : 'POST',
error: function() {
alert('there was an error while fetching events!');
}
}
]
)}
Anyway my JSON feeds seem to have broken, jQuery is getting some sort of ajax error. With Firebug I see that the call being made is:
http://localhost:8080/myapp/calendar/TestJSON.jsp?callback=jQuery1520173438877011995_1303227625166
The error alert pops up and if I examine Firebug I see an 'ajaxError'. Now the JSON is coming through (I can see it in the Firebug response). The statusText is 'parsererror'.
I have already validated the JSON with JSONLint. I have even tried 'hard coding' the JSON. The callback parameter had me worried so I added jsonp: false to the event source but while I was able to eliminate the callback parameter the error persisted. I also tried changing the type to gET instead of POST, but to no avail.
Here is the hardcoded JSON from TestJSON.jsp:
[{"id":111,"title":"Event1","start":"2011-04-10"},{"id":222,"title":"Event2","start":"2011-04-20","end":"2011-04-22"}]
Update
I figured it out, it was a plugin conflict between jQuery 1.5.2 with jquery validation, but there is a fix here:
https://github.com/jaubourg/jquery-validation/raw/master/jquery.validate.min.js

Related

Semantic-ui Form Validation basic setup

I'm new to semantic-ui and to javascript as well, so please bear with me. I have a basic form that I'm trying to get working with the built-in form validation semantic-ui provides. This form is part of a web app using node, express, and pug. The structure of the specific form (view) I'm working on looks like this:
Sorry for using a picture but I'm trying to keep this high-level.
As you can see, I have a form (with I believe the requisite classes), a submit button and a script block at the end, which is where I've got the validation code at the moment.
Here's my validation code such as it is:
$('#new-password-form').form({
on: 'blur',
fields: {
password: {
identifier : 'password',
rules: [
{
type : 'empty',
prompt: 'You must enter a password'
},
{
type : 'regExp[/^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})/]',
prompt: 'Your password must be at least 8 characters long, and contain upper and lower case characters, digit(s), and symbol(s)'
}
]
}
}
}, {
onSuccess : function(e){
e.preventDefault();
}
});
The trouble is, validation isn't working. When I click the submit button the form attempts a regular get submit and it's as if the javascript isn't even there somehow. Yet it is there. Node is showing everything is properly fetched and loaded by the browser. Inspecting the rendered HTML shows everything is there, and I see no errors in the console. The page appears to have loaded all the requisite files successfully as follows:
GET /enroll/new 200 31.281 ms - 2652
GET /stylesheets/style.css 200 0.859 ms - 735
GET /jquery/jquery.js 200 1.491 ms - 280364
GET /ui/semantic.min.css 200 1.508 ms - 628536
GET /ui/semantic.min.js 200 2.070 ms - 275709
GET /images/amm.png 200 2.068 ms - 25415
GET /ui/semantic.min.css 200 0.418 ms - 628536
GET /favicon.ico 404 9.768 ms - 1499
So what gives? Can someone tell me what I'm doing wrong? Happy to provide more detail if what I have here isn't enough.
Update:
I extracted the HTML to a flat file, and relinked the assets (png, js, css) so there is no server involved at all. The page loads in the browser just fine. I get the exact same behavior (nothing happens when submit is clicked except the page reloads with get parameters—default non-js behavior AFAIK). It's making me think something is wrong with jQuery or javascript itself.
Well I found the problem... a missing ',' at the end of the "type:" row (regExp[/^(?=.*[a-z])...).
Now validation is working for both the static file, and the server version. For what it's worth coming from other languages where this is not an issue, javascript's ubiquitous use of inline functions and data structures nested multiple levels deep is something I've had a very hard time getting used to. Makes it all too easy to miss some critical little piece.
I guess let this be another example of a basic setup of semantic-ui that works... so long as you don't leave off any commas. (I fixed the code above for those that might want to copy/paste)

$http returning error response NULL on first call after launch (ionic) everytime, but after subsequent http post its ok

Whenever I launch my app, and click on login on the first few tries, the login will attempt a POST http to the server. However $http always (everytime) returns NULL on first try. sometimes after several few tries still NULL if done fast. But subsequently, its all ok.
I dont get it, why is $http returning error response NULL initially ??
Here is my login controller doing the http post
Login Controller (LoginCtrl)
https://gist.github.com/anonymous/771194bc5815e4ccdf38b57d6158853f
var req = {
method: 'POST',
url: baseURL,
data: postObject,
//timeout: 5000
};
err is NULL here:
}).error(function(err) {
I dont know if it is CORS but I'ved got this set in config.xml
<access origin="*" />
my config.xml
https://gist.github.com/anonymous/b2df3a857338d14ec3fcd6dda776e212
Any ideas ?
Im using ionic 1.7.14
on device iOS 9.3.1
UPDATE
I'ved put the problem code here. can logout first to goto login screen. enter in anything in username/password field, click login once failed, second or third try will be success.
https://github.com/axilaris/ionic_null_http_problem
some troubleshooting so far: i noticed the http post request is called twice. not sure why.
UPDATED the code using $http.post.then but still has the same effect
$http.post(baseURL, postObject).then(function successCallback(response)
response has NULL data --> Object {data: null, status: 0, config: Object, statusText: ""}
It is hard to diagnose having the above details only.
However the problem could be that your handler (login function) is triggered before digest cycle finished updating $scope.data.username and $scope.data.password and for the first tries it sends empty values for those to the server and works fine later.
You can run Safari web inspector to see what is sent to the server to prove this.
The fix may depend on how your view/template is coded. Can you please share it? Or, ideally, create a working sample at http://play.ionic.io/
Another option to fix could be to try to wrap your code related to http request into
$timeout(function() {
// your code goes here
});
or, consider using .$applyAsync() (see the docs for details)
This might help to fix the problem
You are probably getting this inconsistent behavior as you are using the 'success' promise method instead of 'then' (note that use of the success method has now been deprecated).
The key differences between these two methods are:
then() - full power of the promise API but slightly more verbose
success() - doesn't return a promise but offeres slightly more convienient syntax
as highlighted in this answer.
Hence in your scenario, instead of using 'success':
var req = {
method: 'POST',
url: baseURL + 'session/login',
data: postObject,
//timeout: 5000
};
$http(req).success(function(resp) {...
use 'then' along with angular's post shortcut method (you don't have to use this shortcut method, but I think it makes the code more succinct) e.g.:
$http.post(baseURL + 'session/login', postObject).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Using 'then' returns a promise resolved with a value returned from a callback, so it should give you a consistently valid result.
it was a timeout in app.js that caused it. was set to 1 second which gives it it arbitrary success rate.
config.timeout = 1000;

CasperJS Loading resource failed with status=fail (HTTP 200)

After setting "Any Date", output format, and clicking a link on a bank site, some javascript runs in the background, download.qfx is called with a GET request, and then a CSV file is downloaded.
Unfortunately, when I try to replicate these actions with CasperJS the call to download.qfx fails and I get an incomplete CSV file (It has worked once or twice, but I can't figure out why). I've looked at all of the stack overflow questions referencing this error and found no solution.
I call the following piece of a script with:
casperjs --ssl-protocol=any --ignore-ssl-errors=true casper.js
Here is the partial script:
// Call download functions for transaction data
casper.then(function(){
//this.click(x("//a[contains(text(), 'Download')]")); // 'clicking' the link or calling the subsequent javascript both show the same result
this.evaluate(function(){
urchinTracker('/download_transactions/continue');
submitForm('download');
return false;
});
});
// Download transaction data
casper.then(function(){
casper.waitForResource("download.qfx", function(resource) {
this.download(resource.url, 'temp/' + userid + '.csv');
});
});
casper.run();
I've attached the debug log, because it's strange that the page seems to 'navigate' to pages after clicking the link, because in the browser doesn't do that when you click the link, but maybe I'm misunderstanding something.
I'm using casperjs 1.0.0 and phantomjs 1.9.8

Async testing with vows using the http.get library in Node.js

I'm having a doozie of a time trying to get a basic http test to work with vows.
I think I've followed the async example from vows http://vowsjs.org/#-writing-asynchronous-tests and substitued the appropriate calls, but I must be missing something.
The test code looks like this:
var http = require('http'),
vows = require('vows'),
assert = require('assert');
vows.describe("homepage").addBatch({
"Get the home page": {
topic: function() {
http.get({'host': "127.0.0.1", 'port': 5000, 'path': '/'}, this.callback);
},
'should respond with 200 OK': function(res) {
assert.equal(res.statusCode, 200);
}
}
}).export(module);
I get the following error when I try to run the test for this:
/Users/<home_folder>/node_modules/vows/lib/vows.js:80
rrored', { type: 'promise', error: err.stack || err.message || JSON.stringify(
^
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at EventEmitter.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows.js:80:90)
at EventEmitter.emit (events.js:64:17)
at /Users/<home_folder>/node_modules/vows/lib/vows/context.js:31:52
at ClientRequest.<anonymous> (/Users/<home_folder>/node_modules/vows/lib/vows/context.js:46:29)
at ClientRequest.g (events.js:143:14)
at ClientRequest.emit (events.js:64:17)
at HTTPParser.onIncoming (http.js:1349:9)
at HTTPParser.onHeadersComplete (http.js:108:31)
at Socket.ondata (http.js:1226:22)
I can get a simple http example to work on it's own. I can get the vows example to work on it's own but I can't combine them for whatever reason. I'd really appreciate some help here. I've been trying to get this to work for a while now (including much googling).
UPDATE:
Apparently adding an error argument to the call back solves this problem, thanks to help from Alexis Sellier (creator of vows).
But I have no idea why. When writing out the http lib example on it's own no error argument is required. I can't find any documentation in vows to indicate why it's needed so I'm at a bit of a loss.
My new question is why is the error argument required when using the http lib in vows?
After checking vow's source code, I think I know why. Vows always ensure that when you call this.callback, the resulting receiver function's first argument is always an error object. Vows interpret the callbacks by these rules:
If the first argument of your originating callback is a boolean, use that to determine whether or not to append an error object to the receiving callback (e.g. path.exists(boolean) will emit callback(error, exists) instead)
If the first argument is an object, assume it's an error object and use that to determine whether to add the originating callback to the "error" or "success" list. The reason this list exists is to support promise based tests I guess?
While I can't confirm the above is correct, my experience is that vows' async style is made to support node-styled callbacks (e.g. err as the first arg), and 3rd party npm modules that don't conform to this standard will be hard to test.
Please don't take my answer as gospel, as this is my own experience. Another gotcha is when you have async operations inside the function that you want to test - unless you provide a callback, vows won't be able to handle it properly.
Personally, I think vows still make it hard to test async code. I wish it had some waitFor() or until() flow control functions though.
My suggestion? When dealing with async code, use Step. Don't let vows control your flow.
It is actually missing in the documentations which is still a bit short. But you can get a glimpse of it here in this page :
'when peeled *asynchronously*': {
topic: function (banana) {
banana.peel(this.callback);
},
'results in a `PeeledBanana`': function (err, result) {
assert.instanceOf (result, PeeledBanana);
}
}
As it was said by Morten Siebuhr and Ruben Tan, this is how vows works and that is why it works like that.

How would you handle errors when using jQuery.ajax()?

When using jQuery's ajax method to submit form data, what is the best way to handle errors?
This is an example of what a call might look like:
$.ajax({
url: "userCreation.ashx",
data: { u:userName, p:password, e:email },
type: "POST",
beforeSend: function(){disableSubmitButton();},
complete: function(){enableSubmitButton();},
error: function(xhr, statusText, errorThrown){
// Work out what the error was and display the appropriate message
},
success: function(data){
displayUserCreatedMessage();
refreshUserList();
}
});
The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens.
My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined.
I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard .net error page.
I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages.
Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take?
How do you handle these situations?
For debugging, I usually just create an element (in the case below: <div id="error"></div>) on the page and write the XmlHttpRequest to it:
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#error").html(XMLHttpRequest.status + "\n<hr />" + XMLHttpRequest.responseText);
}
Then you can see the types of errors that are occurring and capture them correctly:
if (XMLHttpRequest.status === 404) // display some page not found error
if (XMLHttpRequest.status === 500) // display some server error
In your ashx, can you throw a new exception (e.g "Invalid User" etc.) and then just parse that out of the XMLHttpRequest.responseText? For me when I get an error the XMLHttpRequest.responseText isn't the standard Asp.Net error page, it's a JSON object containing the error like this:
{
"Message":"Index was out of range. Must be non-negative and less than the size of the collection.\r\n
Parameter name: index",
"StackTrace":" at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)\r\n
at etc...",
"ExceptionType":"System.ArgumentOutOfRangeException"
}
Edit: This could be because the function I'm calling is marked with these attributes:
<WebMethod()> _
<ScriptMethod()> _
Should I be throwing the errors in the
ashx, or should I be returning a
status code as part of the data
returned by the call to
userCreation.ashx, then using this to
decide what action to take? How do you
handle these situations?
Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially).
However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code.
Now I have a problem as to which answer to accept.
Further thought on the problem brings me to the conclusion that I was incorrectly throwing exceptions. Duplicate user names, email addresses etc are expected issues during a sign up process and are therefore not exceptions, but simply errors. In which case I probably shouldn't be throwing exceptions, but returning error codes.
Which leads me to think that irobinson's approach should be the one to take in this case, especially since the form is only a small part of the UI being displayed. I have now implemented this solution and I am returning xml containing a status and an optional message that is to be displayed. I can then use jQuery to parse it and take the appropriate action: -
success: function(data){
var created = $("result", data).attr("success");
if (created == "OK"){
resetNewUserForm();
listUsers('');
} else {
var errorMessage = $("result", data).attr("message");
$("#newUserErrorMessage").text(errorMessage).show();
}
enableNewUserForm();
}
However travis' answer is very detailed and would be perfect during debugging or if I wanted to display an exception message to the user. I am definitely not receiving JSON back, so it is probably down to one of those attributes that travis has listed, as I don't have them in my code.
(I am going to accept irobinson's answer, but upvote travis' answer. It just feels strange to be accepting an answer that doesn't have the most votes.)

Resources