Add dynamic fields in woocommerce - forms

I try to add an input on the woocommerce billing-form., i want to use Ajax to render it dynamique.
It goes something like this :
One select input with for example :
choice 1
choice 2
Ie, when selecting "choice 1" another list with radio-boxes appear with choices in correlation with previous menu.
The function works perfectly without wordpress but when we add it on WP, it doesn't work. The function is duplicated and is not working properly
I added it to wp in function.php using require_once();
Can you help us to do this.
Thanks a lot
Le Conseil Informatique

my function work with like this (form_livraison.php):
<script type='text/javascript'>
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest) // Firefox et autres
xhr = new XMLHttpRequest();
else if(window.ActiveXObject){ // Internet Explorer
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else { // XMLHttpRequest non supporté par le navigateur
alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
xhr = false;
}
return xhr;
}
/**
* Méthode qui sera appelée sur le click du bouton
*/
function go(){
var xhr = getXhr();
// On défini ce qu'on va faire quand on aura la réponse
xhr.onreadystatechange = function(){
// On ne fait quelque chose que si on a tout reçu et que le serveur est ok
if(xhr.readyState == 4 && xhr.status == 200){
leselect = xhr.responseText;
// On se sert de innerHTML pour rajouter les options a la liste
document.getElementById('horaires').innerHTML = leselect;
}
}
// Ici on va voir comment faire du post
xhr.open("POST",'http://XX/ajax_livraison.php',true);
// ne pas oublier ça pour le post
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// ne pas oublier de poster les arguments
// ici, l'id du site
sel = document.getElementById('site');
idsite = sel.options[sel.selectedIndex].value;
xhr.send("idSite="+idsite);
}
</script>
<label>Lieux du retrait :</label>
<select name='site' id='site' onchange='go()'>
<option value='-1'>Aucun</option>
<?php
$bdd = new PDO('mysql:host=XX', 'XX', 'XX'); //Connexion à la base
$req = $bdd->query('SELECT * FROM site ORDER BY ville');//Récupération des informations
while($row = $req->fetch()){
echo "<option value='".$row["id"]."'>".$row["ville"]."</option>";
}
?>
</select>
<div id='horaires'>
Horaires :<br/>
</div>
this one call this page (ajax_livraison.php)
<?php
setlocale (LC_TIME, 'fr_FR.utf8','fra'); //Mise en français de la date
echo "Horaires : <br/> Nous sommes le ".(strftime("%A %d %B"))."<br/>"; //Affichage de la date
$num_jour = date("N"); //Récupération du numéro du jour (Lundi 1 -> Dimanche 7)
if(isset($_POST["idSite"])){ //si un élément est sélectionné...
$bdd = new PDO('mysql:host=XX', 'XX', 'XX'); //Connexion à la base
//mysql_select_db("test");
//$res = mysql_query("SELECT * FROM horaires WHERE idSite=".$_POST["idSite"]); //Récupération des informations
$req = $bdd->prepare('SELECT * FROM horaires WHERE idSite = ?');
$req->execute(array($_POST['idSite']));
$resultfinal = array(); //Création d'un tableau
while($row = $req->fetch()){ //Boucle tant qu'il y a des résultats
$inter_jour = $num_jour - $row['id_jour']; //Calcul de l'intervalle entre le jour J et le jour de livraison
if ($inter_jour>=0){ //Si intervalle de livraison supérieur ou égale à 0
$compte_jour = date('d')+(7-$inter_jour); //Calcul jour livraison
}
else{
$compte_jour = date('d')-$inter_jour; //Sinon idem avant
}
$date_livraison = strftime("%A %d %B",mktime(0,0,0,date('m'),$compte_jour,date('Y'))); //Récupération de la date de livraison suite au calcul
$num_livraison = strftime("%d", mktime(0,0,0,date('m'),$compte_jour,date('Y'))); //Récupération numéro livraison suite au calcul
if((($num_jour+1) == $row["id_jour"]) && $row['idSite']==1){ //Si livraison = J+1 et site de livraison == Massy
$write = "<input type='radio' name='heures' id='".$row["id"]."' value='".$row["id"]."' checked><label for='".$row["id"]."'> ".$date_livraison." 16h00 - 20h00</label><br/>";
}
else{
$write = "<input type='radio' name='heures' id='".$row["id"]."' value='".$row["id"]."'><label for='".$row["id"]."'> ".$date_livraison." ".$row["am"]." ".$row["pm"]."</label><br/>";
}
$resultfinal[$num_livraison] = $write; //Ajout de la ligne en fin de tableau
}
ksort($resultfinal); //Trie du tableau par la clé
foreach ($resultfinal as $key => $value) { //Pour chaque ligne du tableau...
echo $value; //afficher le contenu
}
}
?>
so in function.php of wordpress i call it with require_once(form_livraison.php);
add_action( 'woocommerce_checkout_fields' , 'custom_store_pickup_field');
function custom_store_pickup_field($fields) {
require_once("form_livraison.php");
}
I hope you understand my function ^^
thanks for help

