Html/Javascript Page canvas sending to ASP.NET email method - javascript

Scenario:
I have an application being built in Visual Studio using ASP.NET. The application is being hosted on an IIS server. In the application there is an asp.net page with mostly html elements that references a javascript file that allows the user to draw a signature in a canvas and then submit it with an email.
The Goal with this is to have a webpage that allows the user to give their email and signature, click accept, and send that data to the C# method that will attach the signature and email it to the address.
I have tried multiple ways and done some good ajax research but have had no luck. I can't see any errors in the Visual Studio debugger. When i click the send button the text changes to Sending... but never goes further. I have yet to complete and write out the email portion of the method. At this point i just want to be able to pass in the JSON object with the email and canvas image. and somehow display the email (just to verify it was sent through).
What might i be doing wrong here? I'm thinking my issue lies in the ajax statement in the application.js, but have tried multiple ways of sending with no luck.
EDIT::: I am receiving the error code from the POST statement like
Internal Server Error
jquery-1.7.min.js:4 POST http://localhost:port#/SigCapture.aspx/SendMail 500 (Internal Server Error)
send # jquery-1.7.min.js:4
ajax # jquery-1.7.min.js:4
onSubmitClick # application.js:28
dispatch # jquery-1.7.min.js:3
i # jquery-1.7.min.js:3\
Update: I have received a new error after making the WebMethod a public static method so it can be seen by the ajax statement.
{Message: "Invalid JSON primitive: method.",…}
ExceptionType
:
"System.ArgumentException"
Message
:
"Invalid JSON primitive: method."
Here is the code:
NAME: SigCapture.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="SigCapture.aspx.cs" Inherits="mytest.SigCapture" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name=viewport content="width=device-width, initial-scale=1.0,
minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="assets/styles.css" />
<title>Signature Capture</title>
<script src="js/jquery-1.7.min.js" type="text/javascript"></script>
<script src="js/modernizr.custom.34982.js" type="text/javascript"></script>
<script src="js/application.js" type="text/javascript"></script>
<script src="js/signatureCapture.js" type="text/javascript"></script>
</head>
<body>
<form id="mainform" runat="server">
<img src="assets/phonegap.png" alt=""/>
<asp:Button ID="btn1" runat="server" Text="Clickme" OnClick="btn1_Click" />
<h2 runat="server">SAMPLE FORM</h2>
<asp:Label id="labeltext" runat="server" Text="Enter your email and `Sign the form"/>`
</form>
<h2>EMAIL</h2>
<input id="email" type="email" />
<p id="text"></p>
<h2>SIGNATURE</h2>
<div id="canvasContainer" width="100%">
<canvas id="signature" height="200px" />
</div>
<div id="lowerControls">
<div id="feedback"></div>
<div id="buttonsContainer">
<input type="image" id="submit" src="assets/accept.png" />
<input type="image" id="cancel" src="assets/cancel.png" />
</div>
</div>
</body>
</html>
NAME: SigCapture.apsx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace mytest
{
public partial class SigCapture : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn1_Click(object sender, EventArgs e)
{
labeltext.Text = "DER_";
}
public void test(object sender, EventArgs e, string name)
{
labeltext.Text = "DER_";
}
[WebMethod]
public string SendMail(object data)
{
return data.ToString();
}
}
}
NAME: application.js
// JavaScript Document
var sigCapture = null;
$(document).ready(function(e) {
sigCapture = new SignatureCapture( "signature" );
$("#submit").click( onSubmitClick );
$("#cancel").click( onCancelClick );
});
function onSubmitClick( event ) {
if ( verifyEmail() )
{
$("#text").html("CLICKED");
$("#feedback").html( "Sending..." );
var email = $("#email").val();
var sig = sigCapture.toString();
var data = { "method":"submitSignature",
"email":email,
"signature":sig,
"returnformat":"json" };
var url = 'SigCapture.aspx/SendMail';
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: requestSuccess,
error: requestError
});
}
else {
$("#feedback").html( "Please enter a valid email address." );
}
}
function onCancelClick( event ) {
clearForm();
}
function clearForm() {
$("#email").val( "" );
sigCapture.clear();
$("#feedback").html( "" );
}
function requestSuccess( data, textStatus, jqXHR ) {
clearForm();
$("#feedback").html( "Thank you." );
}
function requestError( jqXHR, textStatus, errorThrown ) {
$("#feedback").html( "Error: " + errorThrown );
}
function verifyEmail() {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test( $("#email").val() );
}

Related

Failed to load resource : Internal Server Error (500) : jQuery

We are using jQuery 3.3.1 in our project. When we are using and testing on localhost the jQuery works fine and its loading without any issue.
However, now we have deployed our web application on AWS and after deploying it is giving the below error
Failed to load resource : the server responded with a status of 500 (Internal Server Error)
We are loading third party payment providers iFrame in our html page. Is that causing an issue ? If it is an issue then why does it works fine in localhost ?
Also, we have kept the file in our solution itself and tried with jQuery CDN as well. But it gives the same error.
#using Microsoft.AspNetCore.Mvc.Rendering;
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>PaymentProviders</title>
<script src="~/jquery.min.js"></script>
</head>
<body>
<div class="form-control">
<label>Payment Provider Name:- </label>
#Html.DropDownList("ID", new SelectList(ViewBag.PaymentProvidersList, "ID", "PaymentProviderName"), "Please select", new { #id = "ddlPaymentProviders", #onChange = "SelectedValue(this)" })
</div>
<div id="divContainer"></div>
</body>
</html>
<script>
function SelectedValue(ddlObject) {
var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;
$.ajax({
type: "GET",
url: "/Home/Index",
data: { 'paymentProviderName': selectedText },
success: function (data) {
$('#divContainer').html(data);
$('#divContainer iframe').height("500");
}
});
}
</script>
Below is the screenshot for the same.
Any help on this appreciated !

Why is not the control moving to the script method "checkExistence()"?

I am doing a file upload program in which i am using ajax call to check whether any file exists with the same name.
Here is the code
jsp page
<%# taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload Example</title>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function checkExistence() {
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
document.write(filename);
$.ajax({
type: "POST",
url: "/FileController/fileexists",
data: "filename=" + filename,
success: function(response){
if(response==0)
{
ch="zero";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else if(response==1)
{
alertchoice=alert("File already exists !! Do you want me to overwrite it ?");
if(alertchoice==true || alertchoice.equals(true))
{
ch="one";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else {
ch="two";
alert("Upload suspended as requested by the user ");
} }
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<br>
<br>
<center><form name="fileform" action="savefile" method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file" id="file"><br><br><br>
<input type="hidden" name="choice">
<input type = "button" value ="upload" onClick="checkExistence()">
<input type="reset" value="Reset">
</form></center>
<br>
<br>
<br>
<center><b> ${message} </b></center>
</body>
</html>
//controller class
#RequestMapping(value="/fileexists",method = RequestMethod.POST)
#ResponseBody public String checkingForDuplicates(HttpServletRequest req, HttpServletResponse res){
String filename=req.getParameter("filename");
int i=isDuplicate(filename);
return i+"";
}
Here when i am clicking the button upload , control should go to the function checkExistence() . But it is not moving. Is something wrong with my code ? And i am using
File f=new File(name);
var filename=f.getOriginalFileName();
in javascript function to get the name of the file being uploaded. Does it work ?
I got the answer by making the following corrections.
Including jquery plugin
changing ajax call url from
url: "/FileController/fileexists"
to
url: "fileexists"
In jsp page to get name of the file being uploaded
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
modified :
var filename=document.getElementById('file').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
originalfilename = filename.substring(lastIndex +1);
}
In controller to get the file name(for checking duplicates)
previous : String filename=req.getParameter("filename");
modified : String filename=req.getParameter("originalfilename");

how to return the ajax response as an array of javascript

I'm learning how to use jquery autocomplete, I make an example about the $.get method in ajax.
I take a look at http://jqueryui.com/autocomplete/ to make this example.
In my jsp page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls using Jquery in Servlet</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function(){
$('#user').autocomplete({
source: function (request, response) {
var username = $('#user').val();
$.get('autocompleteServlet', {user : username}, function(responseText){
$('#welcometext').text(responseText);
var value = [responseText];
response(value);
});
}
});
});
</script>
</head>
<body>
<form id="form1">
<h1>AJAX Demo using Jquery in JSP and Servlet</h1>
Enter your Name: <input type="text" id="user" /> <input type="button"
id="submit" value="Ajax Submit" /> <br />
<div id="welcometext"></div>
</form>
</body>
</html>
In servlet :
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("user");
System.out.println("user : "+ value);
try {
Connection cnn = XJdbc.getConnection();
String sql = "SELECT Name FROM reported_tasks WHERE Name LIKE '%"+ value + "%'";
Statement stm = cnn.createStatement();
ResultSet rs = stm.executeQuery(sql);
String result = "";
while (rs.next()) {
result = result + rs.getString("Name") + ",";
}
cnn.close();
System.out.println("Request :" + result);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
}
I think that the problem is how to return ajax response as an array type of javascript.
Please help me how to fix that, thanks all
Your servlet's response currently will produce something like:
name1,name2,name3,...
The response function is looking for an array of strings in your case, though it can take an array of objects in other formats.
I would recommend having your servlet output something like this:
{ "names" : ["name1","name2","name3"...,"nameX"] }
Your Javascript to process the above response would be
$.get('autocompleteServlet', {user : username}, function(responseText){
// I assume the next line is for debugging?
$('#welcometext').text(responseText);
var obj = $.parseJSON(responseText);
response(obj.names);
});

Facebook API - posting to a timeline

I know this can't be that difficult; maybe I'm going about this the wrong way. Hopefully you can help me.
I have a website that needs to be able to post a string to someone's Facebook timeline.
I've gotten them to login properly, but I haven't found any working code to submit information to their timeline after they've given permission.
I've followed the example here with no luck. I've
Created an App
Logged into Facebook
Defined a Cook action with a recipe object
Created a page on my website with the code that they provided, replacing [your_app_id] with my app id
Attempted to post a cook action
But when I click the cook button on their sample page on my site, it gives me the error:
No callback passed to the ApiClient for https://graph.facebook.com/me/fblaevents:cook
and the error occurred browser alert pops up.
Here is the sample code that I'm using:
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"
xmlns:fb="https://www.facebook.com/2008/fbml">
<head prefix="og: http://ogp.me/ns# fblaevents:
http://ogp.me/ns/apps/fblaevents#">
<title>OG Tutorial App</title>
<meta property="fb:app_id" content="542182755801091" />
<meta property="og:type" content="fblaevents:recipe" />
<meta property="og:title" content="Stuffed Cookies" />
<meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
<meta property="og:description" content="The Turducken of Cookies" />
<meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
<script type="text/javascript">
function postCook()
{
FB.api(
'/me/fblaevents:cook',
'post',
{ recipe: 'http://fbwerks.com:8000/zhen/cookie.html' },
function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Cook was successful! Action ID: ' + response.id);
}
});
}
</script>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '542182755801091', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<h3>Stuffed Cookies</h3>
<p>
<img title="Stuffed Cookies"
src="http://fbwerks.com:8000/zhen/cookie.jpg"
width="550"/>
</p>
<br>
<form>
<input type="button" value="Cook" onclick="postCook()" />
</form>
</body>
</html>
If there is an easier way, please point it out to me. I don't know what I'm doing.
You should replace the OG meta tags and the recipe url in your JS code with your own. As the above code is a starting code only, not a working demo (or maybe it was but now the links are dead).
Also since you are getting Error occured then most probably response.error has something in it, so you should check its value by calling the console method for example:
if (!response || response.error) {
console.log('Error occured: ', response.error);
} else {
This would give you:
Error occured: Object {type: "Exception", message: "Could not
retrieve data from URL.", code: 1660002}

Facebook open graph - did not specify reference object?

THis is a very newbie question about facebook open graph. I did the tutorial and have no problem create new namespace with new verbs and new nouns. However, I can't get a simple LIKE an OBJECT to work...
Anyway, here's the result of everything i'm doing.
I am getting the following error when I try to execute a custom built-in like with facebook's open graph:
Object
error: Object
code: 1611072
message: "The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: object."
type: "Exception"
__proto__: Object
__proto__: Object
Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"
xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>OG Tutorial App</title>
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# object: http://ogp.me/ns/object#">
<meta property="fb:app_id" content="99999999999" />
<meta property="og:type" content="object" />
<meta property="og:url" content="http://jl.com/" />
<meta property="og:title" content="Sample Object" />
<meta property="og:image" content="https://s-static.ak.fbcdn.net/images/devsite/attachment_blank.png" />
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
function postbake()
{
FB.api(
'/me/og.likes',
'post',
{ recipe: 'http://jl.com/' },
function(response) {
if (!response || response.error) {
alert('Error occured');
console.log(response);
} else {
alert('bake was successful! Action ID: ' + response.id);
}
});
}
</script>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '999999999999', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<fb:login-button show-faces="true" width="200" max-rows="1" scope="publish_actions">
</fb:login-button>
<input type="button" onclick="postbake()" value="like it" />
</body>
</html>
message: "The action you're trying to publish is invalid because it does not specify any reference objects. At least one of the following properties must be specified: object."
You are trying to post your object to like as recipe – but the parameter name has to be object instead …

Categories