my problem is that when I click send this not entering the sendmail () function , should show alert, the ajax is the admin- ajax.php is good Request URL:http://localhost:8888/password/wp-admin/admin-ajax.php
Request Method:POST
Status Code:200 OK
HTML FORM:
<div class="form">
<form action="" method="POST" id="ContactForm" enctype="application/x-www-form-urlencoded" novalidate="novalidate" >
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="celular" placeholder="Celular o Teléfono">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="message" placeholder="Your Message *" style="height:175px;"></textarea>
</div>
<div id="loading_icon"><img src='<?php echo get_template_directory_uri(). '/images/loading_spinner.gif'; ?>' alt="loading" style="display: none;"></div>
<input class="btn btn-default" type="submit" name="submit" value="Enviar">
<div id="#response"></div>
</form>
</div>
ajax:
jQuery(document).ready(function($){
$("#ContactForm").validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
celular: "required"
},
messages: {
name: "Por favor digite su nombre",
email: {
required: "Por favor digite su correo",
email: "Porfavor ingrese un email valido"
},
message: "Ingrese el asunto en el que le podemos ayudar",
celular: "Digite su numero de celular o telefono"
},
submitHandler: function(form) {
$('#loading_icon').show();
$('#click').hide();
var params = $(form).serialize();
$.ajax ({
type: 'POST',
url: ajaxurl,
data: params + '&action=sendmail',
success: function(response) {
$('#response').hide();
$('#response').html(response);
$('#response').fadeIn('slow');
$('#loading_icon').hide();
}
});
}
});
});
PHP:
<?php
/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/
function frontend_custom_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','frontend_custom_ajaxurl');
add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
function sendmail() {
echo '<script language="javascript">alert("se envió!!");</script>';
}
?>
You cannot run javascript function in the ajax file .. instead run the desired php code in ajaxfile
<?php
add_action('wp_ajax_sendmail', 'sendmail');
add_action('wp_ajax_nopriv_sendmail', 'sendmail');
function sendmail() {
echo 'alert_me';
die;
}
?>
Then is the response you can perform the alerting functionality
submitHandler: function(form) {
$('#loading_icon').show();
$('#click').hide();
var params = $(form).serialize();
$.ajax ({
type: 'POST',
url: ajaxurl,
data: params + '&action=sendmail',
success: function(response) {
$('#response').hide();
$('#response').html(response);
$('#response').fadeIn('slow');
$('#loading_icon').hide();
if(reponse == 'alert_me'){
alert('Alert your required string');
}
}
});
}
I'm not sure what you're trying to accomplish with creating a JS snippet inside PHP.
Hit the admin-ajax route directly in the url. Put your payload in data and the endpoint you want to hit in params: {'action': 'your_endpoint_here'}
$.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
data: data,
params: {'action': 'my_endpoint'}
}).success(function (data) {
// do stuff with response data
}
}).error(function (data) {
// do stuff with error response data
}
});
Your PHP would look like this
add_action('wp_ajax_nopriv_my_endpoint', array($this, 'myMailFunction'));
add_action('wp_ajax_my_endpoint', array($this, 'myMailFunction'));
public function myMailFunction()
{
//send mail here
}
Related
good afternoon
I have a problem, I am trying to save the data values from the form in the database.
AJAX is used to send the data using the POST method but when evaluating the outputs from the .done and .fail functions, they return no information.
This is the html
<div class="form">
<h1>Ingreso Alumno-Trabajo</h1>
<form name="formulario_contacto" id="formdata">
<p>
<label for="cest">cedula estudiante</label>
<input type="number" id="cest" name="cest" autofocus required>
</p>
<p>
<label for="nest">nombre estudiante</label>
<input type="text" id="nest" name="nest" required>
</p>
<p>
<label for="aest">Apellido estudiante</label>
<input type="text" id="aest" name="aest" required>
</p>
<p class="full-width">
<label for="tit">Titulo</label>
<textarea name="" id="tit" cols="30" rows="3" name="tit" required></textarea>
</p>
<p>
<label for="nase">nombre asesor</label>
<input type="text" id="nase" name="nase" required>
</p>
<p>
<label for="fsede">Sede :</label>
<select id="fSede" name="fSede">
<option value="Montalban">Montalban</option>
<option value="Guyana">Guayana</option>
<option value="Virtual">Virtual</option>
</select>
</p>
<p class="full-width button">
<input type="submit" value="Ingresar">
<input type="reset" value="Restaurar">
</p>
</form>
</div>
<div id="mensaje">
<h3></h3>
</div>
This is the JS using AJAX
<pre>
$(document).ready(function () {
// This part of the code will automatically execute when doc is ready.
$("#mensaje").html("");
$("input:submit").click(function () {
// We set the default action to be made once we submit.
// Let's validate the form first
if (validaForm()) {
var formulario = $("#formdata").serializeArray();
$.ajax({
// url: "php/enviar.php",
// type: "POST",
type: "POST",
url: "php/enviar.php",
dataType: "json",
data: formulario,
})
//do something when get response })
.done(function (respuesta) {
//do something when any erro
$("#mensaje").html(respuesta.mensaje);
alert("coño de la madre");
})
.fail(function (respuesta) {
//do something when any erro
alert("coño de la madre falla" + respuesta);
});
} else {
// We show this when the validation fails
$("#mensaje").html("falta Ingresar la data");
}
});
$("input:reset").click(function () {
$("#mensaje").html("");
});
});
</pre>
This is the PHP
<?php
echo "Estoy entrando aqui"; #I'm entering here
if(isset($_POST["cest"]))
{
$cedula = $_POST["cest"];
$nombre = $_POST["nest"];
$apellido = $_POST["aest"];
$titulo = $_POST["tit"];
$nomase = $_POST["nase"];
$sede = $_POST["fsede"];
$inserta = "INSERT INTO tbl-est-teg (cedula,nombre, apellido, titulo, nomase, sede) VALUES ('$cedula','$nombre','$apellido','$titulo','$nomase','$sede')";
$conexion = new mysqli("localhost","yguer2","s&4gBz6nPrA8*S7","estudiante-trabajo",3306);
$respuesta = new stdClass();
if($conexion->query($inserta)){
$respuesta->mensaje = "Se guardo correctamente";
}
else {
$respuesta->mensaje = "Ocurrió un error";
}
echo json_encode($respuesta);
}
?>
<script>
$(document).ready(function () {
// This part of the code will automatically execute when doc is ready.
$("#mensaje").html("");
$("#formdata").on("submit",function () {
// We set the default action to be made once we submit.
// Let's validate the form first
if (validaForm()) {
var formulario = $("#formdata").serializeArray();
$.ajax({
// url: "php/enviar.php",
// type: "POST",
type: "POST",
url: "php/enviar.php",
dataType: "json",
data: formulario,
}).done(function (respuesta) {
//do something when any erro
$("#mensaje").html(respuesta.mensaje);
alert("coño de la madre");
}).fail(function (respuesta) {
//do something when any erro
alert("coño de la madre falla" + respuesta);
});
} else {
// We show this when the validation fails
$("#mensaje").html("falta Ingresar la data");
}
});
$("input:reset").click(function () {
$("#mensaje").html("");
});
});
</script>
You could try by just doing that but as some people have told you in the comments, there are some serious vulnerability issues in your PHP file, but I guess you should solve this first,
Use the console, if you're using chrome you could just press F12,
There are several things to be asked, I'm guessing your validaForm() function is working well
If you have more questions please edit the original questions so we can help.
Post this in the Spanish version of this site and I could help you there too, just let me know.
Publica esto en el sitio en Español y te puedo ayudar allí, solo deja un comentario con el link a la pregunta.
I keep getting two emails when i sent the form, also it keep getting " Error when sending the message" even after I send and receive the email.. I would also like to display the error message if the fields are empty
<?php
#if you also need this script to respond to other domains, add those header lines
// header("Access-Control-Allow-Origin: *");
// header("Access-Control-Allow-Methods: GET, POST");
// header("Access-Control-Allow-Headers: *");
if($_POST) {
$userEmail=$_POST['userEmail'];
$subject=$_POST['subject'];
//$destEmail=$_POST['destEmail'];
$body=$_POST['textarea'];
$response = mail("email#yahoo.com", $subject, $body, "From:" . $userEmail);
echo $response;
exit();
}
?>
<form >
<div data-role="fieldcontain">
<label for="subject">Subject:</label>
<input name="subject" id="Subject_input" value="" type="text">
</div>
<div data-role="fieldcontain">
<label for="email">Email:</label>
<input name="email" id="Email_input" value="" type="email">
</div>
<div data-role="fieldcontain">
<label for="textarea">
Qusstions/Feedback:
</label>
<textarea cols="40" rows="8" name="textarea" id="MessageText_input"></textarea>
</div>
<input type="button" id="sendlink" class="reset" value="submit contact"/>
</form>
<script>
$('#sendlink').on("vclick", function(e) {
"use strict";
e.preventDefault();
var data={
userEmail: $('#Email_input').val(),
subject: $('#Subject_input').val(),
textarea: $('#MessageText_input').val()
};
function sendToServer() {
return $.ajax({
url: 'yates-contact-form-app.php',
type: "POST",
dataType: "xml",
data: data
});
}
//sendToServer().done(handleSuccess);
//sendToServer().fail(handleError);
sendToServer().done(function() {
alert("Message successfully sent");
$(".reset").closest('form').find("input[type=text],input[type=email],textarea").val("");
$.mobile.navigate("#benefits-facts");
});
sendToServer().fail(function() {
alert(" Error when sending the message");
/*console.log("Error when sending the message : ");
console.log(data);
console.log(data.response);
console.log(textStatus);
console.log(jqXHR);*/
});
});
</script>
The problem is you are calling sendToServer 2 times, 1 for the done handler another for the fail handler so you are getting the mail 2 times.
Instead you need to register both these handlers to the same promise like
$('#sendlink').on("vclick", function (e) {
"use strict";
e.preventDefault();
var data = {
userEmail: $('#Email_input').val(),
subject: $('#Subject_input').val(),
textarea: $('#MessageText_input').val()
};
//validation
if (!data.userEmail || !data.subject || !data.textarea) {
alert('enter the data!!!')
return;
}
function sendToServer() {
return $.ajax({
url: 'yates-contact-form-app.php',
type: "POST",
dataType: "xml",
data: data
});
}
var req = sendToServer();
req.done(function () {
//do your stuff
});
req.fail(function () {
//do your stuff
});
//or you can just chain both these calls
});
The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response
So i start in page A (form) and after submit moves to page B (insert)giving me the json response.
I'm having a problem getting the response of the following php into ajax
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));
This is my ajax
$.ajax({
url: 'nova_formacaoBD.php',
dataType: 'json',
data: data,
success: function(data) {
$('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
if(data.status == "success"){
$('#ajaxDivOk').append(data.message);
}
}
});
And this is my form
<form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">
UPDATE
The data is all the input fields in the form
Seven strings and upload of one file
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">Escola: </label>
<select class="form-control" id="escola" name="escola" onchange="verificaEscola()">
<?php echo $escolaOptions; ?>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Nome Formação: </label>
<input class="form-control" id="form" name="form" onchange="verificaNome()">
</input>
<div class="form-group">
<label for="exampleInputEmail1">Data de Início: </label><input type="text" class="form-control" id="data" name="data" onchange="verificaData()" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">Horas: </label><input type="text" class="form-control" id="horas" name="horas" onchange="verificaHoras()">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Local: </label>
<input class="form-control" id="local" name="local" onchange="verificaLocal()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Destinatários: </label>
<input class="form-control" id="dest" name="dest" onchange="verificaDest()">
</input>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Data Limite: </label><input type="text" class="form-control" id="datas" name="datas" onchange="verificaDataLimite()"/>
</div>
<div class="form-group">
<label for="exampleInputFile">Programa da Formação</label>
<input type="file" name="fileToUpload" id="fileToUpload" name="fileToUpload">
</div>
<button type="submit" class="btn btn-default" onclick="return checkBoxes(this)">Registar</button>
</form>
This is my form complete
UPDATE 2 (now it works but i have a warning in my console
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
and the beforeSend funtion doesn't work
I don't see the div "Wait while updating the file)
Js code
<script type="text/javascript">
$(document).ready(function () {
$("#formacao").submit(function (event) {
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend: function(data){
$('#ajaxDivAlert').html('A carregar o ficheiro...aguarde por favor')
},
success: function (data) {
var result = data.status;
console.log(result);
if(result == 'success'){
$('#ajaxDivAlert').empty();
$('#ajaxDivOk').html('Informação: ' + data.message);
$("#ajaxDivOk").fadeIn();
$("#ajaxDivOk").fadeOut(5000);
}
},
error: function(){
$("#ajaxDivErro").html('Esta formação já está registada na base de dados');
$("#ajaxDivErro").fadeIn();
$("#ajaxDivErro").fadeOut(5000);
}
});
return false;
});
});
</script>
So, i just need to put info to complete the code, the rest is working
You have some changes to do :
Html : Remove the action="nova_formacaoBD.php" like that :
<form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
Then I suppose that you have a ajax called like that :
UPDATE
$(document).ready(function () {
$("#formacao").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var ajaxDivAlert = $('#ajaxDivAlert');
$.ajax({
url: 'nova_formacaoBD.php',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
ajaxDivAlert.empty().html('A carregar o ficheiro...aguarde por favor')
}
}).done(function (data) {
var result = data.status;
if (result == 'success'){
ajaxDivAlert.empty().fadeIn().html('Informação: ' + data.message).fadeOut(5000);
}
}).fail(function () {
ajaxDivAlert.empty().fadeIn().html('Esta formação já está registada na base de dados').fadeOut(5000);
});
});
});
You had the error XMLHttpRequest because you put async: false. I removed it because since jQuery 1.8, the use of async: false with jqXHR ($ .Deferred) is deprecated
Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});
I'm using the jquery validator plugin, and I'm trying to make my first attempt with AJAX to it.
Right now, I have the following HTML code:
<div class="grid_12" id="info">
</div>
<div class="grid_12">
<div class="block-border">
<div class="block-header">
<h1>Inserir nova página</h1><span></span>
</div>
<form id="formulario" class="block-content form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="_100">
<p><label for="textfield">Nome da página</label><input id="page_name" name="textfield" class="required text" type="text" value="" /></p>
</div>
<div class="_100">
<p><label for="textarea">Conteúdo da página</label><textarea id="page_content" name="textarea" class="required uniform" rows="5" cols="40"></textarea></p>
</div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-validate-form" href="javascript:void(0);">Limpar</a></li>
</ul>
<ul class="actions-right">
<li><input type="submit" class="button" name="send" value="Inserir"></li>
</ul>
</div>
And my JS code:
<script type="text/javascript">
$().ready(function() {
/*
* Form Validation
*/
$.validator.setDefaults({
submitHandler: function(e) {
$.jGrowl("Ação executada com sucesso.", { theme: 'success' });
$(e).parent().parent().fadeOut();
/*
* Ajax
*/
var mypostrequest=new ajaxRequest();
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("info").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request")
}
}
}
var page_name=encodeURIComponent(document.getElementById("page_name").value);
var page_content=encodeURIComponent(document.getElementById("page_content").value);
var parameters="page_name="+page_name+"&page_content="+page_content;
mypostrequest.open("POST", "ajax/inserir_utilizador.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
v.resetForm();
v2.resetForm();
v3.resetForm();
return false;
}
});
var v = $("#create-user-form").validate();
jQuery("#reset").click(function() { v.resetForm(); $.jGrowl("User was not created!", { theme: 'error' }); });
var v2 = $("#write-message-form").validate();
jQuery("#reset2").click(function() { v2.resetForm(); $.jGrowl("Message was not sent.", { theme: 'error' }); });
var v3 = $("#create-folder-form").validate();
jQuery("#reset3").click(function() { v3.resetForm(); $.jGrowl("Folder was not created!", { theme: 'error' }); });
var formulario = $("#formulario").validate();
jQuery("#reset-validate-form").click(function() { formulario.resetForm(); $.jGrowl("O formulário foi limpo!", { theme: 'information' }); });
});
I have a div #info without anything in it that I'm trying to put there the result of the ajax.
My ajax file is just trying to echo the POST values:
<?php
$page_name=$_POST["page_name"];
$page_content=$_POST["page_content"];
echo $page_name."<br />";
echo $page_content;
?>
But it really doesn't work. It really doesn't do anything, or if it does, it refreshes the page.
What am I missing?
Regards and thanks!
I recommend you to use $.ajax() or $.post().
It's much easier and your headache will surely go away.
$.ajax({
type: 'POST',
url: 'url to post',
data: data,
success: function(data, status) {
//callback for success
},
error: error, //callback for failure
dataType: "json" //or "html" etc
});
many examples here:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.ajax/