I have an html form and I would like to achieve two things with it:
1) - When user clicks on "submit" the data is automatically sent to a specific email and 2) - the user is redirected to a "confirmation page". I do not want to use mailto function as it is pretty bad since its browser dependent. I would like to use a light script... Is it possible using js?
You cannot do this with JavaScript alone.
What you can do is use AJAX to send your form data to a server-side script which will send your email, then the AJAX success handler can redirect the page to some confirmation page.
Some hosts have email scripts installed, like CGI scripts, to handle sending email for you on the server side.
This is essentially the best you can do on the client side (using jQuery for ease):
var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
// Redirection on success
var url = "http://example.com/confirmation.html";
$(location).attr('href',url);
}
});
and the essential server-side script:
<?php
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Input sanitation omitted
// Send the email
mail("my.email#gmail.com", "Message from {$name} - {$email}", $message);
}
No, it's not possible in pure JavaScript.
Related
I have a login form includes password field. I show this login form in modal way and I would like to handle the form submit response is a special way(actually update the login bar to a account menu), so i prevent the default form submit by
$("#myformid").submit(function(event){
var form = $(this);
console.log(form.serialize());
event.preventDefault();
jQuery.ajax({
url: "http://localhost:5782/login",
success: function (data) {
login_form_modal.style.display = 'none';
},
data: {
form: form.serialize(),
},
type:"POST",
async: false,
});
})
I noticed that in the browser debug console, the password is plain text. My question is, is it safe to submit a serialized form using ajax?
'csrf_token=IjI4ODJZjJmMWI5MGU1ZMjM1Y2Y0M2QxNzY3ZGUwZmI5MDki.YcCuVA.3D_79wx6Lp2-hbZWRT04z_eGhbc&username=myusername&password=MyPlainTextPassword'
Thanks,
You have to send the password from the client to the server.
Both the client and the server need to know what it is — the client because it produces it and the server because it has to pass it through the right hash algorithm and compare it to whatever is in the database.
What you don't want is for the password to be intercepted in transit. The way to do that is to use HTTPS and not plain HTTP. (This obviously doesn't matter when you are working with localhost URLs and the data is development data and not production data, but needs to be dealt with for your production deployment).
I have a form that the users complete and then press "Submit" button to register.
I wanted to preview the data to the user before the form is submitted, so i used AJAX to do this. The procedure is as follows:
1) User clicks "submit" button (ex. registration.php)
2) JS script, prevents the default action (which is to submit it) and calls another PHP script via AJAX (registrationAJAX.php), that:
a) Performs some database changes
b) stores some variables in a $_SESSION array
$_SESSION['userID'] = $uID;
$_SESSION['userEmailAddress'] = $email;
$_SESSION['hash'] = $hash;
c) json_encodes the following array:
$results = array(
'result' => 'success',
'message' => 'registration was successful'
);
echo json_encode($results);
d) then exits
exit();
3) Back to JS script and on AJAX success, i check to see whether the result is "success" and then redirect the user to a script that sends an automated email for account verification:
$.ajax({
type: "POST",
url: "js/ajax/registrationAJAX.php",
data: {form data...},
cache: false,
success: function(output){
var outputJSON = $.parseJSON(output);
var status = outputJSON.result;
if(status == 'success')
{
location.href = "https://domain.com/verify.php";
}
}
});
The verify.php script MUST have access to the $_SESSION variables to be executed correctly.
//the code will only executed if the $_SESSION['hash'] is set:
if(isset($_SESSION['hash']))
{
//SEND EMAIL ACTIVATION EMAIL TO USER
//INFORM THE DATABASE THAT THE EMAIL IS SENT
}
Sometimes i see that some of my users don't receiver the activation email. This will happen if the verify.php script doesn't have the $_SESSION variables i stored during registrationAJAX.php and then fail (as shown at the code above).
Question:
1)Is there a possibility that the variables delay to get stored in the $_SESSION and the redirection to verify.php is performed with no $_SESSION variables?
2) Does the exit() command cause a problem?
You should consider move to OAuth authentication to avoid the issue with the cookies disabled:
http://www.sitepoint.com/creating-a-php-oauth-server/
Regards,
I'm trying to send an email using the PHP mail function, but the required content is stored in a JS variable, I'll try to code out my situation for you to understand better.
<script type="txt/js">
var content = "This is what I need to send via email";
if({Irrelevant validation check})
{
alert("Form submitted! Redirecting... <?PHP mail('admin#admin.com', 'subject', [XXX]);?>");
}
</script>
I need the text stored in the content variable to be in place of the [XXX] above.
I would appreciate any help. :)
You can try this way simpler using $.post():
$.post("sendEmail.php", { contentData: content }, function(response) {
console.log(response);
//Form submitted! ...Redirecting...
});
sendEmail.php
$content = $_POST['contentData'];
$to = 'someemail#domain.com';
$subject = 'The content';
$message = 'Content'.$content;
$headers = 'From: youremail#domain.com' . "\r\n";
if (mail($to, $subject, $message, $headers)){
echo "Your email was sent!";
}else{
echo "Email did not send";
}
As others have mentioned it, using AJAX is your best option. You can pass the information to the php file using AJAX as follows:
$.ajax({
type : "POST",
url : url,
data : content,
success : alert('success'),
error: alert('error')
});
To have better data handling, you can define a Formdata and save the content var in that data.
var data = new FormData();
data.append("content", content);
and then you can post this data:
$.ajax({
type : "POST",
url : url,
data : data,
success : alert('success'),
error: alert('error')
});
No, you cannot use pure javascript to do ANYTHING that affects the PHP code. PHP is run on the server side. Javascript is run on the client side. However if you set up your php as a service, i.e. in PHP set up page X to accept mail information, and then use javascript to post to page X, page X will effectively send the mailing with the info given to it by javascript. But javascript cannot directly affect PHP code.
PHP Code is rendered first, Then HTML, Then Javascript. It's the web stack.
AJAX can be used to talk back and forth between client and server like the other answers are mentioning, but the question was is it possible and how do you use JS to send mail via PHP.
I simply used the window.open(url.php?var=var); method using Javascript, and passed the variable through the GET parameter, then the "url.php" page picked it up via $_GET['var'];
Its better to use AJAX in this kind of situations. Pass the "var content" value via AJAX and do whatever you want.
I am creating a login page in PHP. On entering wrong username/password I am showing a javascript alert box. I now want to navigate user back to login page on clicking "OK" button of alert box . Am using "header(location:url)", but then javascript code is not working.
Is there any other way to do this.
You can try this
echo "<script language='javascript' type='text/javascript'>alert('error');
</script>";
echo "<meta http-equiv='refresh' content='1; URL=login.php'>";
For JS redirect, try;
window.location.href="http://url";
Hope this helps :)
Put this code in the login error page ..
<script>
alert('Wrong Username/Password');
window.location = "http://www.google.com";
</script>
But if you are familiar with jquery i advice you to do the login process with ajax request and show the notifications in the same page instead of navigating back and forth.
If you need i can create a simple one in plnkr
For the js redirect, u can use
window.location.href='http://whereEver';
Note: Username/ password validations are server side. Assuming its an ajax call, after you get the validation results, instead of triggering an alert, have a div in the page itself where you can inject the server response. Alerting looks unprofessional.
Better approach would be something like
HTML
<div class="response"></div>
CSS
.response {
display:none;
}
.error {
color: red; // find a better color
}
PHP
On validation failure, have a variable, lets call it status and make it false.
The validation response can be something like,
$response = ['status' => false, 'message' => 'Username / password mismatch'];
Then send back the results
die(json_encode($response));
Note: If you are using PHP < 5.4, use
$response = array('status' => false, 'message' => 'Username / password mismatch');
JS
$.ajax({
url: 'url-to-post',
type: 'POST',
data: $('form[name="your-form-name"]').serialize(),
dataType: 'json',
success: function(data) {
if (!data.status) {
// inject into response
$('.response').addClass('error').html(data.message).show();
}
else
{
// redirect them to home page, i assume
window.location.href = '/home';
}
}
});
I have an HTML form that is processed via PHP, and it's a simple login script. This works fine, but I want to catch the error with AJAX. Basically, if the PHP function to check the login returns false, it should write that error onto the DOM via jQuery. However, if I catch the form submission with AJAX, it will stop the PHP file from doing the redirect. I want to stop the form from redirecting only if the PHP file returns false. Any help would be much appreciated. Here's some code to illustrate what I'm talking about:
controller_login.js
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
errorHandle(response);
}
});
return false;
});
});
function errorHandle(error)
{
console.log(error);
}
This is the file that will eventually modify the DOM if there is a PHP error. For now, it just logs.
checkLogin.php
if($verifySqlRequest==1){
session_register("loginUsername");
session_register("loginPassword");
header("location:http://localhost/asd/dashboard.html");
echo "login success!";
}
else{
echo "Wrong user name or password...";
}
This is just a snippet of the login authentication, but essentially I want that last echo to be communicated to controller_login.js, but it should continue the redirect if the login is successfully authenticated. Any help would be much appreciated!, thanks!
The browser isn't going to respond to a 302 or 301 (redirect) from an Ajax call. You can still certainly respond with that code, but, you'll have to handle the redirect manually via script:
window.location.replace("http://localhost/asd/dashboard.html");
or you can do it like this
> echo '<script>window.location.replace("http://localhost/asd/dashboard.html")</script>';
and
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
$('#response_element').html(response);
}
The point of using Ajax is to avoid reloading the page. If the user is going to be redirected upon login you may as well just submit the form synchronously and let PHP display the error.
Just for the sake of argument, if you wanted to do an Ajax function and display a message returned from the server you would NOT do:
<?php
echo 'this is the message';
?>
You would do
<?php
$response = array('message' => 'this is my message');
return json_encode($response);
?>
However, you can't redirect AND return data.