Related

upload image in PHP5

I have this code in PHP to upload images to directory. The problem is: It's not uploading .png files.
Error: Você não enviou nenhum arquivo!
I don't know how to fix, already tried a lot of changes.
<?php
//Upload de arquivos
// verifica se foi enviado um arquivo
if(isset($_FILES['arquivo']['name']) && $_FILES["arquivo"]["error"] == 0)
{
echo "Você enviou o arquivo: <strong>" . $_FILES['arquivo']['name'] . "</strong><br />";
echo "Este arquivo é do tipo: <strong>" . $_FILES['arquivo']['type'] . "</strong><br />";
echo "Temporáriamente foi salvo em: <strong>" . $_FILES['arquivo']['tmp_name'] . "</strong><br />";
echo "Seu tamanho é: <strong>" . $_FILES['arquivo']['size'] . "</strong> Bytes<br /><br />";
$arquivo_tmp = $_FILES['arquivo']['tmp_name'];
$nome = $_FILES['arquivo']['name'];
// Pega a extensao
$extensao = strrchr($nome, '.');
// Converte a extensao para mimusculo
$extensao = strtolower($extensao);
// Somente imagens, .jpg;.jpeg;.gif;.png
// Aqui eu enfilero as extesões permitidas e separo por ';'
// Isso server apenas para eu poder pesquisar dentro desta String
if(strstr('.jpg;.png;.gif;.jpeg', $extensao))
{
// Cria um nome único para esta imagem
// Evita que duplique as imagens no servidor.
$novoNome = md5(microtime()) . $extensao;
// Concatena a pasta com o nome
$destino = 'images/uploads/logos/' . $novoNome;
// tenta mover o arquivo para o destino
if( #move_uploaded_file( $arquivo_tmp, $destino ))
{
echo "Arquivo salvo com sucesso em : <strong>" . $destino . "</strong><br />";
echo '<img src="' . $destino . '" />';
echo '<META http-equiv="refresh" content="0;URL=/administracao">';
exit;
}
else
echo "Erro ao salvar o arquivo. Aparentemente você não tem permissão de escrita.<br />";
}
else
echo "Você poderá enviar apenas arquivos .jpg, .jpeg, .gif e .png.";
}
else
{
echo "Você não enviou nenhum arquivo!";
}
?>
Can someone help me please?
You are checking if the string after . matches your accepted extensions. Like I mentioned in the comment section a user can easily change their file's extension and upload it regardless of the content.
On PHP.net there is an article/comment about how to upload files, some safety issues are also explained briefly in code and solved. I think this part will do for you:
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.'); // You can replace this with a custom message if you want.
// Either that or catch it in higher level
}
Source to this code (PHP.net)
Also make sure that your errors are enabled, so you can spot any PHP mistakes:
error_reporting(E_ALL); // Report ALL errors once they occur
ini_set('display_errors', 1); // Once they get reported, print them as HTML on your page
One more suggestion, remove the error suppression # in the move_uploaded_file if statement. If anything fails, you won't see why.
So I think this saves you time, as well fixing your problem in a safe way.
Good luck.
some comments.
This path must have write permission.
$destino = 'images/uploads/logos/' . $novoNome;
Also check that your form has
enctype="multipart/form-data"

Difficulty with my form on IE

