How to call method from CS page using AJAX? - javascript

I want to call the method which is in CS page using AJAX.
Here is my design code:
<!-- Name -->
<input type="text" name="name" id="name" required="required" class="form" placeholder="Name" />
<!-- Email -->
<input type="email" name="mail" id="mail" required="required" class="form" placeholder="Email" />
<!-- Subject -->
<input type="text" name="subject" id="subject" required="required" class="form" placeholder="Subject" />
<!-- Message -->
<textarea name="message" id="message" class="form textarea" placeholder="Message"></textarea>
<!-- Send Button -->
<button type="button" id="submit" name="submit" class="form-btn semibold">Send Message</button>
Here is the ajax
$(document).on("click", "#submit", function (e) {
$.ajax({
type: "POST",
url: "OakscrollWebService.cs/SendMail",
dataType: "json",
data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
failure: function (data) {
alert("something went wrong");
//console.log(msg);
}
});
});
Now, I add the asmx page (web service). In that I have given the reference call to the CS file which is in App_Code folder, here is the code.
<%# WebService Language="C#" CodeBehind="~/App_Code/OakscrollWebService.cs" Class="OakscrollWebService" %>
Here the cs file from where I want to call the SendMail method using ajax (which code I shown you previously) and here is the method code in cs file
[WebMethod]
public static void SendMail(string name, string email, string subject, string message)
{
//Thread.Sleep(10000);
// Gmail Address from where you send the mail
var fromAddress = "mextra03#gmail.com";
// any address where the email will be sending
var toAddress = email.Trim();
//Password of your gmail address
const string fromPassword = "*********";
// Passing the values and make a email formate to display
string sub = subject.Trim();
string body = "From: " + name.Trim() + "\n";
body += "Email: " + email.Trim() + "\n";
body += "Subject: " + subject.Trim() + "\n";
body += "Message: \n" + message.Trim() + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, sub, body);
}
This is the content I used to call the sendmail method by ajax. But facing issues like "403 forbidden" and "500 server not found" and can't call the sendmail method using AJAX.

Hi I think you need to change your url to have the file extension .asmx instead of .cs (change the line url: "OakscrollWebService.cs/SendMail", to url: "OakscrollWebService.asmx/SendMail",) because when I tested it I was getting a 404 error meaning the page was not found. You could also create a variable to check that your JSON is correct using JSONLint.
$(document).on("click", "#submit", function (e) {
var data = '{"name":"' + $('#name').val() + '", "email":"' + $('#mail').val() + '", "subject":"' + $('#subject').val() + '", "message":"' + $('#message').val() + '"}'; //Optional to check your JSON
$.ajax({
type: "POST",
url: "OakscrollWebService.asmx/SendMail",
dataType: "json",
data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
failure: function (data) {
alert("something went wrong");
//console.log(msg);
}
});
});
});
Good luck!

Related

html form in Django returns none

I am trying to save this HTML form in my table in the database, but I am getting "None" error. I have been on this for some hour. Please any help will be appreciated
Please, how do i fix this
The is the HTML order.html i created
<form action="" method="post" id="payment-form">
<input type="text" class="form-control" id="first_name"
name="first_name"
value="{{request.user.first_name}}">
<textarea type="text" class="form-control" id="address" name="address"
placeholder="1234 Main St" required></textarea>
<button id="submit" class="btn btn-success lg w-100 fw-bold" >
Proceed to Payment
</button>
</form>
Here is my views.py
def add(request):
basket = Basket(request)
if request.POST.get("action") == "post":
order_key = request.POST.get("order_key")
user_id = request.user.id
baskettotal = basket.get_total_price()
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
print(first_name, last_name, address)
order = Order.objects.create(
first_name = first_name,
address=address,
total_paid=baskettotal,
)
order_id = order.pk
response = JsonResponse({"success": "Order created"})
return response
The js file
<script type="text/javascript">
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
</script>
First of all you don't have to post extra value action to determine post request you just have to use request.method it will return you all available method you can check for specific method by adding check like this
if request.method == "POST":
note : allways use capitalized method while adding this check
and I'm not sure where you're calling makePayment() function and whatever data you're trying to access in your python script you've to pass it through ajax{data:{}} like this
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
order_key : "your order key",
first_name : $('#first_name').val(),
last_name : $('#last_name').val(),
address : $('#address').val()
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
and than access it like this
def add(request):
basket = Basket(request)
if request.method == "POST":
order_key = request.POST.get("order_key")
#....all other fields

downloading pdf using jquery after submit function

