How to create dynamic function in javascript?

javaScript code working in a separate file but not part of a bigger file?

  • I am making a simple Goal-traking completely offline HTML5 app using localStorage. The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system. I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy. Here is the code that's working fine as a seperate file:     <HTML>     <HEAD>     </HEAD>     <BODY>     <script type="text/javascript">     window.onload = function(){     // setup     var goal = "CN";     var date2 = new Date();     var diff = 0;     var active = true;http://jsfiddle.net/#save     var data = '{"goals": [{"goal":"' + goal + '","duedate":"'         + date2 + '","noofdays":"' + diff + '","active":"'         + active + '"}]}';     localStorage.setItem("goals",data);           // test     var goalsStr = localStorage.getItem("goals");     var goalsObj = JSON.parse(goalsStr);     for (i=0; i<goalsObj.goals.length; i++) {       if(goal==goalsObj.goals[i].goal) {         document.body.appendChild(document.createTextNode(             "The goal is " + JSON.stringify(goalsObj.goals[i])));       }     }     }     </script>     </BODY>     </HTML> and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:     <HTML>     <HEAD>     </HEAD>     <BODY>     <script type="text/javascript">     function save()     {     //Get data from the form     var goal = document.getElementById("goal").value; //Get 'goal' from form     var date2 = document.getElementById("date2").value;      //Get 'duedate' from the form     var active = document.getElementById("active").value; //Get 'active' from form     //Calculating the number of days remaining     var date1 = new Date();      //Current Date and Time     var dd = date1.getDate(); //Current Date     var mm = date1.getMonth()+1; //January is 0!     var yyyy = date1.getFullYear();  //Current Year     if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy;   //Parsing the date to the required format     var diff =  Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000);    //Calculate no. of days remaining     if (localStorage.getItem('gcount') === null) {     localStorage.setItem('gcount', "1");     var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';         localStorage.setItem("goals",data);     //document.getElementById("temp").innerHTML="first";     }     else{     var goalsStr = localStorage.getItem("goals");     var goalsObj = JSON.parse(goalsStr);     var goal = "CN"     var data = {  "goal": goal,  "duedate": date2,  "noofdays": diff, "active": active};     goalsObj.goals.push(data);     localStorage.setItem("goals", JSON.stringify(goalsObj));         }     }         function load(){     /* // setup     var goal = "CN";     var date2 = new Date();     var diff = 0;     var active = true;http://jsfiddle.net/#save     var data = '{"goals": [{"goal":"' + goal + '","duedate":"'         + date2 + '","noofdays":"' + diff + '","active":"'         + active + '"}]}';     localStorage.setItem("goals",data);     */         // test     var goalsStr = localStorage.getItem("goals");     var goalsObj = JSON.parse(goalsStr);     for (i=0; i<goalsObj.goals.length; i++) {       if(goal==goalsObj.goals[i].goal) {        document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;        document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;        document.getElementById("active").innerHTML=goalsObj.goals[i].active;        // document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));       }     }     }     </script>     <form name="input" onsubmit="save(); return false;">         <label>Goal: </label> <input type="text" name="goal" id="goal"><br>         <label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>         <label>Active: </label><br>     <input type="radio" name="active" id="active" value="Future">Future <br>     <input type="radio" name="active" id="active" value="Present">Present <br> <br>         <!-- Submit button to submit the form -->     <input type="submit" value="submit">     </form>         <form name="load" onsubmit="load(); return false;">         <label>Goal: </label> <input type="text" name="goal" id="goal"><br>     <input type="submit" value="submit">     <p id="temp"></p>     <p id="temp1"></p>     <p id="temp2"></p>     <p id="temp3"></p>     <p id="temp4"></p>     <p id="temp5"></p>     <p id="temp6"></p>     <p id="temp7"></p>     <p id="temp8"></p>     <p id="duedate"></p>     <p id="noofdays"></p>     <p id="active"></p>     </BODY>     </HTML> What's wrong? What should I do?

  • Answer:

    The document.domain method Method type: iframe. Note that this is an iframe method that sets the value of document.domain to a suffix of the current domain. If it does so, the shorter domain is used for subsequent origin checks. For example, assume a script in the document at http://store.company.com/dir/other.html executes the following statement: document.domain = "http://company.comc"; After that statement executes, the page would pass the origin check with phttp://company.com/dir/page.html. However, by the same reasoning, http://company.com could not setdocument.domain to http://othercompany.com. With this method, you would be allowed to exectue javascript from an iframe sourced on a subdomain on a page sourced on the main domain. This method is not suited for cross-domain resources as browsers like Firefox will not allow you to change the document.domain to a completely alien domain. The Cross-Origin Resource Sharing method Method type: AJAX. http://www.w3.org/TR/access-control/ (CORS) is a W3C Working Draft that defines how the browser and server must communicate when accessing sources across origins. The basic idea behind CORS is to use custom HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail. For a simple request, one that uses either GET or POST with no custom headers and whose body is text/plain, the request is sent with an extra header called Origin. The Origin header contains the origin (protocol, domain name, and port) of the requesting page so that the server can easily determine whether or not it should serve a response. An example Origin header might look like this: Origin: If the server decides that the request should be allowed, it sends a Access-Control-Allow-Originheader echoing back the same origin that was sent or * if it’s a public resource. For example: Access-Control-Allow-Origin: If this header is missing, or the origins don’t match, then the browser disallows the request. If all is well, then the browser processes the request. Note that neither the requests nor responses include cookie information. The Mozilla team suggests in http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ that you should check for the existence of the withCredentials property to determine if the browser supports CORS via XHR. You can then couple with the existence of the XDomainRequest object to cover all browsers: function createCORSRequest(method, url){     var xhr = new XMLHttpRequest();     if ("withCredentials" in xhr){         xhr.open(method, url, true);     } else if (typeof XDomainRequest != "undefined"){ xhr = new XDomainRequest();        xhr.open(method, url);     } else {        xhr = null;     }    return xhr; } var request = createCORSRequest("get", "http://www.stackoverflow.com/"); if (request){    request.onload = function() {         // ...     };    request.onreadystatechange = handler;    request.send(); } Note that for the CORS method to work, you need to have access to any type of server header mechanic and can't simply access any third-party resource. Source: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ The window.postMessage method Method type: iframe. window.postMessage, when called, causes a MessageEvent to be dispatched at the target window when any pending script that must be executed completes (e.g. remaining event handlers if window.postMessage is called from an event handler, previously-set pending timeouts, etc.). The MessageEvent has the type message, a data property which is set to the string value of the first argument provided to window.postMessage, an origin property corresponding to the origin of the main document in the window calling window.postMessage at the time window.postMessage was called, and a source property which is the window from which window.postMessage is called. To use window.postMessage, an event listener must be attached:     // Internet Explorer    window.attachEvent('onmessage',receiveMessage);    // Opera/Mozilla/Webkit    window.addEventListener("message", receiveMessage, false); And a receiveMessage function must be declared: function receiveMessage(event){    // do something with event.data;} The off-site iframe must also send events properly via postMessage: <script>window.parent.postMessage('foo','*')</script> Any window may access this method on any other window, at any time, regardless of the location of the document in the window, to send it a message. Consequently, any event listener used to receive messages must first check the identity of the sender of the message, using the origin and possibly source properties. This cannot be understated: Failure to check the origin and possibly sourceproperties enables cross-site scripting attacks.

Nikhil M.k at Quora Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.