I have a website form, which works flawlessly. Except on IE 10 where it won't work at all, although strangely enough if I enable the compatibility mode, it works 90% fine.
With it on, it will submit the form and then give me an error saying there was an error (which is an internal message about the image which has not been uploaded - although the rest of the form gets uploaded).
*So, without compatibility mode on, it won't work (it will submit blank entry results without actually proceeding to the next screen).
As for with compatibility mode, it will not upload the user's image*
I assume the problem is with the process form.
<?php
include('config.php');
ini_set('error_reporting', E_ALL);
ini_set('display_errors', '1');
require_once('db.php');
$db = new db();
$cats = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['cats'])) {
$cats = implode(",", $_POST['cats']);
}
$categories = $_POST['categories'];
$str = $categories . ": " . $cats;
//echo $str;
}
$data = array();
$data[] = !empty($_POST['company']) ? $_POST['company'] : '';
$data[] = !empty($_POST['phone']) ? $_POST['phone'] : '';
$data[] = !empty($_POST['website']) ? $_POST['website'] : '';
$data[] = !empty($_POST['messagefr']) ? $_POST['messagefr'] : '';
$data[] = !empty($_POST['messageen']) ? $_POST['messageen'] : '';
$data[] = !empty($str) ? $str : '';
$data[] = !empty($_POST['profession']) ? $_POST['profession'] : '';
$data[] = !empty($_POST['manufacturiers_stand']) ? $_POST['manufacturiers_stand'] : '';
$data[] = !empty($_POST['percent_quebec']) ? $_POST['percent_quebec'] : '';
$data[] = !empty($_POST['percent_canada']) ? $_POST['percent_canada'] : '';
$data[] = !empty($_POST['percent_usa']) ? $_POST['percent_usa'] : '';
$data[] = !empty($_POST['percent_autre']) ? $_POST['percent_autre'] : '';
$data[] = !empty($_POST['bt_export']) ? $_POST['bt_export'] : '';
$data[] = !empty($_POST['bt_exporte_souhaite']) ? $_POST['bt_exporte_souhaite'] : '';
$data[] = !empty($_POST['bt_prod_verts']) ? $_POST['bt_prod_verts'] : '';
$data[] = !empty($_POST['bt_new_prod']) ? $_POST['bt_new_prod'] : '';
$data[] = !empty($_POST['name']) ? $_POST['name'] : '';
$data[] = !empty($_POST['email']) ? $_POST['email'] : '';
$data[] = !empty($_POST['resource_phone']) ? $_POST['resource_phone'] : '';
$data[] = !empty($_POST['personne_ressource']) ? $_POST['personne_ressource'] : '';
$data[] = !empty($_POST['backup_name']) ? $_POST['backup_name'] : '';
$data[] = !empty($_POST['backup_email']) ? $_POST['backup_email'] : '';
$data[] = !empty($_POST['backup_phone']) ? $_POST['backup_phone'] : '';
$result = $db->query("INSERT INTO form_corpo_test (compagnie,
telephone,
site_web,
texte_fr,
texte_en,
categories,
profil_exposant,
stands_du_manufacturier,
pourcentage_quebec,
pourcentage_canada,
pourcentage_usa,
pourcentage_autre,
exporte,
exporte_souhaite,
produits_vert,
nouveau_produits,
nom,
courriel,
telephone_ressource,
personne_ressource_c_toi,
autre_personne_ressource,
autre_courriel,
autre_telephone)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $data);
if (!$result) {
echo 'Veuillez nous contactez si vous voyez ce message';
}
$pic = ($_FILES['photo']['name']);
$pic = (mysql_real_escape_string($_FILES['photo']['name']));
$dirPath = $_POST['company'];
$dirExists = is_dir($dirPath);
if (#!dirExists)
$dirExists = mkdir($dirPath, 0755);
#$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo '<br/>' . 'Le dossier ' . $dirPath . " a été créer" . '<br/>';
} else {
echo '<br/>' . "Le dossier " . $dirPath . " n'a PAS été créer car il existe déja" . '<br/>';
}
$folder_name = $dirPath;
$folder = $folder_name . '/';
$folder = $folder . basename($_FILES['photo']['name']);
if ($_FILES["photo"]["size"] >= 10485760) {
echo "F2";
die();
}
if (move_uploaded_file($_FILES['photo']['tmp_name'], $folder)) {
echo '<br/>' . "Le fichier " . basename($_FILES['photo']['name']) . " a été téléchargé" . '<br/>' . '<br/>' . "Et nous avons bien recu votre formulaire!" . '<br/>';
} else {
echo '<br/>' . "Désolé, mais il y a eu une erreur." . '<br/>';
}
?>
Upon the request of posting my form here (it was too long by 2,000 characters), so I posted it on a fiddle:
http://jsfiddle.net/NdRJV/
EDIT:
As Zeeba suggested, I forced the IE to read another browser:
I used
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">
But, to read more on the topic, anyone else in need of this can visit:
What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?
try adding this to you meta tags
<meta http-equiv="X-UA-Compatible" content="IE=edge" >

Cant send e-mail by php mail on first attempt

