I am currently utilizing Ajax to trigger the forgot password button, which then sends an email to a specific email address through CodeIgniter

When using ajax to click the forget button and send an email to a particular email address, I am getting an error "Fail". Can anyone help me figure out what the problem might be? Below you can see the form and controller code:

Form

<div class="field-wrap">
    <label class="view-label">Email Address</label>
    <input type="email" placeholder="Email Address" name="email" id="email" class="input-control inputstyle" value="<?php echo set_value('email'); ?>"/>
    <span class="text-danger"><?php echo form_error('email'); ?></span>
</div>
<div class="field-wrap">
    <input type="password" placeholder="Password" class="inputstyle" name="password" id="password" value="<?php echo set_value('password'); ?>"/>
    <span class="text-danger"><?php echo form_error('password'); ?></span>

    <a href="javascript:void(0)" class="btn btn-link btn-nobg" id="btn-show-forgot" >Forgot ?</a>  

</div>

Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<script type="text/javascript">
    $(document).ready(function () {
        $("#btn-show-forgot").click(function () {
            //e.preventDefault();
            var email = $("#email").val();

            $.ajax({
                type: "POST",
                url: "<?php echo base_url() ?>" + "index.php/Login_cntrl/sendmail",
                data: {email: email},
                success: function (data)
                {
                    alert('Successfully sent mail');
                },
                error: function ()
                {
                    alert('fail');
                }
            });
        });
    });
</script>

Controller

public function sendmail() {

        $this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
        
        if ($this->form_validation->run() == FALSE) {
            $this->load->view('login');
        } else {

            $data['email'] = $this->input->post('email');

            $findemaill = $this->Login_model->getUserInfoByEmail($data['email']);

            if (!empty($findemaill)) {

                $emailTo = $this->input->post('email');
                $this->session->set_userdata('findemaill',  $emailTo);

                $data['result'] = $this->Login_model->forgot_pass_retrive($emailTo);
                $id = $data['result']->id;
                $this->session->set_userdata('idd', $id);

                $six_digit_random_number = mt_rand(100000, 999999);
                $this->session->set_userdata('otp', $six_digit_random_number);

                $this->load->model('Login_model');

                $config = array(
                    'protocol' => 'smtp',
                    'smtp_host' => 'ssl://smtp.gmail.com',
                    'smtp_port' => '465',
                    'smtp_timeout' => '7',
                    'smtp_user' => 'example@gmail.com',
                    'smtp_pass' => 'yourpassword',
                    'charset' => 'utf-8',
                    'newline' => "\r\n",
                    'mailtype' => 'html',
                    'validation' => TRUE,
                );
                
                $this->email->initialize($config);
                $this->email->from('example@gmail.com', 'Terasukhintrade');
                $this->email->to($emailTo);

                $this->email->subject('Reset your password');

                $body=$this->load->view('forgotmailer',$data,TRUE);

                $this->email->message('Use the following OTP to reset password '.$body);
                $this->email->send();

                echo $this->email->print_debugger();

                $this->load->view('login',$data);
            } else {

                $this->session->set_flashdata('message', ' Email address not found!');
                $this->load->view('login',$data);
            }

        }
    }

Answer №1

When using ajax, it is important to always return a value. You cannot simply use

$this->load->view('login');

Furthermore, the ajax function needs to be modified as shown below.

        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>" + "index.php/Login_cntrl/sendmail",
            data: {'email': email},
            dataType: 'json',
            success: function(data) {
                alert('Mail sent successfully');
            },
            error: function() {
                alert('Failed to send mail');
            }
        });

Answer №2

