Search Articles/Question

Loading...

Friday, January 25, 2013

[javascript questions] redirecting to the URL present in response after ajax redirection?

[javascript questions] redirecting to the URL present in response after ajax redirection?


redirecting to the URL present in response after ajax redirection?

Posted: 25 Jan 2013 01:48 AM PST

I searched through many links but somehow could not solve my problem.
I am using dojo.xhrPost to make an ajax post.
I am using ruby on rails and after the data is successfully submitted the controller redirects to a different page.
But since i am making an ajax post i need to somehow find this new redirected url and redirect to that url manually using javascript.
Can you tell me how to do this?
Thanks.

Using evaluated variable values instead of the actual type

Posted: 25 Jan 2013 01:47 AM PST

var foo;    console.log(typeof foo); //"undefined"    if(typeof foo === 'undefined')      console.log(1);    if(!foo)      console.log(2);  

In my example above, the console will log both "1" and "2", since undefined evaluates as false. The same thing will happen for null, NaN, "" (empty string) etc.

Is it more common to use the typeof operator and compare the string value, rather than using the evaluated boolean value? Is there any difference besides readability? Any pros and cons?

First Tuesday of every Month

Posted: 25 Jan 2013 01:46 AM PST

Hello I am trying to use the following code which is a mish mash of "lifted code" but it keeps pumping out todays date and time.

I am trying to get the date for the first Tuesday of every month at 19:00.

I am using W3C School Try-it for testing purposes.

<!DOCTYPE html>  <html>  <head>  <script>  function displayDate()  {    var myDate = new Date();  myDate.setHours(19, 00, 0, 0);  myDate.setYear(2013);    myDate.setDate(1);  myDate.setMonth();      //Find Tuesday  var tue = 2;    while(myDate.getDay() != tue) {      myDate.setDate(myDate.getDate() + 1);    }    document.write(myDate);  </script>  </head>  <body>    <h1>My First JavaScript</h1>  <p id="demo">This is a paragraph.</p>    <button type="button" onclick="displayDate()">Display Date</button>    </body>  </html>   

Roy

What's the difference between $get and $find in JavaScript?

Posted: 25 Jan 2013 01:46 AM PST

I'm a .NET programmer who've just started to learn more about client side scripting, and I was wondering sometimes you use $get('value') and $find('value') and I've discovered that these are just shortcuts for document.getElementById('value') and Sys.Application.findComponent('value'), respectively.

However, I still don't understand: what is the difference between these two functions in JavaScript? What exactly are they looking up/retrieving when invoked?

Thanks in advance.

Add, update and query SharePoint list items from CSOM using javascript

Posted: 25 Jan 2013 01:46 AM PST

Using javascript and SharePoint's CSOM, can someone provide an example for the follow scenario:

Get field value from the selected items in a list (ListA).

Then for each item selected, take a fields value and use it to query a different list (ListB).

If the query returns 0 rows, create item in ListB and update selected item in ListA.

Else if the query returns 1 row, update selected item in ListA.

How to create a select button on TinyMCE?

Posted: 25 Jan 2013 01:45 AM PST

I'm using tinyMCE and i don't know how i can create un select button on the toolbar ?

For example, look at this demo : http://www.tinymce.com/tryit/full.php

I want to create buttons like "Styles", "Paragraph", "Font Family" etc...

Do you have any ideas ?

Thanks !

Edit : I know how to create a plugin with a basic button.

Displaying Transparent iFrame on top of an Applet

Posted: 25 Jan 2013 01:45 AM PST

I wanted to display a transparent iFrame on top of the applet.

However when I use allowtransparency="true" and background-color:transparent, It shows the background of the html under which applet is embedded. It doesn't show the background applet as such.

Is there a way by which we can display a transparent IFrame on top of an applet and the transparent region of the iFrame shows the background applet.

How to read a json object in js

Posted: 25 Jan 2013 01:43 AM PST

I have a json object as

"[{"portal.home":"Home"},{"displaytag.tracking.id":"Item ID"},{"displaytag.tracking.itemName":"Item Name"},{"displaytag.tracking.itemType":"Type"}]"  

Now I want to access the value of "portal.home" or "displaytag.tracking.id"

How shall I do it?

Is there a language over JavaScript that allows users to write code like Java code?

Posted: 25 Jan 2013 01:43 AM PST

If anyone knows if exists any meta-language above Javascript that allows users to write and organize code like Java or other high level programming language (class, variable, method). After code should be simple translate in Javascript.

One example could be be TypeScript http://www.typescriptlang.org/Playground/

but are there others?

Decrypt byte data in javascript/Jquery

Posted: 25 Jan 2013 01:43 AM PST

I have a project where i used gzip in .cs file to zip the data and get it in html page. Here is my code for gzip.

public byte[] CustomerList()      {          SqlDataAdapter da = new SqlDataAdapter("select CustomerID from CustomerMaster", con);            DataSet ds = new DataSet();          da.Fill(ds);          return CompressData(ds);      }      public byte[] CompressData(DataSet ds)      {          using (MemoryStream memory = new MemoryStream())          {              using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress))              {                  var formatter = new BinaryFormatter();                  formatter.Serialize(gzip, ds);                  gzip.Close();              }                return memory.ToArray();          }      }  

