Jump to content

Ajax module front, différentes actions dans le success


Recommended Posts

Bonjour,

Je développe un module de formulaire de contact en AJAX et je souhaiterais rendre le bouton submit disable lorsque le message est envoyé mais pas quand les verifications des champs ne sont pas faites...

 

dans le tpl:

<script type="text/javascript">	
	$( document ).ready(function() {
        var form = $('.callback');
          form.submit(function(e) {
                $.ajax({
                    type: 'POST',
                    url: baseDir + 'modules/callmeback/callmeback-ajax.php',
                    data: 'ajax=true&from=' + $('#from').val() + '&tel='+ $('#tel').val()+ '&id_contact='+ $('#id_contact').val(),
                    dataType: 'json',
                    success: function(jsonData) {
                        $('#result').html(jsonData);
                        //$("#submit").attr("disabled", true);
                    }
                });
                e.preventDefault();
      });
    });
</script>

<!-- Block call me back module -->
<div class="block">
	<h4 class="title_block">
			{l s='Rappellez-moi' mod='callmeback'}
	</h4>
	<div class="block_content blockcallmeback">
			 				<form class="callback form-horizontal" role="form" method="post">
				 				<input id="id_contact" name="id_contact" value="2" type="hidden">
					 				
					 				<div class="form-group">
					 					<div class="col-md-6"> 
					 						<input title="Renseignez votre email" class="form-control" id="from" name="from" value="" placeholder="Adresse e-mail" type="text">
					 					</div>
					 				</div>
					 				<div class="form-group">
					 					<div class="col-md-6"> 
					 						<input title="Renseignez votre téléphone" class="form-control" id="tel" name="tel" value="" placeholder="Téléphone" type="text">
					 					</div>
					 				</div>
					 				
					 				<div class="text-right"> 
					 					<button type="submit" id="submit" class="btn btn-outline btn-lg"> Envoyer
					 					</button>
					 				</div>
			 				</form>
		 			
		 			<div id="result"></div>
	</div>
</div>
<!-- Block call me back module -->

Dans callmeback-ajax.php a la racine de mon module:

<?php

// Located in /modules/callmeback/callmeback-ajax.php
require_once(dirname(__FILE__).'/../../config/config.inc.php');
require_once(dirname(__FILE__).'/../../init.php');
include_once(dirname(__FILE__).'/../../classes/Contact.php');
include_once(dirname(__FILE__).'/../../classes/CustomerThread.php');
include_once(dirname(__FILE__).'/../../classes/CustomerMessage.php');
include_once(dirname(__FILE__).'/../../classes/Mail.php');


if (!($tel = trim(Tools::getValue('tel'))) || !Validate::isPhoneNumber($tel)) {
	die(Tools::jsonEncode('<span style="color:red">Téléphone non valide</span>'));
}

elseif (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
	die(Tools::jsonEncode('<span style="color:red">E-mail non valide</span>'));
}

else {
		$from = Tools::getValue('from');
		$tel = Tools::getValue('tel');
		$id_contact = (int)Tools::getValue('id_contact');
		$module_mail_dir = _PS_MODULE_DIR_.'callmeback/mails/';
		$context = Context::getContext();
		$contact = new Contact($id_contact, $context->language->id);
		$ct = new CustomerThread();
		                        $ct->id_shop = (int)$context->shop->id;
		                        $ct->id_contact = (int)$id_contact;
		                        $ct->id_lang = (int)$context->language->id;
		                        $ct->email = $from;
		                        $ct->status = 'open';
		                        $ct->token = Tools::passwdGen(12);
		                        $ct->add();
		                    
		$cm = new CustomerMessage();
		                        $cm->id_customer_thread = $ct->id;
		                        $cm->message = 'Il faut rappeller le '.$tel.' dont le mail est '.$from;
		                        $cm->ip_address = (int)ip2long(Tools::getRemoteAddr());
		                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
		                        if (!$cm->add()) {
		                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
		                        }

		                    $var_list = array(
		                                    '{email}' =>  $from,
		                                    '{tel}' =>  $tel,
		                                );

		                    if (empty($contact->email)) {
		                    } else {   

		                        if (!Mail::Send($context->language->id, 'call', Mail::l('Demande de rappel'),
		                            $var_list, $contact->email, $contact->name, null, null, null, null, $module_mail_dir, false, null, null, $from) ) {
		                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
		                        }
		                    }

		$html_content='<span style="color:green">Merci, nous allons vous rappeler dans les plus brefs delais !</span>';
 		die(Tools::jsonEncode($html_content));


}



