Need to convert Web Form JavaScript to a js file - javascript

Basically I have three functions embedded into my form. I want to move this into a js file that I have already. I did this previously and my pop ups are working but now I want to move one function which executes the onclick event for a download button and the other two functions belonging to my autocomplete extender so I can display the results how I want them.
I have been messing around but I cannot seem to get this working.
This is my JavaScript function in Web Forms
function Download() {
__doPostBack("<%= btnDownload.UniqueID %>", "OnClick");
}
This is what I have tried in a js file
function Download(button) {
__doPostBack(button, 'OnClick');
}
and this is how I am calling it
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(" & btnDownload.ClientID & ");", True)
please can somebody give me a clue to what I am missing and before I forget yes, the file is in my headers
<script type="text/javascript" src="js/importBuyer.js"></script>

The javascript function __doPostBack("<%= btnDownload.UniqueID %>", "OnClick"); expect a string as the client ID of the button. So you need to construct the calling script with ID parameter as string as follows:
ClientScript.RegisterStartupScript(Me.GetType(), "download", "Download(""" & btnDownload.ClientID & """);", True)
Note the double double-quotes ("") above so that the rendered javascript will be like :
Download("btnDownloadID");

From the example you've posted it seems that the webform way was sending the UniqueID and you are sending the ClientID
So you probably only need to send the UniqueID property instead.
I am wondering why should you do that. I would expect you to move from webforms to an API base backend but I can't understand why you want to separate the js integration part while keeping the webforms backend - I would understand if you'd separated the js logic part... not the part that communicates with the webforms
Hoped that helped
Here is a link describing the difference

Related

Call a PHP Link with Onclick

This isn't a duplicate question by any means and I have tried a lot finding solutions.So, please read it before down voting.
Background:
This application is like a note-taking web app where you can post/delete your notes.
Each item in the list has an id which is needed when making a delete call.
In my application, I have to delete individual items from a list which is generated by looping over a JSON response (by a REST API) using PHP.The JSON response can be obtained after successful login.
Question:
To implement delete functionality I have to send id of each of the items as a parameter to the rest api delete call.
So, for this I have to generate dynamic links of the form :
http://localhost/myfolder/api/notes/:id
which should be passed to the delete.php function (Which I have implemented in CURL).
I searched for possible ways :
Using a PHP function: It seems to be complex, however if there is some way to invoke a PHP function (the delete code using CURL) on click of a link (Which I found not possible as per some answers ?) this could be a great solution.
Using Javascript: I have to call a function upon click of link that sets a variable $_SESSION["id"] to the current item["id"] and then goes to delete.php where I use the $_SESSION variable to first set up the link and then use the CURL code.
I tried basic implementation using the second approach but I have hit a roadblock in this issue. It would be great if you could tell with a bit of code which approach should be followed or any other way to do this ?
This functionality is present in twitter/facebook and almost every such service, how do they implement this, the basic approach should be the same, right: Generate dynamic links and pass them to a php script on click ?
Basic Javasript approach :
<script>
<script>
var el = document.getElementById('del1');
el.onclick = del1;
function del() {
// I have to set $_SESSION here
return false;
}
</script>
echo "<a href=\"delete.php\" title=\"Delete\" id=\"del1\">";
//Here, I have to pass the item["id"] to the javascript function.
I had tried some other ways but I have modified the code a lot so, I can't post them. Thanks for your help.
Regarding #2, you can't access the user's session from Javascript, so that will not work.
My preferred way (if using jquery) is to put the id in a data attribute of the delete button (or the block as a whole). Then in the delete onclick function do something like
<div class="block" data-itemid="<?=$item['id']?>">
...
<div class="delete_button">Delete</div>
</div>
...
$('.delete_button').on('click',function(event) {
block = $(event).target.parent('.block');
itemid = block.data('itemid');
$.post('delete.php',[itemid: itemid]...);
});

Store very small amount of data with javascript

I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.

JavaScript in ASP.Net CodeBehind

I am having trouble with some javascript that I have added to the codebehind. The goal I am trying to achieve here is on the page load to do another postback. Now, you may find this odd, but there is method to my madness.
In my ASP.Net Wizard, I have a textbox that contains a date populated from another step. This date is then used to populate 3 other controls with financial information. It is necessary for these 3 other controls to be populated on the load of this step. Now I have tried to do simply on page_load, but this doesn't work as certain controls either don't exist or the date isn't in the textbox. I have also tried to do this on the page render method, but this didn't work either for the same reasons.
So, I have resorted to using javascript executing a double postback, but it is causing all sorts of problems.
Here is the code from the Page_Load :
Dim validateFinancial as String = "<script language='javascript'>window.onload = function() ( ValidateFinancialDate() { __doPostBack('<%= UpdatePanel2.ClientID %>'); return false; })</script>"
Page.ClientScript.RegisterStartUp(Me.GetType(), "MyScript", validateFinancial, false)
It is not firing and in the javascript error box you see in the bottom left hand corner of the browser it says missing ";". If I remove the javascript code and simply added it to the markup with the function name in the string it will work with errors, but this when posting to the webserver causes the AJAX controls to fail on the whole page.
Is there away of getting this to work, please?
Your problem is that
<%= UpdatePanel2.ClientID %>
will not be interpreted. at the time when you want your javascript to post back, ASP has already finished rendering your page. You're goin to have to find another way of passing your UpdatePanel2.ClientID value.
You shouldn't use <%= UpdatePanel2.ClientID %> on backend side. Get __doPostBack('<%= UpdatePanel2.ClientID %>') equivalent using ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty); replace your __doPostBack('<%= UpdatePanel2.ClientID %>') with return value of mentioned method.
More detailed:
Let's start from the beginning. You need postback to be initiated by UpdatePanel2 after page loaded on client.
The correct JS function pattern should be:
window.onload = function() { ValidateFinancialDate(); %Do postback%; return false;};
To obtain that %Do postback% function call for UpdatePanel2 we need to use ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty) backend method,
which will produce correct JS __doPostBack function call to make postback request initiated by UpdatePanel2 control.
So working example on C# will be as following:
string postbackReference = Page.ClientScript.GetPostBackEventReference(UpdatePanel2, string.Empty);
string validateFinancial = "window.onload = function() { ValidateFinancialDate(); " + postbackReference + "; return false;};";
Page.ClientScript.RegisterStartUp(this.GetType(), "MyScript", validateFinancial, true);
Please pay attention to true argument of RegisterStartUp method, this will wrap validateFinancial script contents into tags automatically.
But this workaround with double postback seems artificial for the problem you're trying to solve, if you provide more source code
we can find better solution.

Error while trying to get asp.net(C#) textbox text from ajax static WebMethod

I am using an ajax htmleditor in asp.net web application so i am trying to get the text the user has entered in the editor then i will send that text back to the client javascript function that will show the text in a div. But I am getting this error "Object reference not set to an instance of an object."
Firstly i tried to access the text of textbox linked with htmleditorextender through javascript but it was not working for me so i moved to ajax webmethod but this time also i am facing a problem. Please Help me.
[System.Web.Services.WebMethod]
public static string seteditor()
{
String x="";
try
{
Content c = new Content();
x = c.txteditor.Text;
}
catch (Exception ex) { x=ex.Message; }
return x;
}
Here, txteditor is the ID of asp:textbox which is linked with ajaxcontroltoolkit htmleditorextender.
You cannot get your aspx controls inside a static method.
If you are Calling a static method from jquery means the Page and its Controls don't even exist. You need to look another workaround for your problem.
EDIT:
I always pass my control values to page methods like this:
Assume I have two text controls: txtGroupName and txtGroupLevel
...My JS with Jquery will be :
var grpName = $("#<%=txtGroupName.ClientID%>").val();
var grpLevel = $("#<%= txtGroupLevel.ClientID %>").val();
data: "{'groupName':'" + grpName + "','groupLevel':'" + grpLevel + "'}",
Where groupName and groupRights are my webmethod parameters.
EDIT2:
Include your script like this:
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>"></script>
I suggest you to use the latest jquery version.
Web methods do not interact with the page object or the control hierarchy like this. That's why they're static in the first place. You need to pass the text from the client as a parameter to the web method, not read it from the textbox.
This issue was torturing me from last 18 hours continuouslyFirst I tried javascript than webmethod and than on user1042031's suggestion I tried jquery and than again I tried javascript and look how much easily it can be done with a single line of code.
var a = document.getElementById('<%= txteditor.ClientID %>').value;
read this stackoverflow article Getting Textbox value in Javascript
I apologize to everyone who responded me in this question but i have not found that article in my initial search.

Get guid values with js and razor

I have an Asp.Net mvc 3 project
I'm using razor, and need to generate guids in javascript
I was trying this:
<script type="text/javascript">
$(document).ready(function () {
function getNewGuid() {
return '#Guid.NewGuid()';
}
I'm using inside the click event for a button, but the second call to the function is returning the same value
What should I do for reevaluating the function with each call?
The
#Guid.NewGuid()
is evaluated server-side when the page is rendered, so you will always get the same value.
You need a Javascript Guid library from somewhere.
Try the accepted answer to this question.
While you could make an Ajax call to the server, it's pretty pointless if all you're after is a unique value that could be generated far more efficiently client-side.
Create a controller then use JSON to return a new Guid from the server. Then use $().ajax to get the value.
If you don't want to ask the server for one use the following answer
Create GUID / UUID in JavaScript?

Categories

Resources