i successfully received the data from html page using ajax function. Here is my code

<script type="text/javascript" language="javascript">      $(document).ready(function () {                        $.ajax({                          type: "POST",                          url: "Service1.svc/CustomerList",                          contentType: "application/json; charset=utf-8",                          dataType: "json",                          processdata: true,                          success: function (data) {                              alert(data.CustomerListResult);                          },                          error: function () {                              alert("Error");                          }                      });                  });        </script>  

I received the data in byte format. Now i want to decrypt the byte-data to get the original data. Here i got stuck. Please help me how to decrypt the byte to get the original data.

Chrome leaks memory when simply adding and removing SVG elements

Posted: 25 Jan 2013 01:43 AM PST

Continuing this question: Task manager shows memory leak, but Heap snapshot doesn't

I managed to create a very simple example, which illustrates this leak, here is full source code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">  <html>      <head>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">          <title>svg test</title>                <script type="text/javascript">                var svg;              var interval;              var svg;                window.onload = function(){                  createSVG();                  start();              }                function start(){                  interval = setInterval(createElements, 100);                              }                function createSVG(){                    var div = document.getElementById("svgdiv");                  div.innerHTML = "";                    svg = createSvgElement("svg");                  svg.style.position = "absolute";                  svg.style.width = "600px";                  svg.style.height = "500px";                  svg.setAttribute("version", "1.1");                  div.appendChild(svg);                  createElements();                             }                  function createElements(){                    removeElements();                    for(var i = 0; i < 500; i++){                      var element = createSvgElement("circle");                      element.setAttribute("r", Math.random() * 10);                      var transform = "translate(" + Math.round(Math.random() * 600) + "," + Math.round(Math.random() * 500) + ")";                      element.setAttribute("transform", transform);                      element.setAttribute("fill", "#CC0000");                      svg.appendChild(element);                  }              }                function removeElements(){                  while(svg.hasChildNodes() ){                      svg.removeChild(svg.lastChild);                  }                             }                  function createSvgElement (name) {                  return document.createElementNS("http://www.w3.org/2000/svg", name);              }                function stop(){                  clearInterval(interval)              }              </script>      </head>      <body style="background-color:#FFFFFF">          <div id="svgdiv" style="width:600px; height:500px;"></div>          <input type="button" value="start" onclick="start()">          <input type="button" value="stop" onclick="stop()">      </body>      </html>  

If I run this script, Chrome keeps eating the memory until it crashes. Other browsers don't. Instead of removing children one by one I also tried to clear it in a fast way by setting innerHTML="", but it's the same.

I enabled an experimental feature of Chrome which shows the kind of memory is used. The "Pages structures" memory is increasing a bit (however the HTML remains the same and there are no detached DOM objects), but the most memory goes to "Other" section.

If I stop the script and force GC to do it's job, the memory decreases by only few kilobytes. However if I wait for a minute or two, the memory is cleaned almost to a initial level. I know that my script is quite intense, but this happens also if I run it every 1 or two seconds only - I think that's quite enough for GC to do it's job. And I know GC is working, as other kind of memory is released. Could this be a Chrome bug? Maybe I should do something before removing the elements?