function sendEmail() {

    $this->form_validation->set_rules('email', 'Email or number', 'required|min_length[10]|max_length[30]');
    if ($this->form_validation->run() == FALSE) {
        $this->load->view('login');
    } else {

        $data['email'] = $this->input->post('email');

        $findEmail = $this->Login_model->getUserInfoByEmail($data['email']);



        if (!empty($findEmail)) {
           // $this->Login_model->getUserInfo('$id');
           // $this->session->set_userdata('forgot_password_flag', 'yes');
            $emailTo = $this->input->post('email');
               $this->session->set_userdata('findEmail',  $emailTo);
              //  $this->session->userdata('findEmail');

            $data['result'] = $this->Login_model->forgot_pass_retrive($emailTo);
            $id = $data['result']->id;
            $this->session->set_userdata('idd', $id);



            $sixDigitRandomNumber = mt_rand(100000, 999999);

            $this->session->set_userdata('otp', $sixDigitRandomNumber);

            $this->load->model('Login_model');

            $pass['pass'] = $this->Login_model->forgot_pass_retrive($emailTo);

            $config['protocol'] = 'smtp';

            $config['smtp_host'] = 'ssl://smtp.gmail.com';

            $config['smtp_port'] = '465';

            $config['smtp_timeout'] = '7';

            $config['smtp_user'] = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8dcdfc7dac3dacdd8c7dadce8cfc5c9c1c486cbc7c5">[email protected]</a>';

            $config['smtp_pass'] = '8722248936';

            $config['charset'] = 'utf-8';

            $config['newline'] = "\r\n";

            $config['mailtype'] = 'html'; // or html

            $config['validation'] = TRUE; // bool whether to validate email or not      

            $this->email->initialize($config);
            $this->email->from('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5420233b263f2631243b2620143339353d387a373b39">[email protected]</a>', 'Terasukhintrade');
            $this->email->to($emailTo);


            $this->email->subject('Reset your password');

            $body=$this->load->view('forgotmailer',$data,TRUE);

            $this->email->message('Use the following OTP to reset password '.$body );

            $this->email->send();

            echo $this->email->print_debugger();

            $data['is_data'] = '1';
            $data['msg'] = 'Mail sent successfully';
            echo json_encode($data);
        } else {

            $data['is_data'] = '0';
            $data['msg'] = 'Email address not found!';
            echo json_encode($data);

        }

    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing the php base_url, I am unable to initiate a redirect to a different page using ajax

My aim is to utilize ajax in order to redirect to another page when a certain condition is met. However, I am facing difficulties when trying to achieve this using the php base_url. Strangely enough, if I use the direct path (http://localhost/CRH/......), ...

Struggling with Creating Custom Validation Methods in JQuery

I'm currently implementing the JQuery validation plugin and have created a new method to check the availability of a name in the database. The PHP script is functioning properly, returning either 1 or 0 depending on availability. However, the method c ...

The HTML Email Template fails to incorporate certain CSS styles

When attempting to create an HTML Email template that includes a button with a link and has a maximum width with consistent margins on both sides, I encountered some issues. While certain parts of the CSS were applied correctly, others were not displaying ...

Excessive width of the lower border

I have a dropdown menu on my website and I wanted to add a border-bottom to the menu. However, the border appears too wide. I went through every step of this solution as it seemed like the same problem, but nothing seems to be working. It would be great i ...

Try repeating the Ajax request until it is successful

Is there a way to continuously repeat an Ajax request until it returns 1, and stop if it returns 0? while(1){ $.ajax({ type: "POST", url: '/admin/importdata/', data: $info, dataType: "json", success: function($result) { ...

When an AJAX request is made, it can either return an array or a single object, potentially leading to

My proficiency in Javascript is definitely lacking, and I've only just begun to understand it. I have set up an AJAX call to an API using the GET method. The JSON data returned by the API is pretty standard. If I don't include an ID, I receive ...

Utilizing MVC6 to send both a CSV file and a string to a controller via Ajax

I'm encountering an issue that involves sending a CSV file along with the value of a string variable back to the controller. Individually, I've been successful in sending the file via the form's submit button and the string variable via aja ...

Replace the image with text inside an anchor when the anchor is being hovered

I want a logo (we'll call it .item-logo) to be shown inside a circle when not being hovered over, but when you hover over the container, the date should be displayed. Here is the HTML code: <div id="main-content" class="container animated"> ...

How can I adjust the appearance of an HTML tag within an Angular component?

I have created an Angular component with the following definition: import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'rdc-dynamic-icon-button', templateUrl: './dynamic-icon-button. ...

Rendering the page using ReactDOM.render

Just started with ReactJS, I'm struggling to figure out why my page isn't displaying anything - <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ...

When new text is added to Div, the first line is not displayed

One of the divs on my page has an ID of "TrancriptBox" and contains multiple lines of text. When I scroll through it on my iPad, everything works fine. However, if I scroll and then change the text within that div, it doesn't display the first line o ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

What is the typical output value that fluctuates?

I only have one input to work with. My goal is to set the input value to "5", then display "3" in the "total" field and "4" in the "total2" field. Additionally, for every increment of +1 to the input value, I want the "total" and "total2" fields to also in ...

Guide on adding a request header to the ajax object in jqGrid

I am trying to add the 'Authorization' request header to the httpXMLRequest. In the grid definition, I attempted to set it through ajaxGridOptions as shown below: ajaxGridOptions: { Authorization: 'Basic YWRtaW5AZGVmYXVsdC5jb206YWRTwa6=&ap ...

Rephrase the ajax call and the data retrieved

I'm struggling to find a solution for writing this code snippet without using async: false,. var imageX; var groupX; $.ajax({ type:'GET', url:'php/myphp.php', dataType:'json', async: false, success: ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

Using a for loop, how can the property value be set in another object?

One challenge that I am facing is setting object property values. The object in question looks like this: const newPlan = { name: '', description: '', number: '', monday: { breakfast: '', ...

The placeholder string is being accepted as the input value for the number

My issue is with a form input of type number. When the form is submitted without entering any number, it treats the placeholder text "rating" as the value. How can I stop this from happening? I need to make sure that the input number field is marked as in ...

Retrieving the selected option from a dropdown list in a cloned format

When the user selects a tax type from the dropdown menu, the value of the selected tax type is posted and stored in the 'data' variable. This value is then passed to a text field located next to the tax type dropdown. The entire functionality is ...