__doPostBack not working for me - javascript

Is there an error in the way i use the __doPostBack?
function displaymessage() {
var scl = "aaaaaa";
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, 'OtherInformation');
alert(scl);
}
<input type="button" value="Click me!" id="Button2" onclick="displaymessage()" />
When i press the button it should call the RaisePostBackEvent in the code file, but it doesn't. If i comment the doPostBack it reaches the alert but when it is uncommented it does not. So it must be an error in the usage of the doPostBack.
I followed this post: Call ASP.NET function from JavaScript?

Place the following script on the header section of your html file:
<script>
function __doPostBack(eventTarget, eventArgument) {
document.Form1.__EVENTTARGET.value = eventTarget;
document.Form1.__EVENTARGUMENT.value = eventArgument;
document.Form1.submit();
}
</script>

for me the _dopostback() was not firing only on IE and chrome browser. I have resolved by adding "return false;" statement in the javascript function. for example:-
function test()
{
_dopostback("logout","");
return false;
}
now its working fine.

Change you code to this:
setTimeout(function () { __doPostBack('btnSave', '') }, 500);
Use btnSave Id. It will work in all browsers.

Drop your second argument of __doPostBack ('OtherInformation'), and replace with an empty string, ''. You could put that data in a hidden input field if you need it, and retrieve it using Request.Form.

I also followed the same post you mentioned and got an error, I tried to use the other answers here but it still didn't work.
Until I've found this post:
http://forums.asp.net/t/1197643.aspx
(look in the 8th reply made by NC01).
1.basically the idea is that your aspx should have something like this:
<script type="text/javascript" language="javascript">
function myfunction() {
if ('<%=Page.IsPostBack%>' == 'False') {
var pageId = '<%= this.UniqueID %>';
__doPostBack(pageId, 'do_something_good');
}
}
</script>
2.then in your .cs you should add interface IPostBackEventHandler (for example:)
public partial class _default : System.Web.UI.Page, IPostBackEventHandler
3.and in your .cs in page_load add this line:
this.ClientScript.GetPostBackEventReference(this, string.Empty);
4.don't forget to implement the interface:
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == "do_something_good")
{
//bla
}
}
And guess what - it even works!
#Subhash Dike - The PageMethods works only for static methods, AFAIK.

Add EnableEventValidation="false" into your <%Page tag to solve __doPostBack problem

Related

Get notified when the submitted POST request finishes (if the response is not HTML)

In the master page of all my web form pages I've set up an overlay which blocks user interation whenever form submitted until browser renders next page response:
<script type="text/javascript">
function overlayWhenSubmit() {
document.getElementById('spinnerOverlay').style.display = 'block';
}
//spinnerOverlay has position:fixed and top/bottom/left/right:0
</script>
protected override void OnPreRender(EventArgs e) {
this.ClientScript.RegisterOnSubmitStatement(
typeof(Page), null, "overlayWhenSubmit();"
);
base.OnPreRender(e);
}
This works great until I try to provide file download:
public static void DownloadFile(this System.Web.HttpResponse #this, string physicalFilePath) {
#this.ContentType = "application/octet-stream";
#this.AppendHeader("Content-Disposition", $"Attachment; filename=\"{Path.GetFileName(physicalFilePath)}\"");
#this.TransmitFile(physicalFilePath);
}
// ... then in some event handler in my page:
Response.DownloadFile(thePathOfFileToDownload);
The file downloads OK, but the original page keeps being overlaid and therefore unusable.
Is there a way the page can get notified when the submitted request has finished so it can turn off the overlay?
The closest thing so far is try not to popup the overlay for the control which leads to non-HTML response:
<script type="text/javascript">
function overlayWhenSubmit() {
if (!document.getElementById('noOverlayWhenSubmit').value)
document.getElementById('spinnerOverlay').style.display = 'block';
document.getElementById('noOverlayWhenSubmit').value = '';
}
function noOverlayWhenSubmit() {
document.getElementById('noOverlayWhenSubmit').value = true;
}
</script>
<input type="hidden" id="noOverlayWhenSubmit" value="" />
<asp:Button runat="server" OnClientClick="noOverlayWhenSubmit()"></asp:Button>

Uncaught TypeError: Cannot read properties of undefined (reading 'get') at HTMLInputElement.geocodio

