I have a form that submits data to parse.com using the code below:
<script>
function validateForm() {
Parse.initialize("xxxx", "xxxxxx");
var TestObject = Parse.Object.extend("Event");
var testObject = new TestObject();
testObject.save({
Name: document.forms["myForm"]["fname"].value,
Date: document.forms["myForm"]["date"].value,
success: function(object) {
$(".success").show();
},
error: function(model, error) {
$(".error").show();
}
});
}
</script>
however I was wondering if there was a way that I could simultaneously send an email with the contents of the form. Is this possible?
You would need some type of server side script to send email.
If you use PHP, you could use the mail function.
In the JavaScript, you would just send an AJAX request to the server-side file containing the code that sends the email.
Yes you can, use AJAX to send it. Here's an example code:
JavaScript
var name = "Test";
var last_name = "Last Test";
$.ajax({
type:"POST",
url:"your_php_file.php",
data:{
name : name,
lastname : last_name
},
success:function(data){
// TODO when success
}
});
And your PHP file would look like:
$name = $_POST['name'];
$lastName = $_POST['lastname'];
Note i've used different last name's on purpose.
EDIT: Forgot to mention, once in PHP you can send email either by using mail, PHPMailer or whatever you wish
Related
I m validating a data by clicking the submit button and then again loading the views. I want just to show the errors on the page before loading the controller. Its is not a form validation. it is just a data validiation.
I think you can do the validation using AJAX.
in view page
<script type="text/javascript">
$(document).ready(function() {
/// make loader hidden in start
$('#loading').hide();
$('#email').blur(function(){
var email_val = $("#email").val();
var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
if(filter.test(email_val)){
// show loader
$('#loading').show();
$.post("<?php echo site_url()?>/user/email_check", {
email: email_val
}, function(response){
$('#loading').hide();
$('#message').html('').html(response.message).show().delay(4000).fadeOut();
});
return false;
}
});
});
</script>
in controller function
public function email_check()
{
// allow only Ajax request
if($this->input->is_ajax_request()) {
// grab the email value from the post variable.
$email = $this->input->post('email');
// check in database - table name : tbl_users , Field name in the table : email
if(!$this->form_validation->is_unique($email, 'tbl_users.email')) {
// set the json object as output
$this->output->set_content_type('application/json')->set_output(json_encode(array('message' => 'The email is already taken, choose another one')));
}
}
}
I've script two script that i want to merge as one . Script 1 is for checking if email and password is right it brings out a success message "Correct" and it logs you in. Script 2 is what i use to store the email and password in a localstorge
Script 1
$(document).ready(function(){
$("#form1").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "log.asp",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="Correct"){
window.location = 'source.asp';
}
}
});
});
});
Script 2
$(function() {
var
$email = $('#email'),
$password = $('#password'),
localEmail = localStorage.getItem("eaddress"),
localPwd = localStorage.getItem("pwd");
// SAVE VARIABLES TO LOCAL STORAGE
$('#form1').on('submit', function() {
localStorage.setItem("eaddress", $email.val());
localStorage.setItem("pwd", $password.val());
});
});
Now i want to merge the two together that it should only save the email and password in the localstorge if the success message is equal
to "Correct" and also logs you in
Never ever store passwords on the client!
Never store passwords unencrypted!
To store the email address in the localStorage you can use this snippet:
$(document).ready(function(){
$("#form1").on('submit',function(event){
event.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: "log.asp",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="Correct"){
localStorage.setItem('eaddress', $('#email').val());
}
}
});
});
});
Note: You have to cleanup the localStorage yourself. If you want to store the data for further identification use a sessionId in a cookie or use the sessionStorage for saving temporary data.
Edit: To submit the form after page load you can try something like this:
$(function(){
var eAddr = localStorage.getItem('eaddress');
if (eAddr !== null) {
$('#email').val(eAddr);
$('#form1').trigger('submit');
}
});
Note: If you store the password encrypted on the client and submit it trough the form, the authentication process is quiet insecure.
I think your authentication design is wrong. You should use an authentication cookie (like a session cookie) and validate it on the server side. Without submitting a form every time a page loads nor storing credentials on the client side.
Have an email input that I'm trying to send to a function using Ajax. I retrieve a success message indicating that it's sent however I don't receive a message back from the php function echoing out the value. Can't see where I'm going wrong.
Any help would be great!
Jquery code is:
jQuery(document).ready(function($) {
$("#submit").click(function(e) {
e.preventDefault();
var vipEmail = $("#email").val();
var ajaxurl = '<?php echo admin_url( "admin-ajax.php", "relative" ); ?>';
console.log(vipEmail);
// This does the ajax request
$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'add_member',
member : email
},
success:function(data) {
// This outputs the result of the ajax request
$(".w-form-done").show();
$(".sign-up-form").css("display", "none");
},
error:function(errorThrown){
console.log(errorThrown);
//Show Error Message
$(".w-form-fail").show();
}
});
});
});
PHP Code inside functions.php is:
function add_member()
{
$member = sanitize_email( $_POST['email'] );
echo $member;
die();
}
add_action('wp_ajax_add_member', 'add_member');
add_action('wp_ajax_nopriv_add_member', 'add_member');
You declare a variable vipEmail, but you send member : email, email is not defined.
Then you look for $_POST['email'] instead of $_POST['member'].
So basically change member : email to email : vipEmail.
In addition to what Musa posted, to me it also looks like in success:function(data) you're not doing anything with data.
I would like to be able to authenticate a user in Joomla via an AJAX call so I can create the error effect if the login is incorrect and redirect the user if it is correct.
I would prefer to do it through the JQuery's .ajax API.
Also, do I need to somehow initialize JQuery or it is there already you just have to use "JQuery" instead of the "$"?
Try this,
You can use Joomla's login options for Ajax login authentication.
collect your user name and password via post and set to the array.
$options = array();
$options['remember'] = JRequest::getBool('remember', false);
$data['username'] = JRequest::getVar('username', '', 'method', 'username');
$data['password'] = JRequest::getString('password', '', 'post', JREQUEST_ALLOWRAW);
$credentials = array();
$credentials['username'] = $data['username'];
$credentials['password'] = $data['password'];
$app = JFactory::getApplication();
$error = $app->login($credentials, $options);
if (!JError::isError($error)) {
// login success
}
else{
//Failed attempt
}
The above code section can be write inside any of your controller function if you have any custom component. If your are using Joomla3.x you can use com_ajax for this task .
var data = "";//set your user name and password
jQuery.ajax ({
type: "POST",
url: "index.php?option=com_ajax&task=loginauth",
data: data,
success: function(data) {
}
});
When you include the jQuery library in your application then just access it with jQuery
'$' is used for moo-tools in Joomla.For including jQuery library you can just edit the template file templates/yourtemplate/index.php
Hope its helps..
My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.
Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";
I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;