How to parse console.log in Chrome Developer Tools?

Posted: 25 Jan 2013 01:37 AM PST

Now I am trying to unit test the a simple Phonegap application. Especially, I want to test the vibration function in this application. This issue is described here.

In the proposed solution, vibration event is written to the Chrome's log by calling console.log(). In order to write unit test, I want to parse Chrome's log after that. Is it possible to do that from JavaScript?

In this reference question, the content of log is written to disk first. I also wonder if it is possible to read the log without saving it to disk.

JavaScript organization chart without waste gaps between nodes

Posted: 25 Jan 2013 01:35 AM PST

I want to make an organization tree by using JavaScript. The tree is needed a function toggle display nodes by clicking. I found some usefull libralies below.

1.jQuery Org Chart

http://th3silverlining.com/2011/12/01/jquery-org-chart-a-plugin-for-visualising-data-in-a-tree-like-structure/

2.Visualization: Organizational Chart http://code.google.com/apis/chart/interactive/docs/gallery/orgchart.html

3.SharePoint Org Chart

http://www.thesanitypoint.com/archive/2009/11/11/a-free-sharepoint-org-chart-web-part.aspx

Libraries of No1 and No2 meet almost my demands but just one thing does not.

Please take a look at the pic below, as you can see there is a gap between [Fruit] and [Bread] due to consider under hierarchies. Doing this leads to over expand width which is not acceptable for me.

On the other hand, an image in [3.SharePoint Org Chart] does not have waste blanks between nodes. I would like to make like this. (unfortunately, this is not JavaScript..)

Does anyone know any libraries satisfied my demand or how to customize above libraries. Any help will be appreciated.

enter image description here

Best practice for documenting events

Posted: 25 Jan 2013 01:34 AM PST