le module est testé ici: http://demo.alexandrecarette.com/3-femmes

 

merci pour votre aide

Link to comment
Share on other sites

J'ai trouvé la solution que je vous partage:
 

<script type="text/javascript">	
$( document ).ready(function() {
var form = $('.callback');
form.submit(function(e) {
			$.ajax({
					type: 'POST',
					url: baseDir + 'modules/callmeback/callmeback-ajax.php',
					data: 'ajax=true&from=' + $('#from').val() + '&tel='+ $('#tel').val()+ '&id_contact='+ $('#id_contact').val(),
					dataType: 'json',
					success: function(jsonData) {
						if ( !jsonData.success) {
						// handle errors for tel ---------------
						if (jsonData.errors.tel) {
							$('#result').html(jsonData.errors.tel);
						}
						// handle errors for email ---------------
						if (jsonData.errors.from) {
							$('#result').html(jsonData.errors.from);
						} 
					}
					else {
						$('#result').html(jsonData.errors);
						$("#submit").attr("disabled", true);
					}
				}
			});
		return false;
	});
});
</script>

mon php:

<?php

// Located in /modules/callmeback/callmeback-ajax.php
require_once(dirname(__FILE__).'/../../config/config.inc.php');
require_once(dirname(__FILE__).'/../../init.php');
include_once(dirname(__FILE__).'/../../classes/Contact.php');
include_once(dirname(__FILE__).'/../../classes/CustomerThread.php');
include_once(dirname(__FILE__).'/../../classes/CustomerMessage.php');
include_once(dirname(__FILE__).'/../../classes/Mail.php');


if (!($from = trim(Tools::getValue('from'))) || !Validate::isEmail($from)) {
		$errors['from'] = '<span style="color:red">E-mail non valide</span>';
	    $data['success'] = false;
	    $data['errors']  = $errors;
		die(Tools::jsonEncode($data));
}

elseif (!($tel = trim(Tools::getValue('tel'))) || !Validate::isPhoneNumber($tel)) {
	    $errors['tel'] = '<span style="color:red">Téléphone non valide</span>';
	    $data['success'] = false;
	    $data['errors']  = $errors;
		die(Tools::jsonEncode($data));
}

else {
		$from = Tools::getValue('from');
		$tel = Tools::getValue('tel');
		$id_contact = (int)Tools::getValue('id_contact');
		$module_mail_dir = _PS_MODULE_DIR_.'callmeback/mails/';
		$context = Context::getContext();
		$contact = new Contact($id_contact, $context->language->id);
		$ct = new CustomerThread();
		                        $ct->id_shop = (int)$context->shop->id;
		                        $ct->id_contact = (int)$id_contact;
		                        $ct->id_lang = (int)$context->language->id;
		                        $ct->email = $from;
		                        $ct->status = 'open';
		                        $ct->token = Tools::passwdGen(12);
		                        $ct->add();
		                    
		$cm = new CustomerMessage();
		                        $cm->id_customer_thread = $ct->id;
		                        $cm->message = 'Il faut rappeller le '.$tel.' dont le mail est '.$from;
		                        $cm->ip_address = (int)ip2long(Tools::getRemoteAddr());
		                        $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
		                        if (!$cm->add()) {
		                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
		                        }

		                    $var_list = array(
		                                    '{email}' =>  $from,
		                                    '{tel}' =>  $tel,
		                                );

		                    if (empty($contact->email)) {
		                    } else {   

		                        if (!Mail::Send($context->language->id, 'call', Mail::l('Demande de rappel'),
		                            $var_list, $contact->email, $contact->name, null, null, null, null, $module_mail_dir, false, null, null, $from) ) {
		                            $this->errors[] = Tools::displayError('An error occurred while sending the message.');
		                        }
		                    }

	$errors = '<span style="color:green">Merci, nous allons vous rappeler dans les plus brefs delais !</span>';
    $data['success'] = true;
    $data['errors']  = $errors;
 	die(Tools::jsonEncode($data));

}



Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...