I am really beginning in PHP/AJAX/Jquery. And I tried the hunijkah's code from this page Replacing HTML form with success message after submit, form sends mail using separate php file and the PHP file gave back: {"success":true,"errors":[]}
on a blank page replacing the current page. And I received emails. So I assume that contact.php works.
I wonder how to get back 'success' in my HTML file and write an answer below the form in my current page after the successful operation.
Here the form, I used:
<form action="contact.php" method="post" id="mail_form">
<fieldset>
<legend>Coordonnées personnelles :</legend>
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Prénom *" required name="firstname" maxlength="50"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Nom *" required name="lastname" maxlength="50"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="email" placeholder="Email *" required name="email"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="tel" placeholder="+681 12 34 56 *" required name="usrtel"></p>
</fieldset>
<fieldset>
<legend>Informations :</legend>
<p><input class="w3-input w3-padding-16 w3-border" type="number" placeholder="Combien de personne(s) *" required name="people" min="1" max="100"></p>
<p><input class="w3-input w3-padding-16 w3-border" type="text" placeholder="Message \ Besoins particuliers *" required name="message"></p>
</fieldset>
<p>* Champs obligatoires</p>
<br>
<div class="g-recaptcha" data-theme="dark" data-sitekey="6LdMKTcUAAAAABNdlU76EOu6W3Wv61T7uKGM9HwB"></div>
<p>Souhaitez-vous une copie de votre message ?
<input type="radio" id="rep_oui" name="copie" value="oui" checked><label for="rep_oui">Oui</label>
<input type="radio" id="rep_non" name="copie" value="non"><label for="rep_non">Non</label></p>
<p id="error" class="w3-red w3-xlarge w3-center"></p>
<p><button class="w3-button w3-light-grey w3-block" type="submit" name="submit">ENVOYER LE MESSAGE</button></p>
<p><button class="w3-button w3-light-grey w3-block" type="reset">EFFACER</button></p>
</form>
In HTML file, I put this script between the head tags :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> // 2.1.3 -> 3.2.1
And this script at the bottom of my file:
<script>
$('#mail_form').on('submit', function(event)
{
event.preventDefault();
var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
$.post( "./contact.php" , dataIn )
.done(function( dataOut )
{
//dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
var finalArray = JASON.parse ( dataOut );
if ((finalArray['success'] == true) && (finalArray['error1'] == false) && (finalArray['error2'] == false))//Check if it was successfull.
{
$("#mail_form").html("<p class='w3-xxlarge w3-center w3-tag'><strong>Votre message a bien été envoyé !</strong></p>");
}
else //there were errors
{
if (finalArray['error1'] == true)
{
// message not sent
$('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît.</strong></p>");
}
else if (finalArray['error2'] == true)
{
// one of 7 variables (at least) is empty ...
$('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur.</strong></p>");
}
else
{
// recaptcha is false
$('#error').html("<p class='w3-xxlarge w3-center w3-tag'><strong>Problème d'authentification par le Recaptcha</strong></p>");
};
};
});
return false; //Make sure you do this or it will submit the form and redirect
});
</script>
I can't see my mistake(s). It's exactly the same code and I wonder what's wrong. Maybe someone can help me because after dayS I've hit a brick wall. Can I use a test in the HTML file to be sure that success variable is passed by the PHP file ?
PS : PHP file
<?php
$success = true;
$error1 = false;
$error2 = false;
// ReCAPTCHA
// grab recaptcha library
require_once "recaptchalib.php";
// foreach ($_POST as $key => $value) {
// echo '<p><strong>' . $key.':</strong> '.$value.'</p>';
// }
// your secret key
$secret = "***_***";
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
/*
********************************************************************************************
CONFIGURATION
********************************************************************************************
*/
// destinataire est votre adresse mail. Pour envoyer à plusieurs à la fois, séparez-les par une virgule
$destinataire = '***@***.**,***@***.**';
// copie ? (envoie une copie au visiteur)
// $copie = 'oui';
// objet du message
$objet = 'Contact depuis le site ***';
// Action du formulaire (si votre page a des paramètres dans l'URL)
// si cette page est index.php?page=contact alors mettez index.php?page=contact
// sinon, laissez vide
$form_action = '';
/*
********************************************************************************************
FIN DE LA CONFIGURATION
********************************************************************************************
*/
/*
* cette fonction sert à nettoyer et enregistrer un texte
*/
function Rec($text)
{
$text = htmlspecialchars(trim($text), ENT_QUOTES);
if (1 === get_magic_quotes_gpc())
{
$text = stripslashes($text);
}
$text = nl2br($text);
return $text;
};
/*
* Cette fonction sert à vérifier la syntaxe d'un email
*/
function IsEmail($email)
{
$value = preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $email);
return (($value === 0) || ($value === false)) ? false : true;
}
// formulaire envoyé, on récupère tous les champs.
$firstnameint = (isset($_POST['firstname'])) ? Rec($_POST['firstname']) : '';
$lastnameint = (isset($_POST['lastname'])) ? Rec($_POST['lastname']) : '';
$email = (isset($_POST['email'])) ? Rec($_POST['email']) : '';
$usrtelint = (isset($_POST['usrtel'])) ? Rec($_POST['usrtel']) : '';
$people = (isset($_POST['people'])) ? Rec($_POST['people']) : '';
$messageint = (isset($_POST['message'])) ? Rec($_POST['message']) : '';
$copieint = (isset($_POST['copie'])) ? Rec($_POST['copie']) : '';
// traitement du numéro de téléphone et aux variables
$firstname = htmlspecialchars($firstnameint);
$lastname = htmlspecialchars($lastnameint);
$usrtel = htmlspecialchars($usrtelint);
$message = htmlspecialchars($messageint);
$copie = htmlspecialchars($copieint);
// traitement du nombre de convives
$people = sprintf("%d",$_POST['people']); // ici le nombre sera un entier
$people = abs($people); // $people sera positif ou nul = valeur absolue (évite les âges négatifs !)
$people = intval($people); // renvoie aussi une valeur entière
if (is_numeric($people)) // n'effectue que si $people est numérique
{
} else {
$people='0';
}
if ($people >= 1 && $people <= 100) // n'effectue que si $usrtel est borné
{
} else {
$people='0';
}
// On va vérifier les variables et l'email ...
$email = (IsEmail($email)) ? $email : ''; // soit l'email est vide si erroné, soit il vaut l'email entré
if (isset($_POST['submit']))
{
if ($response != null && $response->success)
{
if (($firstname != '') && ($lastname != '') && ($email != '') && ($usrtel != '') && ($people != '') && ($message != '') && ($copie != ''))
{
// les 6 variables sont remplies, on génère puis envoie le mail
$headers = 'MIME-Version: 1.0' . "
";
$headers .= 'From:'.$firstname.' '.$lastname.' <'.$email.'>' . "
" .
$headers .= 'Reply-To:'.$email. "
" .
$headers .= 'Content-Type: text/html; charset="utf-8"; DelSp="Yes"; format=flowed '."
" .
$headers .= 'X-Mailer:PHP/'.phpversion().
$headers .= 'Content-Transfer-Encoding: 7bit'."
" ;
// envoyer une copie au visiteur ?
if ($copie == 'oui')
{
$cible = $destinataire.';'.$email;
}
else
{
$cible = $destinataire;
};
// Remplacement de certains caractères spéciaux
$message = str_replace("'","'",$message);
$message = str_replace("’","'",$message);
$message = str_replace(""",'"',$message);
$message = str_replace('<br>','',$message);
$message = str_replace('<br />','',$message);
$message = str_replace("<","<",$message);
$message = str_replace(">",">",$message);
$message = str_replace("&","&",$message);
// formatage du corps de l'email
$msg = '<div style="width: 100%; text-align: left; color: #00002b; font-weight: bold"> Message de '.$firstname.' '.
$lastname.'<br />E-mail : '.$email.' et numéro de téléphone : '.$usrtel.'<br /> nombre de personne(s) : '.$people.
'<br /> Message : '.$message.'</div>';
// Envoi du mail
$num_emails = 0;
$tmp = explode(';', $cible);
foreach($tmp as $email_destinataire)
{
if (mail($email_destinataire, $objet, $msg, $headers))
$num_emails++;
}
if ((($copie == 'oui') && ($num_emails == 2)) || (($copie == 'non') && ($num_emails == 1)))
{
// message sent
// Votre message a bien été envoyé !
}
else
{
// message not sent
// L'envoi du mail a échoué, veuillez réessayer, s'il vous plaît
$error1 = true;
};
}
else
{
// one of 7 variables (at least) is empty ...
// Vérifiez que tous les champs soient bien remplis et que l'email soit sans erreur
$error2 = true;
};
}
else
{
// recaptcha is false
// Problème d'authentification par le Recaptcha
$success = false;
};
}; // fin du if (!isset($_POST['envoi']))
$array['success'] = $success;
$array['error1'] = $error1;
$array['error2'] = $error2;
$finalArray=json_encode($array);
echo $finalArray;
?>
The code you wrote is missing a ) bracket....and you must see in console.log in browser what return after JSON.parse...i attach the code with the missing bracket. PS:For Jquery, now it's on 3.2 version...i suggest to upgrade at the current version instead that continue to use version 2, but this doesn't affect your code.
$('#mail_form').on('submit', function()
{
var dataIn = $(this).serialize(); //serialize turns the form data into a string that can be passed to contact.php. Try doing alert(dataIn); to see what it holds.
$.post("./contact.php", dataIn )
.done(function( dataOut )
{
//dataOut holds the response from contact.php. The response would be any html mail.php outputs. I typically echo out json encoded arrays as responses that you can parse here in the jQuery.
var myArray = JSON.parse(dataOut);
console.log(myArray);
if (myArray['success'] == true) //Check if it was successfull.
{
$("#mail_form").html("Congrats! We just e-mailed you!");
}
else //there were errors
{
$('#error').html(""); //Clear error span
$.each(myArray['errors'], function(i)
{
$('#error').append(myArray['errors'][i] + "<br>");
});//------->HERE WAS MISSING A );
};
});
return false; //Make sure you do this or it will submit the form and redirect
});
Hy Falakiko i answer you here because i put an example, your error it's probabily a wrong codification of the json array that php send to client javascript i write what i usually do to manage json data, inside a fecth of a query i insert a "contatore"(1,2,3,etc...) and stored rows inside an array $risultatiArray[] = array(.....) out of the loop i defined the array response json with the respective KEYS success, the key records and the key totaleRisultati that is the total contatore..after json_encode response...add also /n /r replaced with space but can be ininfluent.
while ($sql->fetch()){
++$contatore;
$risultatiArray[] = array('recid' => trim($contatore),
'rowid' => $id,
'utente' => trim($Utente),
'mese' => trim($Mese),
'orePermesso' => trim($OrePermesso));
}
$response['status'] = 'success';
$response['records'] = $risultatiArray;
$response['totaleRisultati'] = $contatore;
$response = json_encode($response);
$response = str_replace("
", "", $response);
$response = str_replace("", "", $response);
print $response;
And the json looks like this:
{"status":"success","records":[{"recid":"1","rowid":9,"utente":"Andrea","mese":"Aprile","orePermesso":"8"},{"recid":"2","rowid":8,"utente":"andrea","mese":"Gennaio","orePermesso":"8"}],"totaleRisultati":2}
So your code using success and error like an array, because i suppose from your code that errors is an array($.each(myArray['errors'])) could be :
$arrayErrori[] = array('1'=>'error1','2'=>'error2');
$array['succes'] = true;
$array['errors'] = $arrayErrori;
$finalArray=json_encode($array);
print $finalArray;
and the json will look like this....but keep in mind that "true" could be recognize like a string, must see this on road...
{"succes":true,"errors":[{"1":"error1","2":"error2"}]}
Ok now I'VE SEEN your php your error is that you are parsing an object that was just parsed in the server side, your json is correct.The error is here:
var myArray = JSON.parse( dataOut );
the dataOut is just in json you don't need to reparse. So
var myArray = dataOut //Don't need to reparse again
an example of an ajax call and the php
$.ajax({
type: "POST",
url: "MNYLINKPHPTOCALL JSON",
dataType: "JSON",
data:{},
success:function(data){
console.log(data);
console.log(data.success);
console.log(data.errors);
console.log(data.errors[0]);
console.log(data.errors[1]);
},
error:function(data){
alert('Chiamata Fallita');
}
});
AND THE JSON FROM THE PHP
$risultatiErrors= array("prova","prova2");
$output_array['success'] = true;
$output_array['errors'] = $risultatiErrors;
$final = json_encode($output_array);//<---------yOU ARE JUST ENCODING HERE
echo $final;