how do i find what's going wrong with my code - javascript

I have this function for my sql javascript
PATH="http://localhost/dhodia/";
try{
var tags=url.replace(PATH,"");
var spl=tags.split("/");
if(spl[0]=="i"){
if(spl.length>=2 && spl[1]=="hdd"){
}
addtoopen($("#"+spl[1]+"opn").attr("jso"));
menu_action(spl[1],url)
}
}catch(err){
var txt="There was an error on this page.\n\n";
txt+="Error description: " + err.message + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
i found there is problem at replace statement
if i use url as "http://localhost/dhodia/i/hdd" it will do replace
but if i use "http://localhost/dhodia/i/hdd/tarun" it is not doing replace
i want to track why it is not taking replace at this line
EDIT
I am using this in function as shown below
function hstppst(url){
config.pre=url;
if(url==PATH || url==PATH+"i/dashboard"){
$E("#"+current.open).hide();
unfixbox()
$E("#dashboard").show();
addtoopen(dsjsn);
document.title="My DashBoard";
current.open="dashboard";
}else{
var tags=url.replace(PATH,"");
var spl=tags.split("/");
if(spl[0]=="i"){
if(spl.length>=2 && spl[1]=="hdd"){
}
addtoopen($("#"+spl[1]+"opn").attr("jso"));
menu_action(spl[1],url)
}
}
}
and this function call when window.onpopstate changes
in onpopstate i pass url to this function
problem is that code is not executing after var tags=url.replace(PATH,""); and because i am using this function in onpopstate function if any error occurs poage refreshed and i am track what is error i am getting.

Please take a look at the usage of replace method of the string object:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
You mistakenly use replace.

Related

How to fix "multiple if statements in form validations"

I am working on an assignment for university. I need to make a simple form validation system with javascript. The problem is I can't get it right. The first if else statement works perfectly fine, however the second if statement does not work. However, if I copy and paste the second if statement in the console in the browser, it does work. If I try to copy and paste the whole if-else statements it once again does not work.
I have already tried looking at code in other examples but I can't seem to find the solution.
let nameForm = $('#name').val();
let age = $("#age").val();
let email = $('#email').val();
let city = $('#city').val();
if(nameForm != ""){
$("#name").attr("class", function(i, origValue){
return origValue + " is-valid";
});
}
else{
$("#name").attr("class", function(i, origValue){
return origValue + " is-invalid";
});
}
if(isNaN(age)) {
$("#age").attr("class", function (i, origValue) {
return origValue + " is-valid";
});
}
I have tried to remove all attr() and replace it with addClass(). This is the code I have now but still the class is-valid is not added with input age.
if(nameForm != ""){
$("#name").removeClass("is-invalid");
$("#name").addClass("is-valid");
}
else if(nameForm === "") {
$("#name").removeClass("is-valid");
$("#name").addClass("is-invalid");
}
if(isNaN(age)){
alert('test2');
$("#age").removeClass("is-invalid");
$("#age").addClass("is-valid");
}
The only error I got is this:
Failed to load resource: the server responded with a status of 404 (Not Found) But this is for the styles.css file and that file is empty.

get value of input in casperjs

Hi allm I would like to know how to get an input value with casperjs
This is my html element
<input type="hidden" name="key" value="newkey">
This is what I have tried:
view = 'users/registered';
casper.test.begin("Activating account", 5, function register(test){
casper.start(webroot + view, function(){
}).then(function(){
this.echo("Retrieving data from hidden input key", "COMMENT");
activationKey = this.evaluate(function() {
return __utils__.getFieldValue('key');
});
}).then(function(){
this.echo("Activating account with the key \"" + activationKey + "\"", "COMMENT");
window.location = webroot + activationKey;
});
casper.run(function() {
this.echo('Account activated successfully', 'SUCCESS').exit();
test.done();
});
});
casper.viewport(page.width, page.height);
In this case return null
I have also tried:
activationKey = __utils__.getFieldValue('key');
but return me this error:
FAIL ReferenceError: Can't find variable: __utils__
Try using this :
this.getElementAttribute('input[type="hidden"][name="key"]', 'value');
If the value is set dynamically, then this.getElementAttribute won't work, nor will __utils__.getFieldValue. The only way, as of 1.1.3, is to call the underlying document object's querySelector.
var value = this.evaluate(function() {
return document.querySelector('[name="key"]').value
})
A bit verbose, but at least it works.
Also, regarding why __utils__ couldn't be found, use the following to import it:
var __utils__ = require('clientutils').create()
In the OP's example, __utils__ is in the evaluate() function. It shouldn't be, as __utils__ is a casper thing, not a DOM/javascript thing.

How to add custom image tag to pagedown?

I'm attempting to duplicate the original img tag's functionality in custom img tag that will be added to the pagedown converter.
e.g I'm copy the original behavior:
![image_url][1] [1]: http://lolink.com gives <img src="http://lolink.com">
into a custom one:
?[image_url][1] [1]: http://lolink.com gives <img class="lol" src="http://lolink.com">
Looking at the docs the only way to do this is through using the preblockgamut hook and then adding another "block level structure." I attempted doing this and got an Uncaught Error: Recursive call to converter.makeHtml
here's the code of me messing around with it:
converter.hooks.chain("preBlockGamut", function (text, dosomething) {
return text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, function (whole, inner) {
return "<img src=" + dosomething(inner) + ">";
});
});
I'm not very experienced with hooks and everything so what would I do to fix it? Thanks.
UPDATE: found out that _DoImages runs after prespangamut, will use that instead of preblockgamut
Figured it out! The solution is very clunky and involves editing the source code because I am very bad at regex and the _DoImage() function uses a lot of internal functions only in the source.
solution:
All edits will be made to the markdown.converter file.
do a ctrl+f for the _DoImage function, you will find that it is named in two places, one in the RunSpanGamut and one defining the function. The solution is simple, copy over the DoImage function and related stuff to a new one in order to mimic the original function and edit it to taste.
next to DoImage function add:
function _DoPotatoImages(text) {
text = text.replace(/(\?\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writePotatoImageTag);
text = text.replace(/(\?\[(.*?)\]\s?\([ \t]*()<?(\S+?)>?[ \t]*((['"])(.*?)\6[ \t]*)?\))/g, writePotatoImageTag);
return text;
}
function writePotatoImageTag(wholeMatch, m1, m2, m3, m4, m5, m6, m7) {
var whole_match = m1;
var alt_text = m2;
var link_id = m3.toLowerCase();
var url = m4;
var title = m7;
if (!title) title = "";
if (url == "") {
if (link_id == "") {
link_id = alt_text.toLowerCase().replace(/ ?\n/g, " ");
}
url = "#" + link_id;
if (g_urls.get(link_id) != undefined) {
url = g_urls.get(link_id);
if (g_titles.get(link_id) != undefined) {
title = g_titles.get(link_id);
}
}
else {
return whole_match;
}
}
alt_text = escapeCharacters(attributeEncode(alt_text), "*_[]()");
url = escapeCharacters(url, "*_");
var result = "<img src=\"" + url + "\" alt=\"" + alt_text + "\"";
title = attributeEncode(title);
title = escapeCharacters(title, "*_");
result += " title=\"" + title + "\"";
result += " class=\"p\" />";
return result;
}
if you look at the difference between the new _DoPotatoImages() function and the original _DoImages(), you will notice I edited the regex to have an escaped question mark \? instead of the normal exclamation mark !
Also notice how the writePotatoImageTag calls g_urls and g_titles which are some of the internal functions that are called.
After that, add your text = _DoPotatoImages(text); to runSpanGamut function (MAKE SURE YOU ADD IT BEFORE THE text = _DoAnchors(text); LINE BECAUSE THAT FUNCTION WILL OVERRIDE IMAGE TAGS) and now you should be able to write ?[image desc](url) along with ![image desc](url)
done.
The full line (not only the regex) in Markdown.Converter.js goes like this:
text = text.replace(/(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])()()()()/g, writeImageTag);
so check the function writeImageTag. There you can see how the regex matching text is replaced with a full img tag.
You can change the almost-last line before its return from
result += " />";
to
result += ' class="lol" />';
Thanks for the edit to the main post.
I see what you mean now.
It is a bit weird how it uses empty capture groups to specify tags, but if it works, it works.
It looks like you would need to add on an extra () onto the regex string, then specify m8 as a new extra variable to be passed into the function, and then specify it as class = m8; like the other variables at the top of the function.
Then where it says var result =, instead of class =\"p\" you would just put class + title=\"" + .......

JavaScript talking to Flash via ExternalInterface

I have been trying to put together a proof of concept of JavaScript talking to Flash. I am using JQuery and Flash CS5, ActionScript 3.
I am not a Flash developer so apologies for the code, if I can prove this works the Flash will be given to someone who knows what they are doing.
The Actionscript is on a layer in the timeline in the first frame, with a couple of elements in the root movie:
output = new TextField();
output.y = -200;
output.x = -200;
output.width = 450;
output.height = 325;
output.multiline = true;
output.wordWrap = true;
output.border = true;
output.text = "Initializing...\n";
root.bgClip.addChild(output);
try{
Security.allowDomain("*");
flash.external.ExternalInterface.marshallExceptions = true;
output.appendText("External Interface Available? " + ExternalInterface.available + "\n");
output.appendText("External Interface ObjectId: " + ExternalInterface.objectID + "\n");
flash.external.ExternalInterface.addCallback("getMenuItems", returnMenuItems);
flash.external.ExternalInterface.addCallback("changeText", changeText);
flash.external.ExternalInterface.addCallback("changeBgColour", changeBgColour);
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
} catch (error:SecurityError) {
output.appendText("Security Error: " + error.message + "\n");
} catch (error:Error) {
output.appendText("Error: " + error.message + "\n");
}
function returnMenuItems():String{
return "[{\"menu option\": \"javascript:callFlash('changeBgColour','4CB9E4')\"}]";
}
function changeText(t:String){
root.textClip.text = t;
}
function changeBgColour(colour:String) {
var c:ColorTransform = root.bgClip.transform.colorTransform;
c.color = uint(colour);
root.bgClip.transform.colorTransform = c;
}
The JavaScript and HTML are:
function populateMenu(message){
$("#options").changeType("Options", $.parseJSON(message));
$("#options").addMenuActions();
}
function callFlash(methodToCall, param){
alert("method: " + methodToCall + ", param: " + param);
if(param == undefined){
$("#AJC")[methodToCall]();
}else{
$("#AJC")[methodToCall](param);
}
}
var flashvars = {};
var params = {allowScriptAccess: "always"};
var attributes = {name: "AJC"};
swfobject.embedSWF("http://192.168.184.128/ActionscriptJavascriptCommunication.swf", "AJC", "600", "400", "9", "", flashvars, params, attributes);
and
<body>
<div id="wrapper">
<div id="topBar" class="top-bar"></div>
<div id="flashContainer">
<div id="AJC">Loading Flash...</div>
</div>
<ul class="dropdown" id="games"></ul>
<ul class="dropdown" id="options"></ul>
</div>
</body>
Now I know the ActionScript is awful, the reason it looks like it does is because I have read a lot of threads about possible issues to do with contacting Flash from JavaScript (hence the allow security domain * and adding a debug text box etc).
The JavaScript I am using is within a script tag in the head. The changeType and addMenuActions are just JQuery methods I have added. These are just JavaScript methods that have been tested independently but do work.
You'll notice that the last line of my try catch in the ActionScript is:
flash.external.ExternalInterface.call("populateMenu", returnMenuItems());
This does work, it populate my menu with the text sent from Flash. The only thing that doesn't work is trying to call the methods exposed using the addCallback function.
I get the alert which says:
method: changeBgColour, param: 4CB9E4
but an error saying:
Error: $("#AJC")[methodToCall] is not a function
Source File: http://192.168.184.128/test.html#
Line: 88
I set up a local VM to run Apache, which relates to the 192.168.184.128, I wondering if this was the issue, I have seen a couple of threads mention that trying to communicate with flash locally won't work, which is why I set up the VM with apache?
Any ideas? I know people have got this working, it is very frustrating.
Thanks.
Simple mistake: jQuery's factory method produces jQuery.init object, which acts very similar to an array. You need to call the method on the actual DOM element, which is the first member in the "array".
$('#AJC')[0][methodToCall]
If you had security issues, you wouldn't be able to communicate between Flash and JavaScript at all.
The problem is in the way you are accessing your flash object. SwfObject has a built-in function that take care of that, it works great across all browsers:
function callFlash(methodToCall, param)
{
var obj = swfobject.getObjectById("AJC");
if(param == undefined){
$(obj)[methodToCall]();
}else{
$(obj)[methodToCall](param);
}
}
I havent tested the code above, but I guess it should work!

Try catch error in Javascript pass the error statment into Google Analytics

I have a Toogle function that uses to show/hide a div bloack to end users. However, some users said the IE generate an error when they clicks on this link. I am wondering whether I can use try catch statement in JavaScript to catach the error the users got and send to Googel Analytics.
If Yes, How I can do that. I have google analytcis set up in our site.
For instance, I have a div section call dynamic phone number.
<div id = "cs_DynamicForm">
"Phone number..."
<div>
When users click on Phone us link, i am able to track it in google.
<a onclick="javascript: pageTracker._trackPageview('/Contact/UK/phone');" id="phoneNumberToggle" class="more-info-link" href=" javascript:void(0);">Phone us</a>
In the back end, my toggle function works, like that
_dynamicPhoneNumber: function(type, arg)
{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
If i have to rewrite this function, i think it will look likes that:
try{
var phoneNumber = document.getElementById("cs_DynamicForm");
var vis =phoneNumber.style;
//alert(vis);
if(vis.display==''&&phoneNumber.offsetWidth!=undefined&&phoneNumber.offsetHeight!=undefined)
vis.display = (phoneNumber.offsetWidth!=0&&phoneNumber.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
catch (e)
{
var errorMsg=e.message;
if (typeof (e.number) != "undefined") {
document.write ("<br />");
document.write ("The error code: <b>" + e.number + "</b>");
}
if (typeof (e.lineNumber) != "undefined") {
document.write ("<br />");
document.write ("The error occurred at line: <b>" + e.lineNumber + "</b>");
}
//And send the errorMsg to google analytics. how I should do that
}
Any helps,
Cheers,
Qing
first catch the error simply like:
try {
tes.ting = 123;
}
catch(e) {
errors.push(e);
}
then push it to Google
_gaq.push(['_trackEvent', 'Testing', 'Error', errors.toString()]);
You can use the trackEvent as has been pointed here - but I believe the easiest way is to use trackPage, as you did for the other pages.
I use something like this:
try {
...
} catch (e)
{
pageTracker._trackPageview('/errors/'+e.toString());
}
You can replace 'errors/' with whatever makes sense to you ('virtual-errors-list/' for example).
In addition, consider adding the error tracking to window.onerror handler:
window.onerror = function(errorMsg, url, lineNumber){
pageTracker._trackPageview('/errors/'+errorMsg);
}

Categories