Here i am calling a javascript function on a button click and i need to call the server side method inside the javascript function after finishing its execution.
Javascript Function
function exportCharts(exportFormat) {
initiateExport = true;
for (var chartRef in FusionCharts.items) {
if (FusionCharts.items[chartRef].exportChart) {
document.getElementById("linkToExportedFile").innerHTML = "Exporting...";
FusionCharts.items[chartRef].exportChart({ "exportFormat": exportFormat });
}
else {
document.getElementById("linkToExportedFile").innerHTML = "Please wait till the chart completes rendering...";
}
}
}
Server side Method
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
try
{
PredictExportToPPT objOExporttoPPT = new PredictExportToPPT();
PredictionModel();
string reportNames = ObjCommon.GetBIReportNames("Prediction", "Report");
reportNames += ObjCommon.GetBIReportNames("Prediction", "Table");
objOExporttoPPT.ExportToPPTPredict(ObjPredictInputParameter, reportNames, ObjSharedEntities.PredictTableData);
string itemname = "PPTOutput.pptx";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "pptx";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + itemname + "");
HttpContext.Current.Response.BinaryWrite(System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(DataTemplate.PPTOutputTemplateFilePath)));
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
catch (Exception exceptionMessage)
{
throw (exceptionMessage);
}
finally
{
GC.Collect();
}
}
and i have tried like this
$(document).ready(function () {
$("#imgBTNExportPPT").click(function (e) {
e.imgBTNExportPPT_Click();
$.ajax({
type: "POST",
url: "PEventPerformance.aspx/updateContent",
data: "{}",
success: function (result) {
}
});
});
});
Any suggestion??
Your imgBTNExportPPT_Click looks like an click event of a button. You may try the following to raise the event from JavaScript
Place this javascript in aspx page
<script type="text/javascript">
function myfunc() {
<%= Page.ClientScript.GetPostBackEventReference(imgBTNExportPPT, String.Empty) %>;
}
</script>
Call this function against OnClientClick
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="myfunc();" />
This will fire the server side event:
protected void imgBTNExportPPT_Click(object sender, ImageClickEventArgs e)
{
}
You can use Ajaxpro for this purpose, If u want to generate a server side call without any event like button click.
In Your code behind file. Under the Page_Load section add
AjaxPro.Utility.RegisterTypeForAjax(typeof(YourCodebehindfilename));
In client side
call the server side method like
var content = YourCodeBehind.Yourmethod(optional parameters).value;
In content you can get your response as an object and can do further changes
I guess the best way to execute server side method is to use Web Services.
You have to write a Web Service that that contains your server side method.Then you can call it using AJAX.
Related
I need to fire this script from code behind only on certain dates specified in the database
I need to show an image as a fancybox based on the date specified in CMS system.
I will write my logic to show image or not in the Default.aspx and then somehow pass this piece of code from default.cs to MarterPage Javascript $(window).load(function () Code Block
<Script>
$(window).load(function () {
I want this code to fire at a particular location of master page. I am not sure suppose here.
///HERE???
});
</Script>
I want to pass below script as a value so that it js execute ///HERE??? part of code
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');", true);
I am bit lost with this ...
I simple want to do my logic check in Default.aspc file and show image as a fancy box only in default.aspx page. But my ' $(window).load(function () { });code block is in MasterPage file if i write another ' $(window).load(function () { }); in default.aspx file then fancy box is not showing properly.
How can i achieve this without any issue
UPDATE:
I managed to pull it off.. this is based on the solution posted by Irina Bogomaz.
So far this is working I can add full logic to code-behind later on.
$(window).load(function () {
if (window.showMessage) {
// alert(imgPath);
//logic to create fancybox
$("a.fancybox-messageboard").fancybox({
width: 600,
height: 440,
closeClick: true,
hideOnOverlayClick: true,
href: imgPath
}).trigger('click');
}
});
CODE BEHIND
protected override void OnPreRender(EventArgs e)
{
string imgMB = "'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg'";
string sScript = "var showMessage = true; var imgPath=" + imgMB;
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", sScript, true);
}
Try this:
string myscript = "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');"
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "<script>" + myscript + "</script>", false);
You can achieve this in the following way:
Master page:
<script type="text/javascript">
$(window).load(function () {
if (window.isFancybox) {
//logic to create fancybox
}
});
</script>
Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
var fanceBoxDate = new DateTime(2013, 11, 20); //get date from CMS system
if (DateTime.Today == fanceBoxDate)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "fancyBox", "var isFancybox = true", true);
}
}
may be u will use this way
first make aspx page to get service and use web method (_service.aspx)
public partial class _service : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string binddata(yourObject yourDatabaseObject)//tbl_BI_mant[]
{
//connect to Database
//and add your Date filter
return Data.getpictureWithDateFilter(yourDatabaseObject.datefilter)
}
}
then in your default.aspx page call that service with jquery ajax
$(function () {
$.ajax({
url: '../_service.aspx/binddata',
type: 'POST',
data: " {'yourDatabaseObject':" + JSON.stringify(Parameters) + "}",
datatype: 'html',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');;
},
error: function (request, status, err) {
// alert(status);
//alert(err);
}
});
});
I want to call a c# function from JavaScript. I tried the solution specified in Call ASP.NET function from JavaScript? but the RaisePostBackEvent is not getting called.
My JavaScript is:
<script>
function link_load() {
var pageId = '<%= Page.ClientID %>';
__doPostBack(pageId, argumentString);
document.getElementById("sidebar1").innerHTML = "working";
}
</script>
My C# code is:
public void RaisePostBackEvent(string eventArgument)
{
sidebar1.InnerHtml = "working inside";
}
The JavaScript code is executed, which I verified.
[webmethod]
public void RaisePostBackEvent(string eventArgument)
{
sidebar1.InnerHtml = "working inside";
}
in javascriptenter code here
<script type="javascript">
$.ajax({
url:'pagename.aspx/RaisePostBackEvent'`enter code here`
enter code here
});
</script>
I am creating registration page and doing null field validation on submit button click using jquery. if there is any error in form validation then i am preventing default method call using jquery, so it will not call code behind button click event.
Problem:
sometimes user double clicked on button and this is calling code behind button click event two times with two database row insertion having a same data.
I tried lots of solution but unfortunately i couldn't make any success.
Please help me to solve out this problem if you have any solution.
Thanks in advance,
Actually, i was preventing default server side method call in jquery when button is clicked using e.PreventDefault() method of jquery if validation is false.
Don't know what was the problem but when i set function on client click of button and return true/false based on validation instead of e.PreventDefault, trick worked great for me.
Thanks to all who comment on this question.
Simply add a variable called 'loading' for example and check if the ajax call is busy:
At the top of your code:
var loading = false;
Then on form submit:
$('#form').submit() {
if(loading)
return false;
loading = true;
//Ajax call
$.ajax({
type: "POST",
url: "somePage.php",
data: $('#form').serialize(),
success: function(response) {
loading = false;
//Your response code
}
});
}
Use one on the client side. This will prevent double clicks.
$("#button").one("click", function() {
// validate the form.
// if form is valid, submit form
});
An alternative solution is to have a boolean flag.
var submitting = false;
$("#button").click(function() {
if (!submitting) {
submitting = true;
if (formIsValid) {
submitting = false;
$("#form").submit();
} else {
submitting = false;
}
}
});
Add disabled attribute to your button as the first thing in your js method.
function func(event) {
$("#button").prop("disabled", true);
.....
}
try this it might help for your asp button
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" UseSubmitBehavior="false" OnClientClick="ValidationCode(event); return false;" />
<script>
function ValidationCode()
{
//Code of validtion
event.preventDefault();
if(true)
{
__dopostback:("btnSubmit","");
}
}
</script>
Sample code
Client Side:
$("#submit").click(function () {
if (!YourvalidationFunction)
{
return false;
}
else {
//ajax_function is a folder contain Default.asmx page and insertNewRecord is function name (server side)
$.ajax({
type: "POST",
url: "ajax_function/Default.asmx/insertNewRecord",
data: "{ 'prefix': '" + dataString + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessinsertingwcCall,
error: OnErrorCall
});
}
});
Server Side:
[WebMethod]
public string[] insertNewRecord(string prefix)
{
string status = "";
List<string> d = new List<string>();
try
{
// logic code for insertion if success set msg
status = "New record inserted";
}
catch (Exception ac)
{
status = " Error occurs";
}
d.Add(string.Format("{0}", status));
return d.ToArray();
}
I want to set the Image URL of Image control using client side code and save the image to the server using C# code. Here is what i have implemented:
<asp:Button ID="btnImageUpload" OnClick="btnImageUpload_Click" runat="server" Text="Preview" CausesValidation="false" OnClientClick="Image_View();"/>
C# Code:
protected void btnImageUpload_Click(object sender, EventArgs e)
{
if (Directory.Exists(#"C:\\Images"))
SaveImage_Server();
else
{
Directory.CreateDirectory(#"C:\\Images");
SaveImage_Server();
}
}
public void SaveImage_Server()
{
try
{
if (FlUpldImage.PostedFile.ContentLength > 0)
{
String fn = Convert.ToString(DateTime.Now) + Path.GetFileName(FlUpldImage.FileName);
if (fn.Contains('/'))
{
fn = fn.Replace("/", "");
}
if (fn.Contains(':'))
{
fn = fn.Replace(":", "");
}
if (fn.Contains(" "))
{
fn = fn.Replace(" ", "");
}
String Saved_ImagePath = #"C://Images/" + fn; // making the path with created dynamically folder name
FlUpldImage.SaveAs(Saved_ImagePath);
HidnLocalImageURL.Value = Saved_ImagePath;
}
}
catch (Exception re)
{
}
}
JavaScript
function Image_View() {
// __doPostBack('<%= btnImageUpload.ClientID %>', '');
// var clickButton = document.getElementById("<%= btnImageUpload.ClientID %>");
// clickButton.click()
var idFlUpload = '<%= FlUpldImage.ClientID %>';
var fu1 = document.getElementById(idFlUpload);
var idImgCntrl = '<%= imgCorrect.ClientID %>';
var ImgCntrl = document.getElementById(idImgCntrl);
alert("You selected " + fu1.value);
ImgCntrl.setAttribute('src', fu1.value);
}
Now my issue is that once the server side code is executed the page gets refreshed and the link set to Image control using JS gets reset to default value.
How can i get this working wherein the image also gets saved and Image URL property also gets set through JS.
If there is any other way to implement this than please let me know. Thanks in Advance!
You have to set it on server too. You can use hidden field to save the url and access that hidden field on server to get the url to set mgCntrl.ImageUrl
In html
<input type="hidden" runat="server" id="hdnImageSrc" />
On Client javascript
hdnImageSrc = document.getElementById('<%= hdnImageSrc.ClientID %>');
mgCntrl.setAttribute('src', fu1.value);
hdnImageSrc.value = fu1.value;
On server side code
mgCntrl.ImageUrl = hdnImageSrc.Value;
i am using AjaxRequest.Get() method from AjaxRequest.
following is the inline javascript in analysis.aspx
function getAnalysis(type) {
var innerHtml;
AjaxRequest.get(
{
'url': 'getAnalysis.aspx?type=' + type
, 'onSuccess': function (req) { innerHtml = req.responseText; }
}
);
document.getElementById("div_analysis").innerHTML = innerHtml;
}
when getAnalysis(type) is called in analysis.aspx everything goes fine - ajax request is properly submitted and response is send properly. But at the end value of innerHTML remains undefined.
Following is the code of getAnalysis.aspx -
protected void Page_Load(object sender, EventArgs e)
{
if(type == "somwthing") str = load();
Response.Clear();
Response.CacheControl = "no-cache";
Response.Write(str);
Response.End();
}
When i debugged javascript using google chrome, i found that value of innerHMTL is undefined, although everything went fine.
So i dont understand why AjaxRequest class is not accepting text output from Reponse.Write().
P.S. : I have also tried Response.ContentType = "text/Html"; and Reponse.Fluch().
please guide me thnx in advance.
You need to set the div contents in the onsuccess function since it is called asynchronously when the AJAX request completes
function getAnalysis(type) {
var innerHtml;
AjaxRequest.get(
{
'url': 'getAnalysis.aspx?type=' + type
, 'onSuccess': function (req) { document.getElementById("div_analysis").innerHTML = req.responseText; }
}
);
}