Send an AJAX email in a Javascript funciton without using PHP - javascript

I was handed a website to work on and I'm not very familiar with AJAX. I was hoping there was a simple solution to the URL: portion of the Ajax in order to send an email. I'd rather not use a PHP script in place of what's already there but if needed I can.
This is for a website that's mostly bootstrapped with some simple HTML code and naming conventions are standard.
<script>
$("#btnSend").click(function () {
var email = $('#txtFromEmail').val();
if (($('#txtName').val().length === 0) || (email.length === 0) ||
($('#txtSubject').val().length === 0) || ($('#txtBody').val().length === 0)) {
alert("Please fill out all of the form.");
} else {
var emailModel = {
Name: $('#txtName').val(),
FromEmail: $('#txtFromEmail').val(),
Subject: $('#txtSubject').val(),
Body: $('#txtBody').val()
};
$.ajax({
url: "#Url.Action("Contact", "Main")",
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(emailModel),
success: function (result) {
if (result.message.length == 0) {
alert("Message Sent Successfully!");
} else {
alert("Message failed to send. Please try again or call the Sports Hub");
}
}
});
}
});
</script>

Ajax can make HTTP requests. That is all.
If you want to send email then you'll need to either:
Use the user's email client (and not Ajax) which is highly unreliable
Make an HTTP request to a web service that will send the email
You could write the web service in PHP, or you could use a different programming language (you seem to be using ASP.NET so any ASP.NET compatible language will do), or you could find a third-party hosted service.

There is no way you can send an email directly from Javascript.
Either you use php or open directly the mail client from the browser:
window.open('mailto:test#example.com');
If you want to pass more parameters you can use the following string:
window.open('mailto:test#example.com?body=body&subject=subject');

you can use an email web service to do this. i replaced my PHP page because it was a pain setting it up when i migrated from godaddy to aws. check out formspree. you will be able to integrate thru the front-end. on your first email you'll have to accept formspree emails, once you do, all other emails will be fwd to you.

Related

Making a GET request that uses POST method - Javascript to C# API