in this code from https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
<center>
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"><textarea><!--textarea tag should be closed (In this coding UI textarea close tag cannot be used)-->
<br><br>
<a id="linkID" href="#" >
<button type="button" class="btn btn-primary" onclick="sendEmail()" value="Send An Email"
>Submit</button>
</a>
</form>
</center>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
when I click the submit button, I want to download a pdf called "./sales.pdf" only when the submit is a success
this is what i tried to change in the code in the script, i have added $('#linkID').attr({target: '_blank', href : url}); but this does not give any result, nothing downloads
also in phpmailer...if i try to add three forms on the same page, they all stop working..is it related to script integrity?
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
var url = "./Sales.pdf";
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name:email.val(),
email: email.val(),
subject: body.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('#linkID').attr({target: '_blank', href : url});<<<<<----this
}
});
}
Since jQuery 3.0, success: function does no more work as it has been suppressed, see https://api.jquery.com/jquery.ajax/ .
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use
jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
But you can use this arrangement for the new sendMail():
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendMail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}
})
.done(function(response) {
//alert(response.status);
$('#myForm')[0].reset();
$('#linkID').attr({target: '_blank', href : "./sales.pdf", download: "download"});
$('#linkID')[0].click();
})
;
}
}
When you press submit, after sending mail, sales.pdf will be automatically downloaded.

Shopify Trying to update a customer

I'm trying to create a view where my customer can update his personal info (like First Name, Last Name, email, ect) using Liquid/JS, but I have failed epicly.
The nearest point that I have reached is this post where they use a form and some AJAX to update but I'm getting code 500. This is the code that I'm using (based on that).
<form action="/a/custmeta" method="POST" id="custmeta">
<input type="text" name="customer[id]" value="{{ customer.id }}" />
<input type="text" name="customer[first_name]" value="{{ customer.first_name }}" placeholder="namespace1.key1" />
<input type="text" name="customer[last_name]" value="{{ customer.last_name }}" placeholder="namespace2.key2" />
<input type="submit" />
</form>
<script>
$('form#custmeta').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
data: $(this).serialize(),
url: '/admin/customers/#{{ customer.id }}.json',
success: function (data) {
var formValid = (data.status === 'OK');
if (formValid) {
var msgs = '';
for (var i=0;i<data.messages.length;i++) {
msgs += '-- ' + data.messages[i] + '\n';
}
if (msgs > '') {
alert('SUCCESS WITH MESSAGES:\n\n' + msgs);
}
else {
alert('SUCCESS!');
}
}
else {
alert('Status: ' + data.status + '\nMessage: ' + data.message);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('AJAX or Server 500 error occurred');
}
});
return false;
});
</script>
found this other post where you could do it using the API but dont know how to use it.
Any help?

Adding email into MySQL database with PHP, JQuery, Ajax

My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?
Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});
There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});
Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.
You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});

SharePoint 2013 Send Email from Contact Us Form via REST/JS

and thanks in advance for your answers.
I am trying to send an email from a contact us form. It appears to work but I don't receive any emails. I don't have any experience with REST and would like someone who does to see if they can spot any problems.
This is on a SharePoint 2013 Enterprise Publishing Site.
I have changed some variables and IDs for privacy purposes.
The HTML is in a custom page layout, and the JS is being called successfully in the same page layout after jQuery.
JS:
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
function submitForm() {
var toAddress = "email#domain.com";
var fromAddress ="email#domain.com";
var emSubject = "Public Contact Us Form Entry";
var lblName = "Name: ";
var valName = document.getElementById('form-name').value;
var lblEmail = "Email: ";
var valEmail = document.getElementById('form-email').value;
var lblMessage = "Message: ";
var valMessage = document.getElementById('form-message').value;
var emBody = lblName.concat(valName,lblEmail,valEmail,lblMessage,valMessage);
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: toAddress,
Body: emBody,
Subject: emSubject
}
}
var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('User(s) notified')
},
error: function (err) {
alert("Unable to send email -- " + JSON.stringify(err));
}
});
}
});
HTML:
<div class="label">Name</div>
<input name="Name" type="text" id="form-name" size="40">
<div class="label">Email</div>
<input name="E-mail" type="text" id="form-email" size="40">
<div class="label">Message</div>
<textarea name="Message" cols="55" rows="5" id="form-message"></textarea>
<div class="form-button">
<button onclick='submitForm()'>Submit</button>
</div>
You code has one mistake:
I changed To: toAddress to To: { 'results': [toAddress] }.
Now every thing is working fine and I am also getting the emails.
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: { 'results': [toAddress] } ,
Body: emBody,
Subject: emSubject
}
}

Categories

Resources