How to execute method by clicking a button type

Asked

Viewed 783 times

-1

Ola, I am making an application that can re-cover the user password and send the password to the Suport team email. For that I have a page .aspx that has html code and I have it in the class recoverpassword a method I called sendemail() to send the mails. What I want is when clicking on this button to execute the sendemail method that is within the page class. The method sendemail() has the same code as many examples of the net.

HTML code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Cegos Analytics | Lockscreen</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.5 -->
  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
</head>
<body class="hold-transition lockscreen">
<!-- Automatic element centering -->
<div class="lockscreen-wrapper">
  <div class="lockscreen-logo">
   <img src="/Images/^082594892CD6A1E2D2CF4B7361463D84FEF2B4C6FEBD2707B5^pimgpsh_fullsize_distr.png" alt="Cegos Logo">
  </div>
    <br />
  <!-- User name -->
  <div class="lockscreen-name"></div>

  <!-- START LOCK SCREEN ITEM -->
  <div class="lockscreen-item">
    <!-- lockscreen image -->
    <div class="lockscreen-image">
      <img src="/Images/locked.jpg" alt="Locked Screen">
    </div>
    <!-- /.lockscreen-image -->

    <!-- START LOCK SCREEN ITEM -->
  <div class="lockscreen-item">
    <!-- lockscreen image -->
    <div class="lockscreen-image">
      <img src="/Images/locked.jpg" alt="Locked Screen">
    </div>
    <!-- /.lockscreen-image -->
</div>

    <!-- lockscreen credentials (contains the form) -->
    <form class="lockscreen-credentials" action="RecoverPassword.aspx" method="post">
      <div class="input-group">
         <input id='user' type="Text" class="form-control" placeholder="Username">    
    <div class="input-group-btn">
              <button id='enviar' type="submit" class="btn"><i class="fa fa-arrow-right text-muted"></i></button>
         </div>

     </div>
      </div>
    </form>
    <!-- /.lockscreen credentials -->

  </div>
  <!-- /.lockscreen-item -->
  <div class="help-block text-center">
    Enter your username to retrieve your session
  </div>
  <div class="text-center">
    <a href="../Default.aspx">Or sign in as a different user</a>
  </div>
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
  <%--  <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />--%>
    <br />
  <div class="lockscreen-footer text-center">
        <p style="height: 42px" align="center">&copy; <%: DateTime.Now.ToShortDateString() %> - <strong>Cegos Elearning Reports</strong>
  </div>
</div>
<!-- /.center -->

<!-- jQuery 2.2.0 -->
<script src="../../plugins/jQuery/jQuery-2.2.0.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="../../bootstrap/js/bootstrap.min.js"></script>    

<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>

<script type="text/javascript">

    $("#enviar").click(function () {
               @SendEmail();//Insira aqui o código para chamar o sender email.
    });
</script>



            </form>

            </body>

</html>

page Send email.aspx.Cs :

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net.Mail;
using System.Net;
using System.IO;


namespace Email
{
    public partial class Enviaremail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }


        private void SendEmail()
        {

            SmtpClient cliente = new SmtpClient();
            cliente.Host = "smtp.sapo.pt";
            cliente.EnableSsl = true;
            cliente.Credentials = new NetworkCredential("[email protected]", "cegoc123456");

            MailMessage mensagem = new MailMessage();
            mensagem.Sender = new MailAddress("[email protected]");
            mensagem.From = new MailAddress("[email protected]");
            mensagem.To.Add(new MailAddress("[email protected]"));
            mensagem.Subject = "Pedido de suporte Plataforma Cegos Analytics";
            mensagem.Body = "Recebeu um pedido de suporte da  Plataforma Cegos Analytics para recuperação de passwor referente ao utilizador:";
            mensagem.IsBodyHtml = false;
            mensagem.Priority = MailPriority.High;

            cliente.Send(mensagem);

        }
    }
}

And in the EnviarEmail with the help of @Duque and @Leonardo Coelho I have this:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <%--<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />--%>
        <input type="text" name="email" class="campo" /> <button type="button" class="botao">Recuperar senha</button>

    </div>
    </form>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>

<script type="text/javascript">

    var sendEmail = function () {

        $.ajax({

            type: 'POST',

            url: 'http://localhost:5562/Enviaremail.aspx',  //Aqui é a URL até o método onde está a instrução de enviar o e-mail

            dataType: 'html',

            success: function (data) {
                //Trate o retorno sem erros
            }, error: function (request, status, error) {
                //Trate os erros
            }

        });

    }

    $("#enviar").click(function () {
        //Faz a chamada da função ajax
        sendEmail();
    });
    </script>


</body>
</html>

What’s missing to still not succeed? I click the button and does nothing or submit or anything. Please help me

Can you help me see what I’m doing wrong? Thank you.

  • It is not duplicated. I edited the question to help me. I put more information. It is not duplication

  • Nelson, despite having different code, the questions seem to address the exact same problem: send email at the click of the button. I read and reread and saw no practical distinction. That’s why I also voted to close as duplicate. If you don’t agree, edit this again to try to make it even clearer. So maybe it will be reopened.

2 answers

0

Using the framework jQuery you can use the property $.ajax in this way.

$('.botao').on('click', function() {
	var campo = $('.campo');
	$.ajax({
		url: 'url_do_seu_metodo_php',
		method: 'post',
		data: campo.serialize(),
		success: function(resultado) { // Resultado da Consulta
			console.log(resultado); // Verifique o console
		}
	});
});
<input type="text" name="email" class="campo" /> <button type="button" class="botao">Recuperar senha</button>
You are using Asp, this example is in PHP, the difference is just how you will capture the post that was sent to the document.

<?php
var_dump($_POST);
?>
  • No duplicate solution ?

0

The best way is to make an Ajax call, for that:

var sendEmail  =   function () {

    $.ajax({    

        type: 'POST',

        url: 'http://www.seusite.com.br/metodo',  //Aqui é a URL até o método onde está a instrução de enviar o e-mail

        dataType: 'html',

        success: function (data) {
           //Trate o retorno sem erros
        },error: function(request, status, error){
            //Trate os erros
        }

    });

}

$("#enviar").click(function () {
    //Faz a chamada da função ajax
    sendEmail();
});

More details about AJAX calls with Jquery: Ajax Jquery function

  • Thank you Duque. But where do I put this code? the url is for example localhost. /Report/Recoverpassword.aspx? Thank you

  • This code will be in the same place where your page’s JS code is. If the URL you access to send the email is: localhost. //Report/Recoverpassword.aspx, so this is the value to be set in the URL parameter.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.