how to get facebook page id using javascript sdk? - c#

I want to get page id from Facebook on custom page tab click. Here is the code, i am working with. Is this right way to get page id from the Facebook. I am able to get access token and user id values using this code. Any help is greatly appreciated.
window.fbAsyncInit = function () {
FB.init({
appId: 'xxxxxxxxx',
status: true,
cookie: true,
xfbml: true
});
FB.Event.subscribe('auth.authResponseChange', function (response) {
// Here we specify what we do with the response any time this event occurs.
if (response.status === 'connected') {
} else if (response.status === 'not_authorized') {
//FB.login();
} else {
//FB.login();
}
});
};
// Load the SDK asynchronously
(function (d) {
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) { return; }
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
} (document));
$('.btnclick').click(function () {
fblogin();
});
function fblogin() {
//FB.login();
FB.login(function (response) {
if (response.authResponse) {
var sq = FB.getAuthResponse()['signedRequest'];
var data = sq.split('.')[1];
data = JSON.parse(atob(data));
alert(data);
} else {
alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'user_location,user_hometown,user_photos,friends_photos,friends_location,friends_hometown,email,user_likes,publish_actions,manage_pages', display: 'popup' });
}

Step 1 : get manage_pages permission
step 2 :
FB.api('/me?fields=accounts', function (apiResponse) {
//apiResponse will have page id inside apiResponse.accounts.data
});
'/me?fields=accounts' - account is used to get fb pageid
For Getting page Detail form page id
FB.api('/ page id ?fields=about,albums{link},photos{link},phone,location,single_line_address', function (page) {
//To get page details from page id
});

Related

Cascading (Dependent) DropDownList using ASP.NET MVC

I have implemented Cascading (Dependent) DropDownList using ASP.NET MVC.
This is the tutorial
Now I need show alert message box after insert data and redirect on Index page in ASP.NET MVC.
To show alert message in ASP.NET MVC after insert data using store procedure from MySQL database, I have write the code like as shown below.
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
if (msg > 0)
{
alert("User Details Inserted Successfully");
window.location.href = "#Url.Action("Index", "Home")";
}
});
</script>
The data is correctly registered in the database table and the alert message box after insert data it's show.
But the redirect to index.cshtml not working because all the DropDownList on the form are empty except the first DropDownList that populates correctly.
window.location.href = "#Url.Action("Index", "Home")";
I mean that all other (populated cascading) DropDownList are enabled but empty.
I need redirect to Index Action page and being able to reload a new record, with this redirection it is impossible because the populated cascading DropDownList remain empty... instead of disabled and populated from value of first dropdownlist...
How to do resolve this?
Thanks.
Update 2021-01-02
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/DatePicker.js");
#Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(function () {
var msg = '#ViewData["result"]';
console.log(msg);
if (msg > 0)
{
alert("User Details Inserted Successfully");
var url = "#Url.Action("Index", "Home")";
window.location.href = url;
}
});
</script>
<script src="Scripts/jquery-1.10.2.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$.validator.addMethod('date',
function (value, element) {
if (this.optional(element)) {
return true;
}
var ok = true;
try {
$.datepicker.parseDate('dd/mm/yy', value);
}
catch (err) {
ok = false;
}
return ok;
});
$("#thedate").datepicker(options);
$(function () {
$(".loading").hide();
$("select").each(function () {
if ($(this).find("option").length <= 1) {
$(this).attr("disabled", "disabled");
}
});
$("select").change(function () {
var value = 0;
if ($(this).val() != "") {
value = $(this).val();
}
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: '{type: "' + id + '", value: "' + value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var dropDownId;
var list;
switch (id) {
case "CountryId":
list = response.States;
DisableDropDown("#TicketId");
DisableDropDown("#CityId");
dropDownId = "#TicketId";
list = response.Ticket;
PopulateDropDown("#TicketId", list);
break;
case "TicketId":
list = response.States;
DisableDropDown("#StateId");
PopulateDropDown("#StateId", list);
break;
case "StateId":
dropDownId = "#CityId";
list = response.Cities;
DisableDropDown("#CityId");
PopulateDropDown("#CityId", list);
dropDownId = "#CityId2";
list = response.Cities2;
PopulateDropDown("#CityId2", list);
$("#GPS").val(response.GPS);
break;
}
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function DisableDropDown(dropDownId) {
$(dropDownId).attr("disabled", "disabled");
$(dropDownId).empty().append('<option selected="selected" value="">[ === Select === ]</option>');
}
function PopulateDropDown(dropDownId, list) {
var modal = $('<div />');
modal.addClass("modalBackground");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
setTimeout(function () {
if (list != null && list.length > 0) {
$(dropDownId).removeAttr("disabled");
$.each(list, function () {
$(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
});
$(".loading").hide();
$('.modalBackground').remove();
}
}, 1000);
}
</script>
}
update controller
[HttpPost]
public ActionResult Index(PersonModel person)
{
MTsqlinsert(person); //Insert values in the database
if (ModelState.IsValid)
{
PersonModel personModel = new PersonModel();
person.Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
person.States = PopulateDropDown("SELECT StateId, StateName FROM States WHERE CountryId = " + countryId, "StateName", "StateId");
person.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + stateId, "CityName", "CityID");
ViewData["result"] = "1";
return RedirectToAction("Index");
}
return View(person);
}
[HttpGet]
[OutputCache(NoStore = true, Duration = 60, VaryByParam = "*")]
public ActionResult Index()
{
PersonModel personModel = new PersonModel
{
Countries = PopulateDropDown("SELECT CountryId, CountryName FROM Countries", "CountryName", "CountryId");
};
return View(personModel);
}

How to access viewbag value in AJAX success?

Here I EditMyProfile method which is used to edit the customer detail.
In this method I am trying to set ViewBag.msg = 1 and return return PartialView("MyProfile", getCusomerDetail);, set ViewBag.msg = 0; and return return PartialView("EditMyProfile", customer); and using that ViewBag.msg value want put condition on AJAX success whether to show success message or not.
Now, the problem is that even though the ViewBag.msg has value in EditMyProfile view, the var message = '#ViewBag.msg' gives var message = "" in AJAX success.Any help with my code will be a great help
Thank you
Below is my AJAX
<script>
$(document).ready(function () {
$("#EditMyProfileCreate").submit(function (ev) {
debugger;
ev.stopImmediatePropagation();
var Action = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: Action,
type: 'POST',
data: formData,
async: false,
success: function (data) {
debugger
var message = '#ViewBag.msg'; // Here the var message = "" even though #ViewBag.msg' has value
if (message == "1") {
swal("Congratulations!", "Chages saved successfully", "success");
$("section#myAccountMainDiv").html(data);
}
else {
$("section#myAccountMainDiv").html(data);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
})
Below is my
[HttpPost]
public ActionResult EditMyProfile(CustomerVM customer)
{
if (ModelState.IsValid)
{
using (emedicineEntities _db = new emedicineEntities())
{
var getCustomer = _db.Customers.Where(x => x.CustomerId == customer.CustomerId).FirstOrDefault();
getCustomer.CustomerName = customer.CustomerName;
getCustomer.CustomerPhoneNumber = customer.CustomerPhoneNumber;
getCustomer.CustomerEmail = customer.CustomerEmail;
getCustomer.CustomerAddress = customer.CustomerAddress;
getCustomer.ConfirmPassword = getCustomer.PasswordHash;
_db.Entry(getCustomer).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.msg = 1; // here ViewBag.msg is set 1 on successfull edit
var getId = Global.CustomerId;
var getCusomerDetail = _db.Customers.Where(x => x.CustomerId == getId).FirstOrDefault();
return PartialView("MyProfile", getCusomerDetail);
}
}
else
{
ViewBag.msg = 0; // here ViewBag.msg is set 0 when model is invalid
return PartialView("EditMyProfile", customer);
}
}
To Access ViewBag dictionary in javascript, your Javascript code block must be on the cshtml file and not in the external javascript file.
In Controlller
public ActionResult Index()
{
ViewBag.Data = "haha";
return View();
}
In cshtml file
<script>
$(document).ready(function () {
alert('#ViewBag.Data');
});
</script>
As you are calling your controller through an Ajax call, you need to return the data as a variable inside your partial view. What i would suggest is to create a hidden field inside your partial view's cshtml file and assign that the value of ViewBag property at compile time. Then inside success function get the value of hidden field and compare.

WCF Service's JSON string response to Ajax POST request is not accepted. Method always goes to error.

I have written a WCF service which in theory, should accept a JSON object from Ajax and return true or false as a response to indicate the JSON object was accepted from service and sent to the database.
This is how the interface is implemented in IService
[OperationContract]
[WebInvoke(Method ="POST",ResponseFormat=WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,UriTemplate ="InsertPatient")]
String InsertPatient(Patient PatientObj);
The contract is implemented as follows
public String InsertPatient(Patient PatientObj)
{
PatientContext pat = new PatientContext();
Boolean boolObj = new Boolean();
string JsonString = "";
if (pat.Patients.Where(x => x.Username == PatientObj.Username).Any())
{
// Username already taken;
boolObj = false;
JsonString =JsonConvert.ToString(boolObj);
return JsonString;
}
else
{ //Initiate to add user to login table
Login log = new Login();
log.Username = PatientObj.Username;
log.Password = PatientObj.Password;
log.User_Type = PatientObj.User_Type;
if (InsertLogin(log)) //if login added
{
pat.Patients.Add(PatientObj); //add user to patient table
pat.SaveChanges();
boolObj = true;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
else //login was not added
{
boolObj = false;
JsonString = JsonConvert.ToString(boolObj);
return JsonString;
}
}
}
and finally the Ajax script is implemented as follows
<script>
$(document).ready(function () {
$("form").submit(function () {
var L_Username = $("#UN").val();
var L_User_Type = "patient";
var L_Name = $("#name").val();
var L_Birthday = $("#bday").val();
var L_Gender = $("input[name='optradio']:checked").val();
var L_Contact = $("#cNo").val();
var L_Password = $("#password").val();
var L_Address = $("#adress").val();
var jsondata = {
Username: L_Username,
User_Type: L_User_Type,
Address: L_Address,
Birthday: L_Birthday,
Contact: L_Contact,
Gender: L_Gender,
Name: L_Name,
Password: L_Password
};
console.log(JSON.stringify(jsondata));
$.ajax({
url: "http://localhost:50709/Service1.svc/rest/InsertPatient",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(jsondata),
success: function (resultdata) {
alert("inserted");
},
error: function (e) {
alert("Something went wrong");
}
});
});
});
</script>
When I test this through POST-man , I get the correct response as true or false. But when I run this from the website itself. Ajax always throw the error alert, but the values get successfully added to the tables.
What am I doing wrong , please help. Thank you in advance.

JavaScript stop working after AJAX call

My javascript is getting locked after ajax call.
When the user press enter then i call my c# method to search the city that the user typed, and then show the temperature, but when the search ends, the javascript stops working. And i found out that the error is on these lines:
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
code:
$(document).ready(function () {
$('#search-bar').keyup(function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $('#search-bar').val();
$.ajax({
url: '#Url.Action("getWeatherSearch", "Index")',
data: { city: city },
async: false,
complete: function (resp) {
var div = document.getElementById('rb-grid');
div.innerHTML = resp.responseText + div.innerHTML;
Boxgrid.init();
}
});
} });
HTML:
<div align="center" class="div-search-bar">
#Html.TextBox("search-bar", "", new { #class = "search-bar", placeholder = "search" })
</div>
Try the following and see if it works for you:
$(function () {
var $searchbar = $('#search-bar'),
$grid = $('#rb-grid');
if ($grid.length) {
$searchbar.on('keyup', function (event) {
if (event.keyCode == 13) {
myFunction();
}
});
function myFunction() {
var city = $searchbar.val();
$.ajax({
url: $.grid.data('weather-url'),
data: { city: city }
})
.done(function (resp) {
$grid.html(resp.responseText + $grid.html());
Boxgrid.init();
}
});
}
}
});
Add the following as a data attribute somewhere in your html, probably on your grid:
<div id='rb-grid' data-weather-url='#Url.Action("getWeatherSearch", "Index")'></div>

AJAX - respond differently depending on server response

Here is my C# code:
if (!String.IsNullOrEmpty(bookRoom))
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1); //If we ever upgrade, its not that important but change this to the right version
//service.UseDefaultCredentials = true;
service.Credentials = new WebCredentials("MYNLJ", "", "");
service.Url = new Uri("http://DIR/EWS/Exchange.asmx"); //This is the EWS file
Appointment appointment = new Appointment(service);
String ITMtgMailboxToAccess = roomEmail; //Mailbox name
FolderId ITMtgCalendarFolderId = new FolderId(WellKnownFolderName.Calendar, ITMtgMailboxToAccess);
appointment.Subject = "Walk In Meeting";
appointment.Body = "Test Meeting";
double htoAdd = Convert.ToDouble(MeetingLength.SelectedItem.Value);
appointment.Start = DateTime.Now;
appointment.End = DateTime.Now.AddMinutes(htoAdd);
CalendarView Checkcv = new CalendarView(appointment.Start, appointment.End); //Don't change this
try
{
FindItemsResults<Appointment> ITMtgfapts = service.FindAppointments(ITMtgCalendarFolderId, Checkcv);
List<Appointment> ITMtgappointments = new List<Appointment>();
if (ITMtgfapts.Items.Count > 0) // If there is more than one item
{
Here I want to let the ajax request know that the booking wasn't successful
// "Your booking will conflict with another appointment";
}
else
{
Let the ajax request know it was successful
//Success
appointment.RequiredAttendees.Add(roomEmail);
appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
}
}
catch
{
}
}
AJAX code:
<script type="text/javascript">
$(function () {
$('#BookButton').click(function (event) {
var form = $('#Form1');
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: $("#BookRoom :input").serialize()
}).done(function () {
// Optionally alert the user of success here...
$('#BookRoom').modal('hide');
$('#SuccessMsg').text('Meeting Booked');
$('#SuccessMessage').modal('show');
setTimeout(function () { $('#SuccessMessage').modal('hide'); }, 3000);
}).fail(function () {
// Optionally alert the user of an error here...
alert("Error submitting AJAX request");
});
event.preventDefault(); // Prevent the form from submitting via the browser.
});
});
My advice is to respond an enum-value. The advantage is the scalability:
C#
public enum ReponseType : int
{
Success: 0,
InvalidInput: 1,
ServerError: 2,
....
}
Javascript
var ResponseType = {
Success: 0,
InvalidInput: 1,
ServerError: 2,
....
}
On the server:
return base.Json(ReponseType.Success);
// or return base.Json(ReponseType.InvalidInput);
// or return base.Json(ReponseType.ServerError);
On the client:
$.ajax({
...
}).done(function (data) {
if (data === ResponseType.Success) {
// Notify user: Success
}
else if (data === ResponseType.InvalidInput) {
// Notify user: It is his fault
}
else if (data === ResponseType.ServerError) {
// Notify user: It is your fault
}
});

Categories

Resources