I'm trying to send an email via SMTP using PHPMailer on my site, it works the second time I try (use submit), but the first time it says it cannot authenticate, login or password is invalid. I have searched a lot and can't find the answer, can someone help me please?
By the way I'm using JSON to get the PHP response in an alert. My host doesn't have "smtp." in front because support told me to do it this way.
This is the code:
else {
$phpmail = new PHPMailer();
$phpmail->IsSMTP(); // envia por SMTP
$phpmail->Host = "velvetwebdesign.com.br"; // SMTP servers
$phpmail->Port = "587"; // Port
$phpmail->SMTPAuth = true; // Caso o servidor SMTP precise de autenticação
$phpmail->SMTPDebug = 1;
$phpmail->Username = "email#velvetwebdesign.com.br"; // SMTP username
$phpmail->Password = "xxxxxxx"; // SMTP password
$phpmail->IsHTML(true);
$phpmail->From = 'email#velvetwebdesign.com.br';
$phpmail->FromName = $_POST['nome'];
$phpmail->AddAddress("velvetwebdesign#velvetwebdesign.com.br");
$phpmail->AddAddress($_POST['email']);
$phpmail->Subject = 'Contato Velvet Web Design';
$phpmail->Body .= "<b>Cliente:</b> ".$_POST['nome']."<br />";
$phpmail->Body .= "<b>E-mail:</b> ".$_POST['email']."<br />";
$phpmail->Body .= "<b>Telefone:</b> ".$_POST['telefone']."<br />";
$phpmail->Body .= "<b>Assunto:</b> ".$_POST['assunto']."<br /><br />";
$phpmail->Body .= "<b>Mensagem:</b><br />".nl2br($_POST['mensagem'])."<br /><br />";
$phpmail->Body .= "Recebemos a sua mensagem, responderemos em breve.<br />";
$phpmail->Body .= "http://www.velvetwebdesign.com.br/";
$send = $phpmail->Send();
if($send){
echo "A Mensagem foi enviada com sucesso. Enviaremos uma copia para o seu e-mail tambem.";
exit;
}else{
echo "Tente novamente por favor. Erro: " .$phpmail->ErrorInfo;
exit;
}
}
?>

French characters not displaying correctly in PHP mail

I have a basic PHP mail form, but whatever I do, I cannot seem to get the characters to display correctly once sent, if the language is written with French accents.
The example sentence I am using is:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
But it comes out as:
Bonjour, ceci est un message de test envoyé avec PHP pour analyser si
oui ou non la mise en forme est correcte ou fausse. Les personnages ne
devraient être rendus de manière appropriée comme prévu dans le
lexique français.
As you can see, the characters with accents are screwed up, once they are received in the email.
I am processing my message variable as such:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
I am then, sending it like so:
$cc = "example#example.com";
$subject = "Website Enquiry";
$message = '<html><body>';
$message .= "<p><strong>Enquiry</strong><br />" . nl2br($fieldenquiry) . "</p>";
$message .= "</body></html>";
$headers = "From: " . $fieldemail . "\r\n";
$headers .= "Cc: " . $cc . "\r\n";
$headers .= "Reply-To: ". $fieldemail . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";
mail($to, $subject, $message, $headers);
I'm not a PHP developer by any means. The form works in the sense that it sends etc, but I cannot figure out why the characters mess up. I am encoding the POST variable and I am sending the HTML format with a UTF-8 charset.
Help and guidance appreciated.
Michael.
EDIT:
I figured this out. See my answer below.
I figured it out if anyone is in need of a similar piece of help:
I changed this line:
$fieldenquiry = utf8_encode($_POST['fieldenquiry']);
To this:
$fieldenquiry = utf8_encode(htmlentities($_POST['fieldenquiry'], ENT_QUOTES, "UTF-8"));
I use the htmlentities() function with UTF-8 specified in the arguments.
This fixed the issue completely. Hope it helps someone.

How to insert records in external database with objective-C

I have a question, want to make an application to insert records in an external database, but does not work.
Does anyone help me?
This is my xCode code:
-(IBAction)enviar:(id)sender
{
NSString *url = [NSString stringWithFormat:#"http://192.168.1.37/mysql_iphone/insertar_alumno.php?nombre=%#&poblacion=%#",cajaNombre.text,cajaPoblacion.text];
NSData *dataUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *strResult = [[NSString alloc] initWithData:dataUrl encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResult);
}
and this, is my php code
<?php
//Credenciales de la BBDD
$db = "iphone";
$host = 'localhost';
$username = "dpbataller";
$password = '1234';
//Conectamos al servidor de la Base de datos
$link = mysql_connect($host,$username,$password) or die("No se puede conectar");
//Seleccionamos la BBDD
#mysql_select_db($db) or die ("No se ha podido seleccionar a la base de datos");
//Creamos un array para almacenar los resultados
$arr = array();
//Recogemos los valores
//$nombre = $_POST['nombre'];
//$poblacion = $_POST['poblacion'];
//Lanzamos la consulta
$consulta = mysql_query("INSERT INTO alumnos (id,nombre,poblacion) VALUES ('','$_POST[nombre]','$_POST[poblacion]')";
?>
and this is the message of Xcode console:
2012-04-26 23:04:44.981 parse[902:f803] <br />
<b>Parse error</b>: syntax error, unexpected ';' in <b>/Applications/XAMPP/xamppfiles/htdocs/mysql_iphone/insertar_alumno.php</b> on line <b>21</b><br />
What am I doing wrong?
$consulta = mysql_query("INSERT INTO alumnos (id,nombre,poblacion) VALUES ('','$_POST['nombre']','$_POST['poblacion']')";