i have already one Ajax form on my wordpress website. Now, i need a second one. So i duplicate the function in Function.php. But it does'nt work.
The first form is contact. The second one is inscription. The first one work great.
But for the second one, nothing happen when i try to send...
Here my code.
add_action( 'wp_ajax_contact', '_ajax_contact' );
add_action( 'wp_ajax_nopriv_contact', '_ajax_contact' );
function _ajax_contact() {
/*-----------------------------------------------------------------------------------*/
/* On vérifie le nonce de sécurité
/*-----------------------------------------------------------------------------------*/
check_ajax_referer( 'ajax_contact_nonce', 'security' );
/*-----------------------------------------------------------------------------------*/
/* Protection des variables
/*-----------------------------------------------------------------------------------*/
$subject = wp_strip_all_tags( $_POST['subject'] ); // Sujet du message
$name = wp_strip_all_tags( $_POST['name'] ); // Nom de l'expéditeur
$sender = sanitize_email( $_POST['email'] ); // Adresse e-mail de l'expéditeur
$message = nl2br( stripslashes( wp_kses( $_POST['message'], $GLOBALS['allowedtags'] ) ) );
/*-----------------------------------------------------------------------------------*/
/* Gestion des headers
/*-----------------------------------------------------------------------------------*/
$headers = array();
$headers[] = 'FROM : ' . $name . ' <' . $sender .'>' . "\r\n";
/*-----------------------------------------------------------------------------------*/
/* Gestion du message
/*-----------------------------------------------------------------------------------*/
ob_start();
include( get_template_directory() . '/inc/mail/contact.php' );
$mail = ob_get_contents();
ob_end_clean();
/*-----------------------------------------------------------------------------------*/
/* Envoie de l'e-mail
/*-----------------------------------------------------------------------------------*/
// Support d'un contenu HTML dans l'email
add_filter( 'wp_mail_content_type', create_function('', 'return "text/html";') );
if( wp_mail( 'emailtest#gmail.com', '[subject] Contact', $mail, $headers ) ) {
// Tout est ok, on avertit l'utilisateur
wp_send_json( 'success' );
}
else {
// Il y a une erreur avec le mail, on avertit l'utilisateur
wp_send_json( 'error' );
}
}
/*-----------------------------------------------------------------------------------*/
/* Second form
/*-----------------------------------------------------------------------------------*/
add_action( 'wp_ajax_inscription', '_ajax_inscription' );
add_action( 'wp_ajax_nopriv_inscription', '_ajax_inscription' );
function _ajax_inscription() {
/*-----------------------------------------------------------------------------------*/
/* On vérifie le nonce de sécurité
/*-----------------------------------------------------------------------------------*/
check_ajax_referer( 'ajax_inscription_nonce', 'security' );
/*-----------------------------------------------------------------------------------*/
/* Protection des variables
/*-----------------------------------------------------------------------------------*/
$subject = wp_strip_all_tags( $_POST['subject'] ); // Sujet du message
$name = wp_strip_all_tags( $_POST['name'] ); // Nom de l'expéditeur
$sender = sanitize_email( $_POST['email'] ); // Adresse e-mail de l'expéditeur
$message = nl2br( stripslashes( wp_kses( $_POST['message'], $GLOBALS['allowedtags'] ) ) );
/*-----------------------------------------------------------------------------------*/
/* Gestion des headers
/*-----------------------------------------------------------------------------------*/
$headers = array();
$headers[] = 'FROM : ' . $name . ' <' . $sender .'>' . "\r\n";
/*-----------------------------------------------------------------------------------*/
/* Gestion du message
/*-----------------------------------------------------------------------------------*/
ob_start();
include( get_template_directory() . '/inc/mail/contact.php' );
$mail = ob_get_contents();
ob_end_clean();
/*-----------------------------------------------------------------------------------*/
/* Envoie de l'e-mail
/*-----------------------------------------------------------------------------------*/
// Support d'un contenu HTML dans l'email
add_filter( 'wp_mail_content_type', create_function('', 'return "text/html";') );
if( wp_mail( 'testemail#gmail.com', $subject, $mail, $headers ) ) {
// Tout est ok, on avertit l'utilisateur
wp_send_json( 'success' );
}
else {
// Il y a une erreur avec le mail, on avertit l'utilisateur
wp_send_json( 'error' );
}
}
Looking at your code, the first thing I would try to do is to rename fields with name='name'. I coded a lot of forms and in almost every case, WP wouldn't post my forms, because it has reserved field with name='name'.
Also, activate WP_DEBUG mode to show all errors and try to look for JavaScript errors with Firebug or the browser console.
Thank for your answer, finally i have found another solution. The problem was not in this file..
It was on my form file. I forgot to change a value on the send button.
My mistake :
<input type="hidden" name="action" value="contact" />
<?php wp_nonce_field( 'ajax_inscription_nonce', 'security' ); ?>
<input id="send-message" type="submit" value="Envoyer">
The good code
<input type="hidden" name="action" value="inscription" />
<?php wp_nonce_field( 'ajax_inscription_nonce', 'security' ); ?>
<input id="send-message" type="submit" value="Envoyer">
Thanks a lot.
Related
I'm trying desperately to add an image to my db.it's all that remains to be done on my project
It fits well in my public folder, but in my db I have this:
C: \ wamp \ tmp \ phpDDB4.tmp
and I can't find the problem.
SlideController.php
public function validSlide(Request $request){
$validator = Validator::make($request->all(),[
'titre'=>'',
'description'=>'',
/* Storage::put($destinationPath,File::get($image->getRealPath())),*/
]);
$image = $request->file('photo');
$input['photo'] = $image->getClientOriginalName();
$destinationPath = public_path('/media');
$image->move($destinationPath, $input['photo']);
//Si l'une des contraintes n'est pas respectée on rédirige à nouveau vers la page du formulaire et on retourne les erreurs ainsi que l'ancien contenu des champs
if($validator->fails()){
return redirect('admin/add/slide')->withErrors($validator)->withInput();
}
//Sinon on fait l'insert
$parameters = $request->except(['_token']);
//$parameters = $request->all();
//var_dump($parameters); die;
//On appelle le modèle
Slide::create($parameters);
// On le rédirige vers la page d'accueil et on envoie un message flash de confirmation
return redirect('admin/slide')->with(['success'=>'Slide enregistré !']);
}
formulaire.blade.php
<div class="form-group">
<label for="photo">Example file input</label>
<input type="file" name="photo" class="form-control-file"
id="photo" value="{{$slides->photo or ''}}">
</div>
And my model:
Slide.php
class Slide extends Model
{
protected $table = 'slide';
public $timestamps = false;
protected $fillable = [
'titre','description','photo'
];
// the rest of the code
}
Thank you for your help.
PS: sorry for my disastrous English ;-)
WP_MAIL functionality is not working in my ajax function in functions.php file.
Please have an look on the code and help me out !!
Do i need to load any files for the working of wp_mail function ??
function et_contact_form() { ?>
<script type="text/javascript" >
jQuery('#contact_modal').on('submit', function (e) {
e.preventDefault();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var name = jQuery("#name").val();
var data = {
'action':'et_contact_modal',
'name' : name
};
jQuery.post(ajaxurl, data, function(response) {
alert(response);
});
});
</script> <?php
}
add_action( 'wp_footer', 'et_contact_form' );
function et_contact_modal() {
global $wpdb;
$headers .= "Reply-To: test#gmail.com \r\n";
//$headers .= "CC: test#gmail.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$subject = 'New Enquiry From ';
$message .= '<p>' . $_POST['name'] . '</p>';
$message .= '<p></p>';
$mailResult = false;
$mailResult = wp_mail( 'test#gmail.com',$subject,$message, $headers );
echo $mailResult;
}
add_action( 'wp_ajax_et_contact_modal', 'et_contact_modal' );
Sorry people's!!
The code was correct , it was just server issue !!
Thank you.
I have an external paiement application service who take care about the paiements from my shopping application .
I have a form method Post to the service to send the data and the service valide the payment transaction .
<form method="POST" action="https://paiement.systempay.fr/vads-payment/">
...
<input type="submit" name="payer" value="Payer"/></form>
</form>
I would like to post also a request method from my payment controller to update my items who was paid
here my controller wish i would like to be run when the user click on "payer" also
public function postCheckoutCreditCard(Request $request)
{
if(!Session::has('Cart')){
return view('shop.panier');
}
$oldCart = Session::get('Cart') ;
$cart = new Cart($oldCart);
$items = $cart->items;
if(Input::get('payer')) {
// on inject le nouveau statut de la licence
foreach ($items as $item) {
$item['item']->statut_licence_id = LicenceStatut::where('id', '4')->firstOrFail()->id;
$item['item']->valid_licence_id = LicenceValid::where('id', '1')->firstOrFail()->id;
$item['item']->save();
}
$order = new Order;
$prefix = 'F';
$date = Carbon::now();
$saison = Saison::where('dt_deb', '<', $date)->where('dt_fin', '>', $date)->value('lb_saison');
$saison_deb = substr($saison, 2, 2);
$saison_fin = substr($saison, -2);
$num_facture_exist = true;
while ($num_facture_exist) {
$num_facture = $prefix . $saison_deb . $saison_fin . substr(uniqid(rand(), true), 4, 4);
if (!Order::where('num_facture', '=', $num_facture)->exists()) {
$order->num_facture = $num_facture;
$num_facture_exist = false;
}
}
$order->structure_id = Structure::where(['id' => Auth::user()->structure->id])->firstOrFail()->id;
$order->cart = serialize($cart);
$order->date_achat = Carbon::now();
$order->payment_method = 'Carte de Crédit';
$order->etat_paiement = 'Facture Réglée';
$order->save();
Auth::user()->notify(new InvoicePaid($order));
$federation = Structure::where('id', '1')->first();
Mail::to($federation->adresse_email_structure)->send(new NouvelleCommande($order));
Session::forget('Cart');
return redirect('home')->with('status', "Votre paiement à été effectué avec sucess , votre numéro de facture : . $order->num_facture est disponible dans la rubrique Mes cotisation ");
}
}
I'm not sure how to do this . someone could help me ? thanks in advance
I would change the form action to your Controller and then use Guzzle to call the external route. Check here about Guzzle (http://docs.guzzlephp.org/en/latest/quickstart.html#post-form-requests).
Call something like this in your Controller:
$response = $client->request('POST', 'https://paiement.systempay.fr/vads-payment/', [
'form_params' => [
'field_name' => 'abc',
]
]);
Then check the response and return something based on it.
I've an HTML onepage website.
I want insert google recaptcha 2.0 system but something go wrong with js.
When i click on submit button no success message is shown and no message is sent.
The button Send remains clicked and no further actions happen.
WIth the original php file on bottom the form works. But i've to insert recaptcha, too much spam.
Could someone help?
Thank you
Scipio
HTML CODE
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form name="frmcontact" action="php/send.php" class="contact-frm" method="post">
<input type="text" required placeholder="Nome" name="txtname">
<p class="twocolumn">
<input type="email" required placeholder="Email" name="txtemail">
<input type="tel" placeholder="Phone" name="txtphone">
</p>
<div class="g-recaptcha" data-sitekey="xxx"></div>
<textarea placeholder="Testo del Messaggio" name="txtmessage"></textarea>
<input type="submit" class="button" value="SEND" name="btnsend">
PHP CODE THAT I WANT TO INSERT:
<?php
if(isset($_POST['btnsend']) && !empty($_POST['btnsend'])):
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha- response'])):
//your site secret key
$secret = 'XXX';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success):
//contact form submission code
$name = !empty($_POST['txtname'])?$_POST['txtname']:'';
$email = !empty($_POST['txtemail'])?$_POST['txtemail']:'';
$email = !empty($_POST['txtphone'])?$_POST['txtphone']:'';
$message = !empty($_POST['txtmessage'])?$_POST['txtmessage']:'';
$to = 'XXX';
$subject = 'New contact form have been submitted';
$htmlContent = "
<h1>Contact request details</h1>
<p><b>Name: </b>".$name."</p>
<p><b>Email: </b>".$email."</p>
<p><b>Phone: </b>".$phone."</p>
<p><b>Message: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// More headers
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
//send email
#mail($to,$subject,$htmlContent,$headers);
$succMsg = 'Your contact request have submitted successfully.';
else:
$errMsg = 'Robot verification failed, please try again.';
endif;
else:
$errMsg = 'Please click on the reCAPTCHA box.';
endif;
else:
$errMsg = '';
$succMsg = '';
endif;
?>
JS CODE:
$('form[name="frmcontact"]').submit(function () {
var This = $(this);
if($(This).valid()) {
var action = $(This).attr('action');
var data_value = unescape($(This).serialize());
$.ajax({
type: "POST",
url:action,
data: data_value,
error: function (xhr, status, error) {
confirm('The page save failed.');
},
success: function (response) {
$('#ajax_contact_msg').html(response);
$('#ajax_contact_msg').slideDown('slow');
if (response.match('success') != null) $(This).slideUp('slow');
}
});
}
return false;
});
ORIGINAL PHP CODE:
<?php
if(!$_POST) exit;
$to = 'gopal#iamdesigning.com'; #Replace your email id...
$name = $_POST['txtname'];
$email = $_POST['txtemail'];
$phone = $_POST['txtphone'];
$subject = 'Support';
$comment = $_POST['txtmessage'];
if(get_magic_quotes_gpc()) { $comment = stripslashes($comment); }
$e_subject = 'You\'ve been contacted by ' . $name . '.';
$msg = "You have been contacted by $name with regards to $subject.\r\n\n";
$msg .= "$comment\r\n\n";
$msg .= "You can contact $name via email, $email.\r\n\n";
$msg .= "-------------------------------------------------------------------------------------------\r\n";
if(#mail($to, $e_subject, $msg, "From: $email\r\nReturn-Path: $email\r\n"))
{
echo "<span class='success-msg'>Thanks for Contacting Us, We will call back to you soon.</span>";
}
else
{
echo "<span class='error-msg'>Sorry your message not sent, Try again Later.</span>";
}
?>
I have made a custom 'Account Creation' script so that users can login from my phone application.
What I want is to be able to change the responses from the server depending on their locale. So when I request a page I would add lang=en or lang=zh etc.
This works
http://mysite.com/phone/my_custom_account_creation.php?lang=en
Response:
<resource classification="error" code="Error (Code: 500)">
<message>Please enter your name:</message>
</resource>
This does not work:
http://mysite.com/phone/my_custom_account_creation.php?lang=zh
Response:
<resource classification="error" code="Error (Code: 500)">
<message>Please enter your name:</message>
</resource>
If I go into Joomla at set the default language to chinese, it works.
<resource classification="error" code="Error (Code: 500)">
<message>请输入您的姓名。</message>
</resource>
but
http://mysite.com/phone/my_custom_account_creation.php?lang=en
does not work, instead it continues to show the chinese version.
What might I be able to do here?
here is the code I am using for registration:
<?php
header ("content-type: text/xml");
/*
* Register a user from a phone interface using JAVA
*/
define( '_JEXEC', 1 );
//define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root
define('JPATH_BASE', dirname(__FILE__)."/../.." );//this is when we are in the root
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
//My functions
require_once('../shared_functions.php');
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
//Don't use tokens for registration
//JRequest::checkToken() or jexit( 'Invalid Token' );
$user = clone(JFactory::getUser());
$pathway = & $mainframe->getPathway();
$config = & JFactory::getConfig();
$authorize = & JFactory::getACL();
$document = & JFactory::getDocument();
$usersConfig = &JComponentHelper::getParams( 'com_users' );
if ($usersConfig->get('allowUserRegistration') == '0')
{
xmlError("Access Forbidden (Code 403)","Registration has been temporarily disabled");
//JError::raiseError( 403, JText::_( 'Access Forbidden' ));
return;
}
$newUsertype = $usersConfig->get( 'new_usertype' );
if (!$newUsertype)
{
$newUsertype = 'Registered';
}
if (!$user->bind( JRequest::get('post'), 'usertype' ))
{
xmlError("Error (Code: 500)",$user->getError());
return;
//JError::raiseError( 500, $user->getError());
}
$user->set('id', 0);
$user->set('usertype', '');
$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
$date =& JFactory::getDate();
$user->set('registerDate', $date->toMySQL());
$useractivation = $usersConfig->get( 'useractivation' );
if ($useractivation == '1')
{
jimport('joomla.user.helper');
$user->set('activation', md5( JUserHelper::genRandomPassword()) );
$user->set('block', '1');
}
if (!$user->save()) { // if the user is NOT saved...
xmlError("Error (Code: 500)",$user->getError());
//JError::raiseWarning('', JText::_( $user->getError())); // ...raise an Warning
//return false; // if you're in a method/function return false
}
xmlMessage("ok",CODE_ACCOUNT_CREATED,"Success");
?>
I got it working
$lang =& JFactory::getLanguage();
$lang->setLanguage( $_GET['lang'] );
$lang->load();
I found that the language had to be in full format though en-GB or zh-CN