New Div Created WIth Ajax Call and Image/Link Click Gets Disabled - c#

I've an image uploader in a project and uploading images with Ajax that works perfect. It shows uploaded images instantly without page refresh. Here is the code that I am using to upload images:
<script>
$(function () {
$('#btnUpload').click(function () {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var test = new FormData();
for (var i = 0; i < files.length; i++) {
test.append(files[i].name, files[i]);
}
$.ajax({
url: "../UI/Upload.ashx",
type: "POST",
contentType: false,
processData: false,
data: test,
success: function (result) {
alert(result);
//This section refreshes the div with uploaded images and shows images without full page refresh
$('#divImages').load(document.URL + ' #divImages');
},
error: function (err) {
alert(err.statusText);
}
});
});
});
</script>
<input type="file" id="FileUpload1" />
<input type="button" id="btnUpload" value="Upload Files" />
<div id="divImages" clientidmode="Static" runat="server">
<asp:Label ID="labelImages" ClientIDMode="Static" runat="server"></asp:Label>
</div>
The problem is after uploading images, the images are shown in the content but unable to click the images and a 'Delete' link is associated with every image that also seems to be blocked. Then when I refresh the full page, the click on the images and links works. I am not sure why it happens? In the inspect element of the browser, I can see newly div created inside like the below:
<div id="divImages"> //The newly created div after partial refresh with Ajax every time I upload image
<div id="divImages" clientidmode="Static" runat="server">
<asp:Label ID="labelImages" ClientIDMode="Static" runat="server"></asp:Label>
</div>
</div>
Does it prevent me to click on the images/buttons or anything else? Would be grateful if it is pointed out.
This is the code I am using for deleting images with links (Basically I am using the links as button):
$('#divImages a.deleteLink').click(function () { //Ajax used to delete images from 'Images' folder with jQuery
var image = $(this).attr("img");
$.ajax({
type: "POST",
url: "../UI/DeleteImage.ashx",
data: "imageName=" + image,
contentType: 'application/x-www-form-urlencoded',
success: function (response) {
if (response == "true") {
$('#divImages a.imageLink[imgsrc*=\"' + image + '\"]').fadeOut();
$('#divImages a.deleteLink[img=\"' + image + '\"]').fadeOut();
}
},
error: function (response) {
alert('There was an error. ' + response);
}
});
});
});

The OP asked me to post this as an answer and I can't do anything about it.
See my explanation in the comments section
$('body').on('click', '#divImages a.deleteLink', function() {

Related

how to execute server side click event after jquery pop up messgae

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$("[id*=btnModalPopup]").live("click", function () {
$("#modal_dialog").dialog({
title: "jQuery Modal Dialog Popup",
buttons: {
ok: function () {
$(this).dialog('close');
__doPostBack('btnModalPopup', 'OnClick');
//document.getElementById("btnModalPopup").click();
}
},
modal: true
});
return false;
});
</script>
<body>
<form id="form1" runat="server">
<div id="modal_dialog" style="display: none">
This is a Modal Background popup
</div>
<asp:Button ID="btnModalPopup" runat="server" Text="Show Modal Popup" ClientIDMode="static" OnClick="btnModalPopup_Click" />
</form>
</body>
Above Code Shows J query popup Message.It Works fine. but after popup message i need to execute server Side Code
if i Remove Return False from the script it execute the server Side Code But Popup message disappears. It should execute After popup's OK button Click
Please help....
Server Side Method
[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
return "Hello " + name + Environment.NewLine + "The Current Time is: "
+ DateTime.Now.ToString();
}
Client Side
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "CS.aspx/GetCurrentTime",
data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function(response) {
//do
}
});
}
function OnSuccess(response) {
btnModalPopup_Click();
}
Call ASP.Net Page Method using jQuery AJAX Example
Add ClientIdMode='static' to your button, return false from your event handler and try this in your OK button callback
OK: function() {
$(this).dialog('close');
__doPostBack('btnModalPopup','OnClick');
}

jQuery progress bar until save in database asp.net

