2

I want to send an email as soon as I click on html button. To do this task, I've written following code

HTML code:

<button onclick="sendEmail()">Send Email</button>
<p id="mailStatus"></p>

Java Script Code:

function sendEmail()
{
     $.ajax({
           url: "mail.php",
           type: "POST",
           success: function(response) {
               if (!response) {
                    alert("Something went wrong. Please try again");
                    return;
               }

               var parsedJSON = eval('('+response+')');

               // If there's an error, display it.
               if(parsedJSON.Error) {
                  // Handle session timeout.
                  if (parsedJSON.Error == "Timeout") {
                       alert("Session timed out. Please login again.");
                       window.location.reload();
                   }
                }
               document.getElementById('mailStatus').innerHTML = "Email Sent successfully";  
            }
     });
}

The problem if when I click on Send Email button, I get an error message as

"Uncaught ReferenceError: $ is not defined"

Can someone please help??

5
  • 3
    have you added jquery? Commented Feb 11, 2016 at 5:01
  • no.. as I am new to this thing, where should I add jquery??? Commented Feb 11, 2016 at 5:02
  • var parsedJSON = eval('('+response+')'); why eval? Commented Feb 11, 2016 at 5:02
  • @RaviSingh You have to add the Jquery library in your script files. Below is the link for Jquery reference cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.js Commented Feb 11, 2016 at 5:08
  • Thanks @Steve and Divyesh. Vicky, I copied the JS code, didn't realise about eval. I'll fix it up now.. Thanks all. Commented Feb 11, 2016 at 5:09

1 Answer 1

3

As $.ajax is function of jQuery so you need to add jQuery in your file.

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

Add this line above sendMail function.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome.. thanks mate.. This resolved my issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.