I have a situation where I'm required to encrypt data in flight from a JavaScript based application (Chrome Extension popup.html) to an API hosted in a .NET MVC website(C#).
I can run the request as a GET but project requirements make it necessary to encrypt the parameters I'm sending. For example if I was searching for all people named 'John' I need to encrypt 'John' in flight.
My JavaScript application is using jsencrypt and a RSA (public) key provided by the website in other APIs that work quite well to return counts.
If my GET version of the link looks like this:
<span class="person" id="personList">Person: '+ query +'</span>
On the .NET website end, this request is processed into a view that generates a table using a database call. As you can see in my link the results are populated onto a new tab in the browser.
How would you recommend changing it to calling a POST method and getting the same result as a GET?
EDIT
I tried to employ an AJAX function to make the POST but it doesn't like the data element:
event.preventDefault();
$.ajax({
url: repurl + 'Persons/Search',
timeout:30000,
type: "POST",
data: {body: encryptedmsg},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
alert('ok');
}
else
{
alert('some thing went wrong, plz try again');
}
}
});
});```

How to get data from JS prompt into php

I have a mini-project to finish and I am facing a problem. I created a button to delete data from database and it works. But I want to add a prompt which asks for a password. I read that JavaScript is required.
So I used this code:
echo
"
<script>
var password=prompt('Please enter the password');
$.ajax(
{
type: 'POST',
url: '/test.php',
data: password,
success: function(data, textStatus, jqXHR)
{
console.log(data);
}
});
</script>
";
if($_POST['data'] == "admin")
{
The rest of the code doesn't matter. But it throws me this error:
Uncaught ReferenceError: $ is not defined
Any solutions? I am new in PHP and I've never used JavaScript before :)
You will need to add a reference to jQuery before you use the $ operator.
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
You need to include jquery in your code. Just add this before your scripts.
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
You're trying to use the jQuery library, but haven't included the jQuery script necessary to run it. However, I would not recommend including an entire library to perform a single task.
Presumebly, your browser supports the Fetch API, which does the same as jQuery' $.ajax function, but natively. I would suggest that you learn how to use JavaScript without any libraries.
The example below shows how you should do this with the Fetch API. It sends a POST request with the password in an object. That object is transformed to JSON before being sent. JSON is a intermediate language that both JavaScript and PHP can understand, so it's a perfect way of communicating between two languages.
The request expects a response that is text based. Whenever a response is received it will print the received string to the console.
var password = prompt('Please enter the password');
fetch('/test.php', {
method: 'POST',
body: JSON.stringify({ // Send the object as JSON
password: password
})
})
.then(response => response.text()) // Decode the response as text.
.then(text => {
console.log(text); // Log the received text.
});
On the PHP side, try to keep this logic in a seperate file. Your Fetch request will call the PHP file and the PHP file should send back a response.
The example below checks if the password key in the $_POST array exists. Because we converted our JavaScript object into JSON earlier, PHP is able to convert it into an assosiative array. So JS is effectively turned into PHP at this point.
Then check if the $password equals the admin string and return a string. This returned string will be sent back to client and processed as the response.
$password = $_POST['password'] ?? ''; // If the password key does not exist, use an empty string.
if ($password === 'admin') {
return 'Password is admin';
} else {
return 'Password is NOT admin';
}
die(); // Stop this file from running any further.

jQuery AJAX request to remote API blocked

I have been successfully accessing data from an external weather data service API for some time now using PHP cURL. Sometimes it takes a few seconds, sometimes up to 15 seconds for this web service to process my request. Therefore, I would like to perform this operation asynchronously.
I am trying jQuery AJAX to send this GET request now. However, it keeps throwing the following error:
"No Access-Control-Allow-Origin header is present on the requested resource".
I'm aware of the "same origin policy" restrictions, and have been researching it extensively here on stackoverflow and the jQuery docs. The docs say that JSONP requests are not subject to this restriction. When I try to designate JSONP as the dataType, I get an "unexpected token" syntax error.
I have the user entering in their zip code into a form text box, then click the button to submit. This sends the GET request to the web service. I'm very comfortable with PHP, but a newbie with jQuery and AJAX. I appreciate the help with this, and look forward to the day when I can help others as I've been helped here.
Here is the jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnGetETo').click(function () {
var resultElement = $('#resultDiv');
var requestData = $('#txtZip').val();
$.ajax({
url: 'http://et.water.ca.gov/api/data?appKey=B51CF64B-C37B-406A-83F1-1DBD8CE40EEF&targets=94805&startDate=2015-07-01&endDate=2015-07-01&dataItems=day-asce-eto,day-eto,day-precip&unitOfMeasure=E;prioritizeSCS=Y',
method: 'get',
data: { q: requestData },
dataType: 'json',
success: function (response) {
if (response.message != null) {
resultElement.html(response.message);
}
else {
resultElement.html('ETo: ' + response.DayAsceEto[0].value);
}
},
error: function (err) {
alert(err);
}
});
});
});
</script>
Unfortunately, it seems that the API in question does not support JSONP. In fact, they seem to have gone out of their way to make it difficult to query via JavaScript.
Here's how to test for JSONP (not foolproof, but most mainstream JSONP-enabled services will respond correctly). Take whatever URL you were planning to send, and add &callback=foo to the end of it. (If there are no other query string parameters of course, use ? instead of &.)
If the server supports JSONP, the response should look like:
foo({
...
});
If not, it'll look like:
{
...
}
As you can see, the only difference is that JSONP-enabled servers can wrap the JSON in a function of arbitrary name. Some servers will insert a little extra code for safety/convenience. For example, the following output was generated by the JSONplaceholder API using the URL http://jsonplaceholder.typicode.com/users/1?callback=foo:
/**/ typeof foo === 'function' && foo({
"id": 1,
"name": "Leanne Graham"
...
});
The upshot of all this is that it's the API provider's fault, not yours. If I were giving them feedback I'd make the following suggestions:
Handle cross-origin requests correctly.
Allow fallback to JSONP.

Assign JavaScript variable value from view to controller variable

I am trying to assign a value from a variable created in JavaScript in my view to a variable in my controller. How can I do that? I am new to CodeIgniter and JavaScript.
The idea is that I validate an email input field in my view with JavaScript and then assign that value to a controller variable and then retrieve that value in my controller.
$john_email is my controller variable and email my JavaScript variable
$('#submitRequests').click(function(){
console.log("Clicked submit");
var data = getTableContent();
console.log("machines: ");
console.log(data);
var email = $("#emailInput").val();
if(isEmail(email)){
$john_email = email; // something like this!
uploadMachines(data);
}
else
alert("Incorrect email");
});
It sounds like you're very new to client-server programming. JavaScript runs on the client (web browser), PHP runs on the server. To send data from JavaScript to PHP, you need to submit the data back to the server, either by posting the page, or by using AJAX for asynchronous communication with the server (allowing you to send data back to the server and update the page on the client without posting and reloading it).
There are many great tutorials on AJAX out there, and I've linked, what I feel, is the best one. Read up on the subject, and if you still need help, report back with what code you've tried and what results you got.
Since you are already using jQuery in your code, take a look of jQuery.ajax() method. Also, for CodeIgniter take a look of Input class.
// Javascript
$('#submitRequests').click(function(){
console.log("Clicked submit");
var data = getTableContent();
console.log("machines: ");
console.log(data);
var email = $("#emailInput").val();
if(isEmail(email)){
$.ajax({
type: "POST",
url: base_url + "controller/post_email", //here base_url = http://domain.com
data: {email: email},
dataType: "text",
cache:false,
success:
function(john_email){
alert(john_email);
}
return false;
});
}
else
alert("Incorrect email");
});
//codeigniter controller
<?php
function post_email()
{
$john_email = $_POST['email'];
return $john_email;
}
?>

Securing an AJAX service call in jQuery and PHP (with session token)

I'm currently building a framework in which for example form submit's are being implemented as jQuery ajax calls to a .php (service) file.
Part of the jQuery for reference:
var dataSerialized = $(form).serialize();
var service = $(form).attr("action");
$.ajax({
url: "services/" + service + ".php",
data: dataSerialized,
type: "POST",
cache: false,
dataType: "json",
success: function(json) {
$(json).each(function() {
loadPage(this.callback);
});
},
error: function(json, message) {
finalError(message);
}
});
And the .php does currently nothing more than:
include_once("../content/includes/connect.php");
include_once("_functions.php");
//TODO: support sending variables
$check = true;
$callback = "error";
foreach ($_POST as $key => $value) {
list($pass, $errormessage) = checkRules("register", $key, $value);
if (!$pass) {
$check = false;
$callback = "error";
break;
}
}
if ($check) {
$callback = "register_success";
}
echo json_encode(array(
"callback" => $callback
));
SQL::close();
Now I want the service call to be as secure as possible, given my situation, I see the following options:
SSL cannot be used, as it is relatively too expensive. Just working on a homebred project, nothing important.
jCryption library cannot be used, as I'm on a cheap web hosting and do not have access to the server itself.
OAuth 2.0 is a possibility, but seems quite complicated.
$_SERVER variables can be used to help protecting the service .php pages, but not reliable.
$_SESSION could be used to generate tokens.
I already implemented an easy measure: Change GET to POST. This will only deter the most easy attack, now the attacker actually needs to use some tampering tool instead of being able to do it directly through the browser.
I think I can protect every call that comes from an URL typed in the browser, however I see two serious threats:
Direct requests to the webserver: The attacker can pass any data he wants.
Using a Browser JavaScript Console to send custom jQuery requests.
I think it is best, again under these circumstances, to try to protect the service .php pages with $_SESSION tokens, but how exactly do I go about these?
They need to be set as some point in time before the service call, and then the service call could check it.
I also have access to a MySQL database and of course plain text files on the webspace.
Can anyone help me out any further?
Have a csrf token send together with the form and in your .php file you could use something like this
session_start();
if ($_SERVER['HTTP_X_CSRF_TOKEN'] !== $_SESSION['csrfToken']) {
return false;
die();
}
Send CSRF Token with all service calls
$.ajaxSetup({
headers: {
'X-Csrf-Token': "TOKEN HERE"
}
});

Categories