In an Asp.Net application I need the jQuery progress bar that runs till the data is not saved in database
For this I created a web service and the Ajax jQuery function and the progress bar Javascript plugin
HTML
<div id="progressbar"></div>
<div id="result"></div>
<asp:Label runat="server" ID="lbldisp" Text= "Percentage Completed : "/>
<asp:Label runat="server" ID="lblStatus" />
<asp:Button ID="btnSave" runat="server" Text="Save" class="buttonstyle" />
Script (I am using Sys.Application.add_load instead of document.ready function due to DOM Interruption )
<link type="text/css" href="CSS/ui.all.css" rel="stylesheet" />
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script src="js/ui.core.js" type="text/javascript"></script>
<script src="js/ui.progressbar.js" type="text/javascript"></script>
<script type="text/javascript">
Sys.Application.add_load(function() {
// jquery Progress bar function.
$("#progressbar").progressbar({ value: 0 });
$("#lbldisp").hide();
//button click event
$("#ctl00_ContentPlaceHolder1_btnSave").click(function() {
$("#ctl00_ContentPlaceHolder1_btnSave").attr("disabled", "disabled")
$("#lbldisp").show();
//call back function
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "JobCard.aspx/InsertData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
$("#progressbar").progressbar("value", 100);
$("#lblStatus").hide();
$("#lbldisp").hide();
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
$("#lblStatus").text((value + 1).toString() + "%");
}
}
</script>
Web service
[System.Web.Services.WebMethod]
public static string InsertData()
{
fortest jobcardForm = new fortest();
//this is a line 760 --> jobcardForm.Insert_OilService();
jobcardForm.Insert_TuningService();
jobcardForm.Insert_OtherServices();
jobcardForm.Insert_QRCService();
jobcardForm.Insert_problemTaken();
jobcardForm.Insert_ActionTaken();
jobcardForm.Insert_SpareParts();
//Insert_Technician();
dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter insertjobcard = new dsJobCardTableAdapters.Select_JobCarRegistrationTableAdapter();
string a = insertjobcard.Insert_JobCarRegistration(
jobcardForm.txtdate.Text, jobcardForm.txtTimeIn.Text,
jobcardForm.txtTimeOut.Text, jobcardForm.Txt_RegNo.Text,
jobcardForm.Txt_FleetNo.Text,
jobcardForm.chkbkdvechle.Checked, jobcardForm.chkwalkin.Checked,
jobcardForm.chkRepeatJob.Checked,
jobcardForm.txtCustomerName.Text, jobcardForm.txtRiderName.Text,
jobcardForm.txtPhoneNo.Text, jobcardForm.txtEmail.Text,
Convert.ToInt32(jobcardForm.ddl_ServiceAdvisor.SelectedValue),
Convert.ToInt32((jobcardForm.ListBox1.SelectedValue == "" ? "0" : jobcardForm.ListBox1.SelectedValue)),
jobcardForm.ddl_Model.SelectedValue,
jobcardForm.ddl_type.SelectedValue, jobcardForm.txtKMSRUN.Text,
jobcardForm.ddl_color.SelectedValue
, "1", HttpContext.Current.Session["user_id"].ToString(),
jobcardForm.txtdateout.Text, jobcardForm.txtchassis.Text,
jobcardForm.ddlyear.SelectedValue, jobcardForm.txtexpirydate.Text,
jobcardForm.txtnotes.Text,
jobcardForm.ddllocation.SelectedValue).ToString();
HttpContext.Current.Response.Redirect(HttpContext.Current.Request.RawUrl);
return "Save Completed...";
}
Looks like the script is working fine but I am getting an error in the web browser console Window and the error is "500 Internal Server Error" at line 760 in web service jobcardForm.Insert_OilService();. But when I use the web service code in server side onclick event the data is inserted into the database. I need the progress bar, that's why I have to change the logic using web service
ERROR
I normally create an object of a class to use it in a static method and this was the simplest way to use a non-static method in a static method.
Why dont you do something like this:
function FunctionName() {
$.ajax({
type: "POST",
url: ,
data: JSON.stringify(),
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#progress-bar").show();
$("#progress-bar1").hide();
},
complete: function () {
$("#progress-bar").hide();
$("#progress-bar1").show();
},
success: function () {
}
});
}
And have 2 div
<div class="gap"></div>
<div id="progress-bar" style="display:none;">
<img src="~/Images/ajax-progressbar.gif" />
</div>
<div id="progress-bar1"></div>
</div>
So before you send your request you show $("#progress-bar").show(); once once the content loaded you hide it. Hope this answer your question.

how to save canvas image and share to facebook using fb.api

i want to save canvas image to folder and share that in facebook on wall of the user logged i'm using html2canvas plugin but my issue is the div element is not getting drawn in the canvas the data in the div is coming from database following is the code i have written.
HtmlCode:
<div class="fan_wrap">
<ul class="fan_list">
<% foreach (ProfileDetails currentFollowers in AllFollowers)
{
%>
<li <%if (currentFollowers.ID != 0) { Response.Write("class=\"locate\""); } %>>
<img src="<%=currentFollowers.ProfileImg %>" alt="<%=currentFollowers.Name %>" title="<%=currentFollowers.Name %>" />
<div class="frame"></div>
</li>
<%} %>
</ul>
<div class="clearfix"></div>
<div class="logo_water_mark">
<img src="images/trans_logo.png" alt="" />
</div>
</div>
Javascript Code:
$(document).ready(function () {
$('#share_lnk').on('click',function () {
html2canvas($('.fan_wrap'), {
onrendered: function (canvas) {
var image = canvas.toDataURL("image/jpeg");
var url = canvas.toDataURL("image/jpeg");
image = image.replace('data:image/jpeg;base64,', '');
$.ajax({
type: 'POST',
url: 'FacebookLogin.aspx/UploadImage',
data: '{ "imageData" : "' + image + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
alert('Image saved successfully !');
}
});
var newImg = document.createElement("img");
newImg.src = url;
document.body.appendChild(newImg);
}
});
});
});
First thing is that you have to save the canvas image on the domain from where you want to share it as your facebook app supports only one. next you can share the url of the pic to be sharer like below:
FB.ui({
method: 'feed',
name: "some name",
link: "somelink.com",
picture: urltobeshared,
caption: 'some caption',
description: "some descrtiption",
},
function(response) {
if (response && response.post_id) {
console.log('Thank you');
}
}
);
},
docs are here.Hope that helps

