ajax call to send access token fail - c#

Hello I'm trying to allow login in my app through facebook, and than I want to get some info with the access token I'm getting.
I'm trying to pass the access token from facebook js sdk to a webmethod on the server for me to use it later, but the call is failing.
here's my aspx:
<html>
<head>
<title>Facebook Login Authentication Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// 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));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: '474928559284763', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
var dataString = JSON.stringify({ access_T: response.authResponse.accessToken });
alert(dataString);
$.ajax({
type: "POST",
async: false,
url: "Default2.aspx/save_access_token",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (result) {
alert(result.d);
}
});
FB.api('/me', function (me) {
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
//here
//
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
});
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="display: none">
Hi, <span id="auth-displayname"></span>(logout)
</div>
</div>
</body>
</html>
here's my webmethod:
[WebMethod(EnableSession = true)]
public static void save_access_token(string access_T)
{
HttpContext.Current.Session["a_t"] = access_T;
}
EDIT:
I checked to see what is written on the post and here it is:

Problem solved. something with the web form was not right, when I started a new one it worked.

Related

Send Email with different Forms to different Email Addresses

I have 2 Forms , One for Print and One for Cloud and in each Form i have an input field ,where user should write their email address in input feild and when User Submit button for example In Print Form, it should send an email with users email address (Just inform in input feild) to Print Email address and when user submit button in Cloud Form it should send an email to Cloud Email address.
For example;. if Form = Print send value of Input field in Print Form to Print Email Addresse
if Form = Cloud send value of Input field in Cloud Form to Cloud Email Address
I can get it just work for One Form for example Print , but i dont know how get this things work for the others Forms like Cloud. Can anyone please point me in right direction! thanks :)
PrintForm HTML Markup:
<form id="PrintForm">
<input type="text" id="txtEmail" />
<input type="submit" value="Send" />
</form> <br>
CloudForm HTML Markup:
<form id="CloudForm">
<input type="text" id="txtEmail" />
<input type="submit" value="Send" />
</form>
AJAX:
<script>
$(document).ready(function () {
$("#PrintForm").submit(function (e) {
e.preventDefault();
var email = $("#txtEmail").val();
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
});
</script><br>
Controller:
[HttpPost]
public JsonResult AjaxMethod(string email)
{
var SubjectOne = "Print";
var SendToPrint = "Print#Print.com";
var errorMessage = "";
//BookingViewModel
Booking book = new Booking {
Email = email,
};
try
{
// Initialize WebMail helper
WebMail.SmtpServer = "smtp";
WebMail.SmtpPort = 25;
WebMail.UserName = "email#email.com";
WebMail.Password = "";
WebMail.From = "email#email.com";
WebMail.EnableSsl = true;
WebMail.SmtpUseDefaultCredentials = false;
// Send email
WebMail.Send(to: SendToPrint,
subject: SubjectOne,
body: "email: " + email + "<br>"
);
}
catch (Exception ex)
{
errorMessage = ex.Message;
}
return Json(book);
}
Register a submit event on the cloud form just like you do for the print form.
$("#CloudForm").submit(function (e) {
e.preventDefault();
var email = $("#txtEmail").val();
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
If both the CloudForm and PrintForm are on the same page, you will have to change the id of the textbox inputs so that they both have an unique ID.
Add a class to the two forms:
<form id="PrintForm" id = printFormGroup">
<form id="CloudForm" id = printFormGroup">
and then amend your AJAX to respond to the class:
$(".printFormGroup").submit(function (e) {
This will cover all forms with the same class and will return whatever the user enters.
You need to update your Controller by adding the parameter named formType,
[HttpPost]
public JsonResult AjaxMethod(string email, string formType)
{
if(formType == "print")
{
//Perform print related stuff
}
else if(formType == "cloud")
{
//Perform cloud related stuff
}
}
And updating your AJAX call with data: { email, formType: "print"} for Print form,
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
formType: "print"
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
data: { email, formType: "cloud"} for Cloud form,
$.ajax({
type: 'POST',
url: "/xxx/AjaxMethod",
dataType: 'json',
data: {
email: email,
formType: "cloud"
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});

Ajax call is not working - Collect Information from merchant transaction page

I am new to Ajax. I want to retrieve the transaction details from the merchant website after payment processing. My ajax call script is not working. Please help.
C# Method
public class RetrieveCache
{
[WebMethod]
public string RetrieveTransactionData(string ID)
{
ChannelFactory<ServiceSoap> PayChannelFactory = new ChannelFactory<ServiceSoap>("ServiceSoap12");
ServiceSoap Paychannel = PayChannelFactory.CreateChannel();
XmlNode node = Paychannel.RetrieveCachedData(ID);
return node.InnerXml;
}
}
Ajax call Script in HTML Page to call the above c# method
Html Page URL: http://localhost:55014/SuccessPage.html?id=29473740923
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var url = window.location.search;
debugger;
var token = (url.replace("?", "").split("=")[1]).toString();
debugger;
var dataval = JSON.stringify({ token: token });
$.ajax({
url: "http://localhost:55014/RetrieveCache.cs/RetrieveTransactionData",
type: 'post',
data: JSON.stringify({ token: token }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data){
alert(data);
},
error: function (err) {
alert(err)
}
});
});
</script>

How to call webservice in HTML page using JQuery?

i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.
Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});

asp.net integrate facebook login

Hi i am using facebook login authenticate in my local application.But at last when i click on facebook image it shows this error:
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
I know its domain name error that i have set in facebook aap url and site url.
i have set same url in IIS and facebook app .still i got error.
HERE IS MY CODE:
<html>
<head>
<title>Facebook Login Authentication Example</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
// 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));
// Init the SDK upon load
window.fbAsyncInit = function () {
FB.init({
appId: '553530488015828', // App ID
channelUrl: '//' + window.location.hostname + '/channel', // Path to your Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// listen for and handle auth.statusChange events
FB.Event.subscribe('auth.statusChange', function (response) {
if (response.authResponse) {
// user has auth'd your app and is logged into Facebook
FB.api('/me', function (me) {
if (me.name) {
document.getElementById('auth-displayname').innerHTML = me.name;
}
})
document.getElementById('auth-loggedout').style.display = 'none';
document.getElementById('auth-loggedin').style.display = 'block';
} else {
// user has not auth'd your app, or is not logged into Facebook
document.getElementById('auth-loggedout').style.display = 'block';
document.getElementById('auth-loggedin').style.display = 'none';
}
});
$("#auth-logoutlink").click(function () { FB.logout(function () { window.location.reload(); }); });
}
</script>
<h1>
Facebook Login Authentication Example</h1>
<div id="auth-status">
<div id="auth-loggedout">
<div class="fb-login-button" autologoutlink="true" scope="email,user_checkins">Login with Facebook</div>
</div>
<div id="auth-loggedin" style="display: none">
Hi, <span id="auth-displayname"></span>(logout)
</div>
</div>
</body>
You need to add unique facebook app id to use facebook login authenticate in your localhost. And you need to specify url in https://developers.facebook.com/

Update Panel in ASP.NET MVC 3

I'm looking for a way to do a "Update Panel" in ASP.NET MVC 3. I found this link: How to make update panel in ASP.NET MVC but didn't work.
So, i did this in my view:
<div>
<input type="text" id="userName" />
<button type="button" onclick="searchUserByName()">Search</button>
</div>
<div id="usersPanel">
#{Html.RenderPartial("_UserList", Model);}
</div>
<script type="text/javascript">
function searchUserByName() {
var userName = $("#userName").val();
$.post('#Url.Action("SearchUserByName")',
{username: userName},
function (htmlPartialView) {
$("#usersPanel").html(htmlPartialView);
}
);
}
</script>
And in my controller:
public ActionResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_UserList", users);
}
But i don't know if is a good (or right) way to do that, or if there is a way to do this with asp.net mvc 3. There is a better way to do this, or with asp.net mvc 3?
Just use ajax request to get the results from your action methods. It basically does the same thing as update panels in asp.net.
So something like the following.
$.ajax({
async: false,
cache: false,
type: 'POST',
url: /controller/action,
data: { id: idParam },
beforeSend: function (XMLHttpRequest) {
if (confirmMessage !== undefined) {
return confirm(confirmMessage);
}
return true;
},
success: function (data) {
// do stuff
},
error: function () {
alert('An error occured');
}
});
I would do it like that.
You might also want to take a look at client side libraries for handling bindings etc. Looks like knockoutjs will be included in MVC4
In View:
<script type="text/javascript">
var userName = $("#userName").val();
$.ajax({
url: "/<ControolerName>/SearchUserByName",
type: "POST",
data: { userName: userName},
success: function (result) {
$('#divResults').html(result);
},
error: function (ex) {
alert("Error");
}
<script>
<div id="divResults">
</div>
In controller:
public PartialViewResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_users", users);
}

Categories