Consider a modular web application based on JavaScript, JQuery and all that "en vouque" JavaScript stuff (that shouldn't be too extraordinary nowadays).

The modules of this application are communicating with each other and with the application core through events (JQuery Events, Backbone Events).

Events of those frameworks consists (most of the time) of:

  • a name
  • an event callback
  • a data object

for example the event treeclick will have a reference to the callback onTreeClick() and a data object telling the callback which treeNode has been clicked.

If you now think of this application growing and growing, getting newer modules, several developers hacking on it... time is passing by...

Now your task is:

Find out how the event is called that takes care for editing items in a table, AND how the parameters are that its callback expects.

Well... you could have a look at the super detailed event-documentation that someone already wrote for you and put alongside the code for a good reference. Then you wake up and notice that nobody ever did this and since you are a kind of super hero programmer, you'll attend this matter immediately.

Is there a best practice or a tool or some other good advice on how to document events inside or alongside JavaScript code?

How can i use javascript to get a browser window from background back to the front on buttonclick?

Posted: 25 Jan 2013 01:34 AM PST

If a user clicks on a button a new window opens where the user can do irrelevant stuff. In case the user clicks on the former page the new window gets pushed into the background and the user is not able to see it anymore. That is notmal behaviour so far.

What i need now is that the already opened window comes back to the front on a second button click of the user. Is this possible? How?

Creating pie chart using jq plot which takes the value from the web service(vb.net)

Posted: 25 Jan 2013 01:34 AM PST

I am trying to create a sample pie chart which takes the value from the web service(vb.net), but I am stuck as the chart is not getting created properly.

Here is my code. function chart() {

     alert("clicked");         $.ajax({           type: "POST",           url: "Service1.asmx/GetChart",           contentType: "application/json; charset=utf-8",             data: "{'sDB':'" + "sDB" + "'}",           dataType: "json",             success: OnGetMemberSuccess2,           failure: function (errMsg) {               $('#errorMessage').text(errMsg);           }         });         function OnGetMemberSuccess2(data, status) {             //RenderPieChart('container', [['Firefox', 45.0]]);           RenderPieChart('container', [[data.d]]);           alert(data.d);     }       function RenderPieChart(elementId, dataList) {             new Highcharts.Chart({               chart: {                  renderTo: dataList,                   plotBackgroundColor: null,                   plotBorderWidth: null,                   plotShadow: false               }, title: {                   text: 'Browser market shares at a specific website, 2010'               },               tooltip: {                   formatter: function () {                      return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';                       alert(tooltip);                   }               },                               plotOptions: {                                    pie: {                                        allowPointSelect: true,                                        cursor: 'pointer',                                        dataLabels: {                                            enabled: true,                                            color: '#000000',                                            connectorColor: '#000000',                                            formatter: function () {                                                return '<b>' + this.point.name + '</b>: ' + this.percentage + ' %';                                            }                                        }                                   }                                },               series: [{                   type: 'pie',                   name: 'Browser share',                   data: dataList               }]           });       };   }  

Web service code:

    Public Function GetChart(ByVal sDB As String)      Dim oSB As New StringBuilder        '  oSB.Insert(42, "Firefox")      oSB.Append("Firefox")      oSB.Append(",")      oSB.Append("45.0")      'oSB.Append("'Safari', 6.5")      'oSB.Append("'Opera', 8.2")        'oSB.Append("'Others', 0.7")        Return oSB.ToString  End Function  

I am getting the chart created if i give

    RenderPieChart('container', [['Firefox', 45.0]]);   

instead of

    RenderPieChart('container', [[data.d]]);  

can any one please help me to solve this problem.

cheers.

Write outside of my script javascript

Posted: 25 Jan 2013 01:33 AM PST

Hello I am new in the world of javascript

I have a script which detect silverlight is installed on my PC Now when i run it i only see true or false when the line document.write(silverlightInstalled); is inside my script and not outside I want to know if there is a way to set it outside of my script

Code:

<body>  <script language="javascript">      var browser = navigator.appName // Get browser      var silverlightInstalled = false;        if (browser == 'Microsoft Internet Explorer') {          try {              var slControl = new ActiveXObject('AgControl.AgControl');              silverlightInstalled = true;          }          catch (e) {              // Error. Silverlight not installed.          }      }      else {          // Handle Netscape, FireFox, Google chrome etc          try {              if (navigator.plugins["Silverlight Plug-In"]) {                  silverlightInstalled = true;              }          }          catch (e) {              // Error. Silverlight not installed.          }      }        document.write(silverlightInstalled);      </script>  </body>  

Is it possible to manually control the browser throbber?

Posted: 25 Jan 2013 01:32 AM PST

Is there an easy way to start and stop the browser throbber (page loading indicator) without changing the page you are on? Preferably with no external libraries or AJAX calls.

Merge two different json object in extjs

Posted: 25 Jan 2013 01:30 AM PST

Let's say my first json object is

  "jvtdata":{      "tranid":"100001",      "trandate":"Sun Jan 20 2013 00:00:00 GMT+0800 (Taipei Standard Time)",      "trantype":"f"    }  

and my second data is

 "detail" : [     {        "id": "1",        "obj": "data1"     },     {        "id": "2",        "obj": "data2"     },     {        "id": "3",        "obj": "data3"     }    ]  

how do I make it like this in extjs 4?

  "jvtdata":{      "tranid":"100001",      "trandate":"Sun Jan 20 2013 00:00:00 GMT+0800 (Taipei Standard Time)",      "trantype":"f",      "detail" : [     {        "id": "1",        "obj": "data1"     },     {        "id": "2",        "obj": "data2"     },     {        "id": "3",        "obj": "data3"     }    ]    }  

\n new line character won't work

Posted: 25 Jan 2013 01:30 AM PST

I tried making a web page by writing

document.write("This is the first line \n And this is the second");  

The desired effect is:

This is the first line  And this is the second  

But I get this:

This is the first line And this is the second  

I tried writing <br> inside and it worked. But Why writing an escape \n didn't? Anything I am doing wrong? I am using Firefox.

Wordpress, getting date and time when form was submited (submission button clicked)

Posted: 25 Jan 2013 01:29 AM PST

I'm using User Meta plugin for wordpress and it seems that it does not have function to show the date when user submitted/modified their data.

How could I do so any suggestions?

There is timestamp column in database where user first submission date is put, and I thought that I somehow could use this in my advantage, but I can't find there in code it's happens. I personally think, that it happens somewhere here:

register_activation_hook( $userMeta->file,  array( $this, 'userMetaActivation' ) );          add_action( 'user_meta_schedule_event',     array( $userMeta, 'clearCache' ) );    function userMetaActivation(){          wp_schedule_event( current_time( 'timestamp' ), 'daily', 'user_meta_schedule_event');      }  

Any leads?

------EDIT-------

Ok, I've managed to put submission date and time to Database. Bu I can't retrieve it and don't know why.

global $current_user;  $current_user = wp_get_current_user();  $userID = $current_user->ID;    global $wpdb;  $lastSubmitDate = $wpdb->get_results("SELECT meta_value FROM wp_usermeta WHERE user_id = $userID AND meta_key = 'submission_date'");  echo $lastSubmitDate;  

It returns me string Array. What's wrong with it? Maybe someone could help me with this?

PHPBB BBcode - code tag with: select, expand/collapse function - SOLVED

Posted: 25 Jan 2013 01:29 AM PST

Im creating a custom bbcode for phpbb, in which i need a "select all" and a "expand/collapse" function. The expand/collapse option should then have a specific style when scrolling is active.

The select and expand/collapse work fine, but where i have a problem is when looking for if scrolling is active.

First the scrolling and looking for it works fine, but the bbcode is not unique (only works on the first one posted) Second the getElementByTagName('testlink') for the expand/collapse link does not work.

So quickly excplayn what i want the script to do, and what is working so far.

  • When div class is ready run function - working
  • set var for the link class (testlink) - not working
  • set var for the content div class - working
  • set var for scrolling - working
  • try to scroll content - working
  • if scrolling works scroll back up - working
  • if scrolling works set visibility of (testlink) to visible - not working
  • if no scrolling (else) set visibility of (testlink) to hidden - not working

Javascript:

$(document.getElementsByTagName('pre_header')[0]).ready(      function () {      var expandlink = this.getElementsByTagName('testlink')[0];        var eee = this.getElementsByTagName('dd')[0];         var old = eee.scrollTop;      eee.scrollTop += 220;          if (eee.scrollTop > old) {          eee.scrollTop -= 220;          expandlink.style.visibility = "visible";      }       else {          expandlink.style.visibility = "hidden";          };        }  );  

HTML:

<div class="pre">      <dt class="pre_header">          <b>Code: </b>          <a class="testlink" href="#">expand</a>      </dt>      <dd style="overflow:auto;">          content here      </dd>  </div>  

Hope to get some help, and when it all done ill add the whole BBcode for others to use..

/megaman

keypress event not generated in Chrome on ENTER Key?

Posted: 25 Jan 2013 01:29 AM PST

My application requires an input from users, on entering a value in a textbox, users hit Enter (Return Key) and this calls a buttons onclick event. This works fine in IE, FF but not Chrome. On enter in chrome, keypress event is not generated Here is my code snippet

 $('#myDiv').keypress(function (e) {      alert("Key  pressed");      if (e.keyCode == $.ui.keyCode.ENTER) {         alert("enter pressed");      }    });  

Could anyone provide input on this?

Getting a Java applet to scale to a big browser

Posted: 25 Jan 2013 01:29 AM PST

I have been trying to get a Java applet embeded in a .htm file. I want to scale the maximum size for a browser window depend of users current resolutom, especially for chrome and toolbars. The problem is I don't know a way to maximise the browser using PHP/JS or whatever. If the applet launches in a scaled-down browser window the applet will be permenently small. If I ask the browser to start the applet in any window that may be constricted. There is no real way for my applet (within the realm of wisdom) gaining the current size.

Here my source code:

<html>  <head>    <style>   applet   {          width: 100px;      height: 100px;  }  </style>    <script>    function resizea()    {      var a = document.getElementsByTagName("applet")[0];      a.style.height = screen.height;      a.style.width = screen.width;    }    resizea();  </script>  </head>  <body>    <applet archive="jarfile4.jar" width="1" height="1" code="rebuiltgui.class"></applet>  </body>  </html>  

How to detect global variables with the sonar javascript plugin

Posted: 25 Jan 2013 01:29 AM PST

We're trying to detect usage of global variables in our js code by using a sonar analysis. It seems that this rule was present in old versions of the javascript plugin, but not anymore (we're using version 1.2 of the plugin). Are we doing something wrong ? Or is there a way to use XPath to mimic this rule ?

Thanks in advance

confused about internationalise the button text of the file picker

Posted: 25 Jan 2013 01:28 AM PST

<input type="file" .../>  

I understand this will always show as |choose file| no file selected.(chrome) / Browse... (I.E 9 / Firefox)

I wanted to ask if the text "Choose File/ Browse" will change dependent to the users localisation.

As by default it shows as "Choose File", but someone viewing in 'fr/FR' would they see "Choose File" or "choisir le fichier"

Or is it possible to localize the text of the button to "Select" so it shows the same across all browsers and that way i can localize the string?

create html templates textarea or script or div or else

Posted: 25 Jan 2013 01:28 AM PST

I have seen html templates created using any of the following tags

<textarea>  <script>  <div>  

Which one is better and why?

Which of the following way of creating html templates is better and y?

CSS:

.template {    display: none;  }  

textarea :

<textarea class="template" id="tmpl1">    <div>adfsdfsdfs</div>  </textarea>  

script :

<script type="text/html" id="tmpl1">    <div>adfsdfsdfs</div>  </script>  

div :

<div class="template" id="tmpl1">    <div>adfsdfsdfs</div>  </div>  

I had faced problem with script tag here

How to make a blog type page with prev & next page functionality?

Posted: 25 Jan 2013 01:28 AM PST

I was wondering if I needed to learn javascript and or php to make a site that can move content from page to page as new content is added (like a blog). I was thinking of using wordpress and wipe the design and write my own css, but seems you need to do a $30 update to have access to css.

Is there a free site (like wordpress) that could help me out with the php part or whatever is needed to have this kind of functionality? How many hours would it take to learn php to get the 'blog' running correctly if I only know html/css right now, with a bit of javascript and can manage jquery plugins.

Thanks alot for any answers.

How to deactivate select-option with javascript?

Posted: 25 Jan 2013 01:28 AM PST

In the following html-code, I would like to realize the following with javascript. When the user selects Audi, he has only the option to select application 2 (application 1 has to disappear in this case).

<select>      <option value="volvo">Volvo</option>      <option value="audi">Audi</option>  </select>  <select>      <option value="app1">application 1</option>      <option value="app2">application 2</option>  </select>  

I wrote the code here: http://jsfiddle.net/L2NFA/ for any ideas.

OAuth2.0 with IMAP to be implemented in chrome extension to get email attachements from gmail

Posted: 25 Jan 2013 01:27 AM PST

I am trying to build a chrome extension which first uses oauth2.0 to authenticate users credentials and then after that by using IMAP i want to get his email attachments list from gmail.

Please help.

Things that i did..

in my background.js file.. i have written this code .by this i am able to get email address of user. but my main objective is to get gmail attachment list that too by using imap.

I am not able to get material or blog regarding IMAP implemenation with oauth 2.0 and chrome extension.

var googleAuth = new OAuth2('google', {    client_id: '[client id]',    client_secret:'[client secret]',    api_scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'   });    googleAuth.authorize(function() {    // We should now have googleAuth.getAccessToken() returning a valid token value for us     // Create an XMLHttpRequest to get the email address     var xhr = new XMLHttpRequest();    xhr.onreadystatechange = function() {       if( xhr.readyState == 4 ) {        if( xhr.status == 200 ) {           var parseResult = JSON.parse(xhr.responseText);          alert(xhr.responseText);          //console.log(parseResult);          // The email address is located naw:           var email = parseResult["email"];         // var name = parseResult["name"];          //console.log(email);         // alert(name);          //alert(email);        }      }    }    // Open it up as GET, POST didn't work for me for the userinfo     xhr.open("GET","https://www.googleapis.com/oauth2/v1/userinfo",true);    // Set the content & autherization     xhr.setRequestHeader('Content-Type', 'application/json');    xhr.setRequestHeader('Authorization', "OAuth " + googleAuth.getAccessToken() );    xhr.send(null);        console.log(xhr);  });  

No comments:

Post a Comment