How can c# codebehind fire JavaScript code?

I have some JavaScript code that will display a modal dialogue box asking the user to wait while it runs a web service that could take several seconds to run. What cannot figure out is how to launch the JS code from my C# code running in the server. Here is the scenario:
1) User clicks asp:Button code that launches server code.
2) Server code [somehow] fires a browser event that launches the JS code that calls the web service
The JS code looks like this:
<form id="form1" runat="server">
<div>
<script type="text/javascript">
$(function () {
$('#btn_BeginProcessB').click(function (event) {
event.preventDefault();
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $this = $(this);
var $Loader = $('#Loader');
// show loading indicator
$Loader.show();
$("body").css({ background: "#C8C5C5" });
// Begin process
$.ajax({
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Seconds: $Seconds }),
url: 'SimpleWebService.asmx/LongRunningProcess',
error: function (xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
// show button
// hide loading indicator
$Loader.hide();
},
success: function (data) {
alert("Data:" + data.d);
// show button
// hide loading indicator
$Loader.hide();
$("body").css({ background: "#FFFFFF" });
}
});
});
});
</script>
<script type="text/javascript">
function LoadPageWorking() {
var $Seconds = $("INPUT[id*='txtSeconds']").val();
var $Message = $("INPUT[id*='txtMessage']").val();
var $WorkingMessage = $('#WorkingMessage');
$WorkingMessage.text($Message);
var $data = JSON.stringify({ Seconds: $Seconds });
PageWorking('Loader', 'SimpleWebService.asmx/LongRunningProcess', $data, PageWorkingSuccess, PageWorkingError);
};
function PageWorkingSuccess(data) {
$("SPAN[id*='lblResult']").html("<br /><b>Result:</b>" + data.d + "<br />");
$('body').css('background', originalBackground);
};
function PageWorkingError(xhr, textStatus, errorThrown) {
alert('Error! ' + errorThrown);
$('body').css('background', originalBackground);
}
</script>
<!--- HTML --->
<div id="Page">
<h1>
Long Running Process Test Page</h1>
<p>
This site demonstrates how to invoke a long running process and let the user know
that the process is underway. When the button is clicked, it calls a web service
that sleeps for the designated number of seconds and returns a message.</p>
<br />
Enter number of seconds for worker process to sleep:
<asp:TextBox ID="txtSeconds" runat="server" Width="25" Text="3" /><br />
Enter the message to be displayed while the process is working:
<asp:TextBox ID="txtMessage" runat="server" Text="Working...(please be patient)"
Width="300px" /><br />
<asp:Label ID="lblResult" runat="server" />
<br />
<input type="button" id="btnBegin" value="Click to test LoadPageWorking function"
onclick="LoadPageWorking();" />
</div>
<div id="Loader">
<center>
<span id="WorkingMessage">Default Loader Message</span>
<div class="ProgressBar-Animated">
</div>
</center>
</div>
</div>
</form>
What code can I write in my C# event that will fire the LoadPageWorking() JS function?
Even if you have a server side button control, you can use it's onclientclick property to call javascript directly. But if you have to call the script from code behind, you can use ClientScriptManager.RegisterStartupScript() or ClientScriptManager.RegisterClientScriptBlock() based on your requirement. There are plenty of examples out there.
Have the button trigger a page working function that creates some indicator that you are working, fire off the ajax request, and when it comes back finish the working and hide the indicator. No need to ever have to go to code behind.
Why don't you have your LoadPageWorking() start the server, then show the JS modal popup? You can have your popup poll your service to determine if it's completed, and hide itself when it is.
You should try using the RegisterClientScriptBlock method. It will allow you to dynamically add script sections to your page's source. You can include any Javascript you'd like, including invocation of a method already defined in the page.

Jquery .ajax async postback on C# UserControl