I am having issues trying to run an API using Geocodio. This is set up through WordPress and I would really appreciate any help I can get!
Everything works up until the actual API itself has to run. The Geocodio documentation states that it runs "using a jQuery AJAX call". I have tried multiple script sources that claim to fix the problem, but I get the error that "superfish() is not a function" or that "Cannot read properties of undefined (reading 'get')".
<head>
<script src="jQuery.js"></script>
<script src="superfish.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('ul.sf-menu').superfish();
});
</script>
</head>
<body>
<input type="text" id="myTxt" style="width: 400px;" placeholder="Type Your Address Here!"></input>
<input type="submit" id="myBtn" value="Search Now!"></input>
<script>
var submit = document.getElementById("myBtn")
var myInput = document.getElementById("myTxt")
submit.addEventListener("click", geocodio)
function geocodio() {
if(myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
$.get('https://api.geocod.io/v1.7/geocode?q='+ encodeURIComponent(myInput)
+'&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results)});
}
};
</script>
</body>
You must be using some strange version of jQuery that forces you to refer to it as jQuery and not $. Odd, I thought all versions of jQuery also set up the $ global.
Try replacing $ with jQuery inside geocodio():
function geocodio() {
if (myInput.value.length == 0) {
alert("Please input a valid address")
}
else {
jQuery.get('https://api.geocod.io/v1.7/geocode?q=' + encodeURIComponent(myInput.value)
+ '&api_key=' + encodeURIComponent('YOUR_API_KEY'), function (response) {
console.log(response.results);
});
}
}
(also fixed: encode myInput.value instead of encoding whole input)
If that doesn't work, perhaps jQuery.js failed to load. Check the console messages and/or network trace tab in the developer tools.
If that doesn't work, try stepping thru the code using the JavaScript debugger built in to your browser (short tutorial video).

How to pass values to an external Javascript script from ASP.NET

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.

Why is google apps script changing my user property to some random code every time I save it?

I am creating an editor add-on for google sheets and I'm currently stumped on why my user property (MY_WEBHOOK) is being changed every time I try to save it with setProperty to this code:
function(){var L=h(fb(arguments));if(b&32)Vd(function(){a.apply(g||this,L)});else return m(a.apply(g||this,L))}
Here is the code I am using:
code.gs:
function saveSettings(url) {
PropertiesService.getUserProperties().setProperty('MY_WEBHOOK', url);
SpreadsheetApp.getUi().alert("Saved")
}
function getSettings() {
return PropertiesService.getUserProperties().getProperty('MY_WEBHOOK');
}
In my html file:
<body onload="get()">
<form>
<label>What is the URL?</label>
<input id="webhook-url" type="url" autofocus required placeholder="Webhook Here">
<br><br>
<input type="button" value="Save" onclick="save()">
<script>
function save() {
var url = document.getElementById('webhook-url').value
google.script.run.saveSettings(url)
alert(url)
alert(google.script.run.getSettings)
google.script.host.close()
}
function get() {
var settings = google.script.run.getSettings
document.getElementById('webhook-url').value = settings;
}
</script>
</form>
</body>
Modification points:
I think that there are 2 modification points in your script.
About google.script.run.getSettings, in this case, the function of getSettings is not run. Please add () like google.script.run.getSettings(). By this, the function is run.
I think that this is the reason of your issue.
About alert(google.script.run.getSettings) and var settings = google.script.run.getSettings, google.script.run returns no value. So in this case, withSuccessHandler is used.
google.script.run is run with the asynchronous process.
When above points are reflected to your script, it becomes as follows.
Modified script:
Please modify your Javascript as follows.
function save() {
var url = document.getElementById('webhook-url').value
google.script.run.withSuccessHandler(() => {
google.script.run.withSuccessHandler(e => {
alert(e);
google.script.host.close();
}).getSettings();
}).saveSettings(url);
}
function get() {
google.script.run.withSuccessHandler(settings => {
document.getElementById('webhook-url').value = settings;
}).getSettings();
}
When above script is used, at first, the value is retrieved from getSettings by get(), and when the value is inputted and click button, the value is put by saveSettings() and the current value is retrieved by getSettings() and alert() is run, and then, google.script.host.close() is run.
Note:
This is a simple modification. So please modify it for your actual situation.
Reference:
Class google.script.run

Go to URL if input val == something

So, I've found this JSFiddle example. In JSFiddle works well, the problem is that, even if I search any != from "advogados" (just testing), the browser goes to: http://www.site.com/index.html?procura=teste
No jQuery conflict, no html issue.
Here's JS
$("#procura").on("submit", function(event){
// prevent form from being truely submitted
event.preventDefault();
// get value of text box
name = $("#procura_texto").val();
// compare lower case, as you don't know what they will enter into the field.
if (name.toLowerCase() == "advogados")
{
//redirect the user..
window.location.href = "http://jornalexemplo.com.br/lista%20online/advogados.html";
}
else
{
alert("no redirect..(entered: " + name + ")");
}
});
If your javascript is somewhere in your HTML before your <form> your $("#procura") will be an empty set, so the submit-action won't be bound to anything. Try following code:
<html>
<head>
<script type="text/javascript" src="/path/to/your/jquery.js"></script>
<script type="text/javascript">
$(function() {
// This code will be run if your document is completely
// parsed by the browser, thus all below elements are
// accessible
$('#procura').on('submit', ....);
});
</script>
</head>
<body>
<form id="procura">...</form>
</body>
</html>
$(function() {}) is also known as $(document).ready(function() {}), (documentation)
You aren't defining the variable name. http://jsfiddle.net/zwbRa/59/
var name = $("#procura_texto").val();

Categories