I have a form made with ajax, in this form there are 2 submits, both have the same function as sending an email but depending on whether the user uses one or the other the email must indicate this selection.
I tried to use the isset function to see which of the two buttons to submit but when I receive this parameter it is empty.
HTML form
<form id="form-landing" data-ajax="<?php echo admin_url('admin-ajax.php?action=contactlanding'); ?>">
<?php while (have_posts()) : the_post();
the_content();
endwhile; ?>
<?php wp_nonce_field(); ?>
<div id="step1">
<div class="group-form">
<p>1.- question 1</p>
<div>
<label for="afrontarsi">Yes</label><input type="radio" name="afrontar" value="Si" id="afrontarsi">
<label for="afrontarno">No</label><input type="radio" name="afrontar" value="No" id="afrontarno">
</div>
</div>
<div class="group-form">
<p>2. - Question 2</p>
<div>
<input type="text" name="importe" id="importe"> €
</div>
</div>
<button class="send-button" name="1button" href="">Yes</button>
<button class="send-button" name="2button" href="">No</button>
</form>
jQuery
if(is_page_template('template-landing.php')): ?>
$('#form-landing').submit(function(e){
e.preventDefault();
var form = $(this).addClass('loading');
var alert = form.find('.alert').removeClass('alert-danger alert-success').html('');
$.ajax({
url:form.data('ajax'),
type:'POST',
data:new FormData(this),
processData:false,
contentType:false,
}).done(function(data){
form[0].reset();
form.find('.btn').prop('disabled',true);
alert.addClass('alert-success').html(data);
}).fail(function(error){
alert.addClass('alert-danger').html(error.responseText);
}).always(function(){
form.removeClass('loading');
});
});
<?php endif;
?>
PHP function
function contactlanding(){
if(check_ajax_referer()){
$afrontar = sanitize_text_field($_POST['afrontar']);
$importe = sanitize_text_field($_POST['importe']);
if (isset($_POST['1button'])) {$button="First";} else{$button="Second";}
$web = parse_url(home_url(),PHP_URL_HOST);
$message = '<p><strong>Afrontar:</strong> '.$afrontar.'</p>';
$message .= '<p><strong>Importe:</strong> '.$importe.'</p>';
$message .= '<p><strong>Button:</strong> '.$button.'</p>';
$headers = 'MIME-Version:1.0'."\r\n";
$headers .= 'Content-type:text/html;charset=utf-8'."\r\n";
$headers .= 'From:noreplay#'.$web."\r\n";
$headers .= 'Reply-To:'.$email."\r\n";
$send = mail(get_bloginfo('admin_email'),'Mensaje enviado desde '.$web,$message,$headers);
if($send==true){
echo 'Gracias, tu mensaje se ha enviado correctamente.';exit;
}
}
http_response_code(400);echo 'Algo salió mal, por favor intenta más tarde.';exit;
}
You can store the action in an hidden input.
Your server will receive the data, and you will be able to read it. Next, a very simple approach to show you the way :
$('.send-button').on('click', function (){ $(this).closest('form').find('[name="action"]').val($(this).data('submit'))
})
$('form').on('submit', function(evt) {
// form content :
console.log($(this).serialize());
// prevent form submission for the demo
evt.preventDefault();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type="text" name="firstname" value="Johon" />
<input type="hidden" name="action" value="" />
<button class="send-button" name="1button" href="" data-submit="yes">Yes</button>
<button class="send-button" name="2button" href="" data-submit="no">No</button>
</form>
Related
I have a little problem here. I'm working on a simple quotation form on wordpress.
I have two forms, the first one sends data to jQuery that does all the calcs (very few options so we didn't use a DB), then prints an html row. No issue until here; the problems start when I'm trying to send that row/rows to PHP to send a simple email. I've tried with ajax and wp_mail but with no success.
Here is what i've tried:
HTML inside wordpress template file:
<!--first form with data to calculate-->
<form class="needs-validation">
<!--select fields, no problem here-->
</form>
<div class="table-responsive"> <!--risultato preventivo-->
<table class="table table-bordered" id="dynamic_field">
<tr>
<!--result given by jQuery-->
</tr>
</table>
<p id="total"><!--total price passed by jQuery--></p>
</div>
<!--second form for sending email-->
<form action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
<div id="worked"></div>
jQuery with calcs inside file main.js:
(function ($) {
$(document).ready(function () {
function generaRisultato (riga,nProfilo,nColore,nSerramento,costoRiga){
var risultato = '<tr id="row' + riga +
'" class="dynamic-added"><td><div><h5 class="my-0">Articolo: ' + nProfilo +
'</h5><br><small class="text-muted">Colorazione: ' + nColore +
'</small><br><small class="text-muted">Serramento: ' + nSerramento +
'</small></div><span id="costo-riga'+riga+'">'+costoRiga+'€</span></td>'+
'<td><button type="button" name="remove" id="'+ riga +'" class="btn btn_remove">-</button>
</td></tr>';
return risultato;
}
//calcs done correctly
$('#dynamic_field').append(generaRisultato(i,profile,color,name,price)); //result printed
var risultatoFinale = $('#dynamic_field').html(); //variable with result stored for email
//sending form mail ajax
$('#inviaForm').on('submit', function(e){
//evito l'invio del form
e.preventDefault();
//recupero i valori
var nomeUser = $('#nome').val();
var cognomeUser = $('#cognome').val();
var emailUser = $('#email').val();
var totaleFinale = $('#totale').html();
var preventivoFinale = $('#dynamic_field').html();
//eseguo la chiamata ajax
$.ajax({
type: "POST",
url: my_vars.ajaxurl,
data: {
action : 'invio_mail', //azione da eseguire
_nonce : my_vars.nonce,
nome : nomeUser,
cognome : cognomeUser,
email : emailUser,
totale : totaleFinale,
preventivo : preventivoFinale
},
success: function(res){
$('#funzionante').html(res);
}
});
});
});
})(jQuery);
PHP inside functions.php:
function vf_load_theme_preventivatore(){
wp_register_script('main', get_template_directory_uri().'/preventivatore/js/main.js', false, false,
true);
wp_enqueue_script('main');
wp_localize_script( 'main', 'my_vars', array(
'ajaxurl' =>admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('invio-mail-nonce')
));
}
add_action('wp_enqueue_scripts', 'vf_load_theme_preventivatore');
function invio_mail_ajax(){
//verifico che il nonce sia corretto
if(!wp_verify_nonce( $_REQUEST['_nonce'], 'invio-mail-nonce') ){
die('Non autorizzato!');
}
//Prepariamo le variabili da usare
$successo = '';
$nome = strval($_REQUEST['nome']);
$cognome = strval($_REQUEST['cognome']);
$email = $_REQUEST['email'];
$preventivo = $_REQUEST['preventivo'];
$totale = $_REQUEST['totale'];
//script mail
$header = "From: Site <test#site-domain.it>\n";
$header .= "BCC: Altro Ricevente <test2#my-domain.it>\n";
// costruiamo le intestazioni specifiche per il formato HTML
$header .= "Content-Type: text/html; charset=\"UTF-8\"\n";
$oggetto = "Ecco il tuo preventivo";
$messaggio = "<html><body><p>Richiesta preventivo da sito</p><p>Nome: ".$nome."</p><p>Cognome:
".$cognome."</p><p>Email: ".$email."</p> <p>Dati del preventivo</p><p>".$preventivo."</p><p>Totale:
".$totale."€</p></body></html>";
$inviata = wp_mail($email,$oggetto,$messaggio,$header);
$successo .= '<p>'.$nome.'</p>';
echo $successo;
die();
if($inviata){
$successo = '<p> email invata</p>';
echo $successo;
die();
} else die('errore nella mail');
}
add_action('wp_ajax_invio_mail','invio_mail_ajax');
add_action('wp_ajax_nopriv_invio_mail','invio_mail_ajax');
That's what i've done, i've simply hidden the jQuery calculations because that worked flawlessly.
I wanted to send an email with an html formatted text, with this solution the email doesn't even get sent (before putting ajax and php script in fuction the email arrives, php was inside the template file), also i cannot pass the html table rows with results and the total of the quotation. Maybe i got wrong the ajax or php part.
Is there any help about this? thank you for all your support!
Created AJAX submit form. Tested working good you can change your data. Hope this help you.
Copy and paste in your function.php file
function invio_mail(){
$to = 'sendto#example.com';
$subject = 'The subject';
$body = 'The email body content';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail( $to, $subject, $body, $headers );
echo 'mail send';
die;
}
add_action("wp_ajax_invio_mail", "invio_mail");
add_action("wp_ajax_nopriv_invio_mail", "invio_mail");
Just paste you want the page (Form)
<form id="ajaxformid" action="#" method="POST">
Nome:<br>
<input type="text" name="nome" id="nome">
<br>
Cognome:<br>
<input type="text" name="cognome" id="cognome">
<br>
Email:<br>
<input type="email" name="email" id="email">
<input type="hidden" name="invia" value="s">
<input type="submit" id="inviaForm" value="Invia">
</form>
Just paste in footer
<script>
jQuery(document).ready(function($) {
var frm = $('#ajaxformid');
frm.submit(function (e) {
var formData = {
nome: jQuery('#nome').val(),
cognome: jQuery('#cognome').val(),
email: jQuery('#email').val(),
action:'invio_mail'
};
$.ajax({
type : 'POST',
url : "<?php echo admin_url('admin-ajax.php'); ?>",
data : formData,
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
e.preventDefault();
});
});
</script>
I'm trying to submit a form with jquery from plugin With multiple submits, but i can't get the value from the $_POST['aggInf'] in php, i can get it in js.
My form:
<form action="#" method="post" id="gestioneProfilo">
My inputs:
<input name="aggInf" type="submit" value="Upload" class="upload">
<input name="aggInfAnn" type="submit" value="Annulla" id="cancel">
If i try onsubmit='alert($(this).serialize()); return false;' on the from i always get this in return:
On the js side i used this solution and it works fine, if i try a console.log() command i get the correct value.
If i try a var_dump() command i only get all the other input and textboxes values. How do i fix this?
Full form html:
<form action="#" method="post" id="gestioneProfilo">
<!-- Scelta avatar -->
<div id="sceltaAvatar">
<!-- Profilo -->
<div id="perAvatar">
<h1>Scelta dell'Avatar</h1>
<p>Carica dal tuo pc o dal web una tua immagine di profilo</p>
<!-- <input type="hidden" name="immP"> -->
</div>
<!-- Copertina -->
<div id="perCopertina">
<h1>Scelta della copertina</h1>
<p>Carica dal tuo pc o dal web una tua immagine di copertina</p>
<!-- <input type="hidden" name="immC"> -->
</div>
<!-- Info generali -->
<div id="altreInfo">
<div>
<!-- informazioni -->
<h1>Informazioni</h1>
<textarea placeholder="Cosa fai nella vita? Scrivi una breve descrizione su di te" name="bio" id="bio"><?php get_stuff('bio', TRUE, TRUE) ?></textarea>
</div>
<div id="due">
<div>
<!-- Sito -->
<h1>Sito</h1>
<textarea placeholder="Il tuo sito" name="sito" id="sito"><?php get_stuff('sito', TRUE, TRUE) ?></textarea>
</div>
<div>
<!-- Posizione -->
<h1>Posizione</h1>
<textarea placeholder="Da dove vieni?" name="pos" id="pos"><?php get_stuff('pos', TRUE, TRUE) ?></textarea>
</div>
</div>
</div>
<!-- Torna indietro -->
<input name="aggInf" type="submit" value="Upload" class="upload">
<input name="aggInfAnn" type="submit" value="Annulla" id="cancel">
</div>
</form>
<?php include_once 'lightbox.php' ?>
js:
$('#gestioneProfilo').submit(function(e) {
e.preventDefault();
var
val = $("input[type=submit][clicked=true]").val(),
pop = $(this);
console.log(val);
// it works, if i press upload it prints upload, if i press annulla it prints annulla
if (val == "Upload") {
$(this).ajaxSubmit({
type: 'POST',
url: "lib/ajax.php",
dataType: "json",
data: pop.serialize(),
success: function(data){
//stuff
}
});
}else{
cambiaA("#perCommentare", "#gestioneProfilo", "ritorna");
};
});
$(document).on('click', '#gestioneProfilo input[type=submit]', function() {
$("input[type=submit]",
$(this).parents("#gestioneProfilo")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
php:
if (isset($_POST['aggInf'])) {
update_info();
$return_data['immP'] = get_stuff('immP');
$return_data['immC'] = get_stuff('immC');
$return_data['bio'] = get_stuff('bio');
$return_data['sito'] = get_stuff('sito', FALSE, TRUE);
$return_data['pos'] = get_stuff('pos');
echo json_encode($return_data);
exit;
}
I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
TL; DR Solution: change .val in the javascript to .serialize for any radio inputs.
I've been using this tutorial to build a form that, when the submit button is pressed, fades out the button and fades in a "thanks" message and sends the mailer.php in the background. My form has radio buttons and I cannot seem to figure out how to get the javascript to send which button was selected through to my email.
Here's the form html:
<form action="" method="" name="rsvp" id="rsvp-form">
<fieldset>
<legend>RSVP</legend>
<ol>
<li>
<input id="accepts1" class="rsvps" name="rsvps" type="radio" value="Graciously_Accepts" />
<label for="accepts1">Graciously Accepts</label>
</li>
<li>
<input id="declines1" class="rsvps" name="rsvps" type="radio" value="Regretfully_Declines" />
<label for="declines1">Regretfully Declines</label>
</li>
<li>
<input id="accepts2" class="rsvps" name="rsvps" type="radio" value="Regretfully_Accepts" />
<label for="accepts2">Regretfully Accepts</label>
</li>
<li>
<input id="declines2" class="rsvps" name="rsvps" type="radio" value="Graciously_Declines" />
<label for="declines2">Graciously Declines</label>
</li>
</ol>
</fieldset>
<div id="rsvp-wrapper">
<fieldset>
<button class="button" type="submit" value="send">RSVP!</button>
</fieldset>
</form>
<div class="success"></div>
</div>
The javascript:
<script type="text/javascript">
$(function() {
$(".button").click(function() {
var rsvps = $(".rsvps").val();
var dataString = 'rsvps=' + rsvps;
$.ajax({
type: "POST",
url: "rsvp-mailer.php",
data: dataString,
success: function() {
$('#rsvp-wrapper').html("<div class='success'></div>");
$('.success').html("<p class='italic'>Thanks!</p>")
.hide()
.fadeIn(500, function() {
$('.success');
});
}
});
return false;
});
});
</script>
And the mailer.php:
<?php
$rsvps = $_POST['rsvps'];
$formcontent="
RSVP: $rsvps \n";
$recipient = "myemail#domain.com";
$subject = "RSVP";
$mailheader = "RSVP \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
?>
Thank you so much for any insight you can provide.
Give this a try. See jQuery.post() for more info.
<script type="text/javascript">
$('form').submit(function() {
var data = $(this).serialize();
$.post("rsvp-mailer.php", data, function() {
$('#rsvp-wrapper').html("<div class='success'></div>");
$('.success').html("<p class='italic'>Thanks!</p>")
.hide()
.fadeIn(500, function() {
$('.success');
});
}
return false;
}
</script>
Rather than accessing the radio button via a class selector, try the following:
var rsvps = $('input[name=rsvps]:radio').val();
You don't need javascript to get the values in order for them to be sent to the email. Use PHP instead.
$formcontent .= $_POST['rsvp'];
That line will added before $recipient should send the value of the radio buttons.
change var rsvps = $(".rsvps").val(); to var rsvps = $(".rsvps[selected=selected]").val();
Also, dataString needs to be a json object like this var dataString = { rsvps : rsvps }; to be accessible via ajax POST.
I've got this form that updates user information on db. However, this functionality is not working with ajax (works with a simple submit with refresh).
This postes form serialized data to the server
jQuery
$('#commit-changes').click(function(){
$('#validation').submit(function(){
$.ajax({
type: "POST",
data: $("#validation").serialize(),
cache: false,
url:"modules/user/updateuser.php",
success : function(data){
$("#response-update").html(data);
},
error:function(){
alert("ERROR");
}
});
});
});
Here's the HTML that outputs the markup
HTML
$rcs_roles = $user->getRoles();
$role ='';
foreach($rcs_roles as $roles)
{
if($roles->role_number == $rcs_user->permissao)
$role .= '<option value="'.$roles->role_number.'" selected="selected">'.$roles->role.'</option>';
else
$role.= '<option value="'.$roles->role_number.'">'.$roles->role.'</option>';
}
if($rcs_user->activo == 0)
{
$activo = '<input type="checkbox" name="activo" class="on_off_checkbox" value="1" />';
}
else
{
$activo = '<input type="checkbox" name="activo" class="on_off_checkbox" checked="checked" value="1" />';
}
$response = '';
$response.='<form id="validation" action="" method="post">
<fieldset >
<input type="hidden" name="user_id"
value="'.$_POST['user_id'].'"/>
<legend>Actualizar Dados Utilizador</legend>
<div class="section ">
<label>Nome<small>Insira o seu nome</small></label>
<div>
<input type="text" class="validate[required,custom[onlyLetterSp]] large" name="nome" id="f_required" value="'.utf8_encode($rcs_user->nome).'">
</div>
</div>';
$response.='<div class="section ">
<label> Email<small>Insira o seu email</small></label>
<div>
<input type="text" class="validate[required,custom[email]] large" name="email" id="e_required" value="'. utf8_encode($rcs_user->email).'">
</div>
</div>';
$response.= '<div class="section">
<label>Permissões<small>Seleccione o tipo de utilizador </small></label>
<div>
<select class="medium" name="role">
'.$role.'
</select>
</div>
</div>
<div class="section">
<label>Activo<small>Activar utilizador</small></label>
<div>
'.$activo.'
<span class="f_help">ON / OFF </span>
</div>
</div>
<div class="section last">
<div>
<a id="commit-changes" class="uibutton submit_form" name="submit" >Gravar</a><a class="uibutton special" onClick="ResetForm()" title="Limpar Formulário" >Limpar Formulário</a>
</div>
</div>
</fieldset></form>';
And then the server side processing
PHP
$response='';
$id_user = $_POST['user_id'];
$name = utf8_encode($_POST['nome']);
$email = utf8_encode($_POST['email']);
$permitions = $_POST['role'];
if(!isset($_POST['activo']))
{
$active = 0;
}
else
{
$active = 1;
}
$user = new Users();
try
{
$user->updateUsers($name, $email, $permitions, $active, $id_user);
$response = "SUCESSO";
}
catch (Exception $e)
{
$response = "ERRO".$e->getMessage();
}
echo $response;
Glad for all the help I can get
From an initial glance, it looks like you aren't waiting until the document has loaded before binding an event handler. This means that #commit-changes doesn't even exist when you try to add the .click event handler.
To fix this in jQuery, wrap this around your entire code:
$(document).ready(function(){
// do stuff
});
This function sends a callback to jQuery's document.ready handler, so that all the code only executes once the page is loaded.
Remove the .submit() function. something like this.
$.post("modules/user/updateuser.php",{data:$("#validation").serialize()},function(response){
$("#response-update").html(response);
});
on the php side try to print_r($_POST['data']); and please post the output.
In the updateUsers function (in Users class) you try to update the field nome or name ?
You are suppose to use nome only right?