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

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

Related

Asp.Net - How to call ActionResult with ajax

I want to click "2" Ajax will call ActionResult and put new question up but not rerun page
i have been trying two day but it haven't worked
People help me, please
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return View(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Json",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
In HTML:
<li>
1
</li>
enter image description here
Thanks for reading
I changed but it dont work!!
I learned it myself so it was hard to get started
ActionResult:
[HttpPost]
public ActionResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return PartialView(cauhoi);
}
Function Ajax:
<script>
function loadcauhoi(num) {
$.ajax({
dataType: "Html",
type: "POST",
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
$('#baitetstiq').html(a);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
Full HTML:
<div class="col-md-9" style="border-top-style:double;
border-top-color:aquamarine;
border-top-width:5px; margin-left:-15px">
<p style="text-align:center">
<b>Thời Gian Còn Lại Là:xxx</b>
</p>
<div id="baitestiq"></div>
#foreach(var item in Model)
{
<div class="baitest">
<div class="ques">
<img src="~/Hinh_Cauhoi/#item.Cauhoi" />
</div>
<div class="anw">
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn1" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn2" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn3" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn4" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn5" />
</div>
<div class="dapan">
<img src="~/Hinh_Cauhoi/#item.DAn6" />
</div>
</div>
<div class="numbertest">
<ul>
<li>
1
</li>
</ul>
</div>
1st you need to return a partial view.
2nd you need to make a get ajax request and not a post
3rd you need to test first the result of #Url.Action("BaiTestIQ","TestIQ"), translate this to a URL, directly to make sure it returns the expected results without the ajax call to avoid getting into sideways with routing etc. see this for example
See a working example here
Update:
I see it now, you changed dataType: "Html"
You need to change several things:
1. The method is not changing any state so it should not be declared as a post method. You need to remove [HttpPost] attribute.
You need to be aware of ajax parameters contentType and dataType. From the documentation: contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8'). This specifies what type of data you're sending to the server. And dataType (default: Intelligent Guess (XML, json, script, or HTML)) specifies what jQuery should expect to be returned. In your case, it should be 'json' because you are using the result return from a LINQ query.
So the method might look like:
public JsonResult BaiTestIQ(int id)
{
var cauhoi = from q in data.Questions
join a in data.Answers on q.MaTests equals "IQ"
where q.MaCHoi == a.MaCHoi && a.keys == id
select new baitest()
{
Cauhoi = q.Noidung,
DAn1 = a.DAn1,
DAn2 = a.DAn2,
DAn3 = a.DAn3,
DAn4 = a.DAn4,
DAn5 = a.DAn5,
DAn6 = a.DAn6,
};
return Json(cauhoi.ToList(), JsonRequestBehavior.AllowGet);
}
3. Moving to the ajax call:
<script>
function loadcauhoi(num) {
$.ajax({
url: '#Url.Action("BaiTestIQ","TestIQ")',
data: { id: num },
type: "GET",
cache: false,
dataType: "json",
success: function (a) {
// Replace the div's content with the page method's return.
alert("success");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown)}
});
}
</script>
**But I'd like to suggest another approach using a ViewModel with a partial view because serializing JSON data can sometimes get you errors. A quick tutorial

Calling a linkbutton click with jquery

I've got a textbox, I want a function to be called onkeyup, for that reason I've got a hidden button that is trying to redirect to another c# function. The problem is jquery goes inside the function, but then doesn't go to the server side event.
Here's my HTML for both elements:
<div class="row" style="margin-top: 5px;">
<div class="col-sm-12">
<div class="input-group input-group-sm">
<span class="input-group-addon">Име:</span>
<asp:TextBox ID="tbCliName" ClientIDMode="Static" runat="server" onkeyup="runQuery(this)" CssClass="form-control"></asp:TextBox>
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
<span class="input-group-addon">Егн/Булстат:</span>
<asp:TextBox ID="tbEgnBStat" ClientIDMode="Static" runat="server" CssClass="form-control"></asp:TextBox>
</div>
</div>
</div>
Here's my jquery funtion:
function runQuery(e) {
$('#hiddenButton').click();
}
And the C# for the button click:
protected void hiddenButton_Click(object sender, EventArgs e)
{
AutoComplete_Press(tbCliName.Text);
}
EDIT with Ajax:
function runQuery(e) {
var search = $(e).val();
function runQuery(e) {
var search = $(e).val();
var params = {
url: 'addEditProduct.ascx/AutoComplete_Press',
method: 'post',
contentType: 'aapplication/json',
data: '{searchClause:' + search + '}',
dataType: 'json',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
};
$.ajax(params);
}
[WebMethod]
public static void AutoComplete_Press(string searchClause)
{
int searchType = 0; //ЕГН
int csKind = 0;
Regex regex = new Regex("^[0-9]+$");
if (!regex.IsMatch(searchClause))
searchType = 1;
//if (rbLP.Checked)
// csKind = 1;
string clients = laboratory.getClients2(searchType, searchClause, 1);
}
try using webmethod. In server side
[WebMethod]
public static void BindData()
{
AutoComplete_Press(tbCliName.Text);
}
And in client side
$("#hiddenButton").click(function() {
$.ajax({
type: "POST",
url: "index.aspx/BindData",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({/*pass values here*/}),
dataType: "json",
});
});
Refer below link
https://www.aspsnippets.com/Articles/Calling-server-side-methods-using-JavaScript-and-JQuery-in-ASP.Net.aspx
The reason why it is not working is that you are using asp:LinkButton which is rendered as a element with href attribute set to javascript:__doPostBack().
If you replace asp:LinkButton to asp:Button calling $('#hiddenButton').click(); will start to work.
Just change this line of code
<asp:LinkButton ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:LinkButton>
to this
<asp:Button ID="hiddenButton" class="btn btn-default" Style="opacity: 0;" ClientIDMode="Static" OnClick="hiddenButton_Click" runat="server"></asp:Button>
You can invoke function like this but not event
Create a Web Method and try Jquery Ajax
var params = {
url: 'Index.aspx/YourWebmethod',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
data: JSON.stringify(data to be send ),
success: function (result) {
alert('Success');
},
error: function (result) { alert('Warning! It failed.'); }
};
$.ajax(params);

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

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() {

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.

Available Tennis Court Interface in MVC 3: Errors and Questions

Context:
Hello, I'm developing an on line application of Tennis Club Management... I would like to create an "Available Tennis Court Interface" that allows the user to check if a court is busy or free... So in my Interface I have one DatePicker, an image "Google Maps" of the Tennis Club and 13 labels that represents all tennis courts. So in this interface, if a tennis court is busy, I would like to "color" the label in red and if the tennis court is free, in green...
Here my Interface:
Code
For that, I'm using Jquery, JavaScript and Json... Here what I have tried to make in my View :
<script type="text/javascript">
function loadCourts() {
var maDate = $('#datePicker').val();
$.post({
type: 'POST',
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
data: "{ 'date' : " + maDate + " }",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
alert('test');
//How to use data and verify if a tennis is free or not ?
},
error: function(x, t, m) {
if (t === "timeout") {
window.HandleTimeout();
} else {
alert(t);
}
}
});
}
</script>
<h2>Emplacement(s) disponible(s)</h2>
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(chargerCourts());
});
</script>
//Here the label
<div class="AvailableCourt">
<div class="label1" align="center">
#Html.Label("1")
</div>
<div class="label2" align="center">
#Html.Label("2")
</div>
<div class="label2" align="center">
#Html.Label("3")
</div>
<div class="label2" align="center">
#Html.Label("4")
</div>
<div class="label3" align="center">
#Html.Label("5")
</div>
<div class="label4" align="center">
#Html.Label("6")
</div>
<div class="label5" align="center">
#Html.Label("7")
</div>
<div class="label6" align="center">
#Html.Label("8")
</div>
<div class="label7" align="center">
#Html.Label("9")
</div>
<div class="label8" align="center">
#Html.Label("10")
</div>
<div class="label9" align="center">
#Html.Label("11")
</div>
<div class="label10" align="center">
#Html.Label("12")
</div>
<div class="label11" align="center">
#Html.Label("13")
</div>
}
</div>
Controller method
//Get all the tennis courts and verify if a court is busy or not (Available attribute)
public JsonResult GetTennisCourt(DateTime date)
{
System.Diagnostics.Debug.WriteLine("test");
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
System.Diagnostics.Debug.WriteLine("test");
return Json(courts, JsonRequestBehavior.AllowGet );
}
When I'm using Firebug, I get an error in my function "loadCourts" and so my controller's method (getTennisCourts) is never reaches) I don't understand why:
Questions
So, my questions are :
1) Why get I an error in Firebug ?
2) Why is my Controller's method never reaches ?
3) How could I use "data" in my function "loadCourts" to check if a tennis court is free or not ?
Sorry for the length and thanks in advance...
For Darin Dimitrov :
Try like this:
// get the underlying Date object from the datepicker instead
// of using .val()
var maDate = $('#datePicker').datepicker('getDate');
$.ajax({
type: 'POST',
url: '#Url.Action("GetTennisCourt", "AvailableCourt")',
data: '{ "date":"\\/Date(' + maDate.getTime() + ')\\/" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000,
success: function(data) {
// we loop through the collection of courts
// returned by the server and we can access each
// element's properties
$.each(data, function(index, court) {
alert(court.ID);
});
},
error: function(x, t, m) {
if (t === 'timeout') {
window.HandleTimeout();
} else {
alert(t);
}
}
});
Notice that I used $.ajax instead of $.post. And I have used the datepicker's getDate method to fetch the native Date object and encode it.
I dont know C# but this line:
url: ({source:'#Url.Action("GetTennisCourt", "AvailableCourt")'}),
Is resolving the url as an object, if you had
url : '/path/to/controller'
It might work
The 'data' in the success function is JSON so you can treat it as an object.
data.xyz

Categories