I'm working on adding a todo list to a project system and would like to have the todo creation trigger a async postback to update the database. I'd really like to host this in a usercontrol so I can drop the todo list onto a project page, task page or stand alone todo list page.
Here's what I have.
User Control "TodoList.ascx" which lives in the Controls directory.
The script that sits at the top of the UserControl. You can see where I started building jsonText to postback but when that didn't work I just tried posting back an empty data variable and removed the 'string[] items' variable from the AddTodo2 method.
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({ tdlId: 1, description: "test test test" });
//data: jsonText,
$.ajax({
type: "POST",
url: "TodoList.aspx/AddTodo2",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg.d);
},
error: function() {
alert("error");
}
});
});
});</script>
The rest of the code on the ascx.
<div class="divTodoList">
<asp:PlaceHolder ID="phTodoListCreate" runat="server">
<div class="divTLDetail">
<div>Description</div>
<div><asp:TextBox ID="txtDescription" runat="server"></asp:TextBox></div>
<div>Active</div>
<div><asp:CheckBox ID="cbActive" runat="server" /></div>
<div>Access Level</div>
<div><asp:DropDownList ID="ddlAccessLevel" runat="server"></asp:DropDownList></div>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phTodoListDisplayHeader" runat="server">
<div id="divTLHeader">
<asp:HyperLink ID="hlHeader" runat="server"></asp:HyperLink>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phTodoListItems" runat="server">
<div class="divTLItems>
<asp:Literal ID="litItems" runat="server"></asp:Literal>
</div>
</asp:PlaceHolder>
<asp:PlaceHolder ID="phAddTodo" runat="server">
<div class="divTLAddItem">
<div id="divAddButton">Add Todo</div>
<div id="divAddText"><asp:TextBox ID="txtNewTodo" runat="server"></asp:TextBox></div>
</div>
</asp:PlaceHolder>
<asp:Label ID="lbTodoListId" runat="server" style="display:none;"></asp:Label></div>
To test the idea I created a /TodoList.aspx page that lives in the root directory.
<uc1:TodoList runat="server" ID="tdl1" TodoListId="1" ></uc1:TodoList>
The cs for the todolist.aspx
protected void Page_Load(object sender, EventArgs e)
{
SecurityManager sm = new SecurityManager();
sm.MemberLevelAccessCheck(MemberLevelKey.AreaAdmin);
}
public static string AddTodo2()
{
return "yea!";
}
My hope is that I can have a control that can be used to display multiple todo lists and create a brand new todo list as well.
When I click on the #divAddButton I can watch it build the postback in firebug but once it completes it runs the error portion by alerting 'error'. I can't see why.
I'd really rather have the response method live inside the user control as well. Since I'll be dropping it on several pages to keep from having to go put a method on each individual page.
Any help would be appreciated.
I wasn't able to get the jquery ajax to work so I backed up and tried just putting the div and the jquery on the page itself and created a webservice.asmx page to handle the postbacks.
I'm still getting the error returned from the jquery and wondering if I've got something configured wrong or some other issue.
Here's the todo.aspx
<asp:Content runat="server" ContentPlaceHolderID="cpHolder" ID="ContentId">
<div id="divAddButton">Add Todo</div>
<script type="text/javascript">
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({ Todo: { TodoId: 1, Description: "test test test"} });
//var jsonTextEmpty = jsonText.stringify({""});
$.ajax({
type: "POST",
url: "WebService.asmx/HelloWorld",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg);
},
error: function() {
alert("error");
}
});
});
});
The webservice.asmx is unchanged from the default bit Visual Studio created. Is there a way to find out what is causing the error?
In order to do this with jQuery as you describe, you need to sent it to a decorated method in your ASPX.cs file, you cannot send directly to the .ascx method. The good news is that the aspx.cs method can call the ascx one, so it is really pretty easy and you can just use it as a pass through to that.
[WebMethod]
public static string AddTodo2(myTodo todo2add)
{
//call your ascx method here
mymethod(todo2add.td1Id,todo2add.description);
return "yea!";
}
at the end of the aspx.cs, or in another class library put in your class so it knows how to decode the stuff:
public class myTodo
{
/// <summary>
/// web service/webmethod needs 0 parameter constructor
/// </summary>
public myTodo()
{
}
public myTodo(int tdlId, string description)
{
TdlId= tdlId;
Description= description;
}
public int TdlId;
public string Description;
}
slight change to the ajax call:
$("#divAddButton").click(function() {
var jsonText = JSON.stringify({myTodo:{ tdlId: 1, description: "test test test" }});
$.ajax({
type: "POST",
url: "TodoList.aspx/AddTodo2",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('retrieved');
$("#divAddButton").text(msg.d);
},
error: function() {
alert("error");
}
});
});

Categories