Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Ten kod należy umieścić w pliku functions.php
- add_action('wp_ajax_formularz', '_formularz');
- add_action('wp_ajax_nopriv_formularz', '_formularz');
- function _formularz(){
- try {
- if ( empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) ) {
- throw new Exception('Puste pola.');
- }
- if ( !is_email($_POST['email']) ) {
- throw new Exception('Niepoprawny email');
- }
- $name = $_POST['name'];
- $email = $_POST['email'];
- $message = $_POST['message'];
- $headers = 'From: WP Solucje <dev@wpsolucje.pl>';
- $send_to = $email;
- $subject = "Test formularza AJAX : " . $name;
- $message = "Wiadomość od ".$name.": \n\n ". $message . " \n\n Odpowiedz do: " . $email;
- if ( wp_mail( $email, $subject, $message, $headers ) ) {
- echo json_encode( 'Sent' );
- exit;
- } else {
- throw new Exception( 'Error sending, Sprawdź AJAX.' );
- }
- } catch ( Exception $e ) {
- echo json_encode( array( 'status' => 'error', 'message' => $e->getMessage() ) );
- exit;
- }
- wp_die();
- }
- // Dodanie zmiennej globalnej do JS:
- //formularz kontaktowy
- wp_register_script ( 'contact_form', get_template_directory_uri() . '/inc/contakt_form.js', array('jquery'), '1.1.3', true );
- wp_localize_script( 'contact_form', 'ajaxurl', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
- wp_enqueue_script ( 'contact_form' );
- // Plik JS obsługujący formularz:
- jQuery(document).ready(function ($) {
- // 1. Pierwszys sposob:
- // jQuery(document).on( 'submit', '#forma', function(e) {
- // e.preventDefault();
- // var data = {
- // action: 'formularz', //calls wp_ajax_nopriv_ajaxlogin
- // name: $('form#forma #name').val(),
- // email: $('form#forma #email').val(),
- // message: $('form#forma #message').val(),
- // };
- // // We can also pass the url value separately from ajaxurl for front end AJAX implementations
- // $.post( ajaxurl.ajaxurl, data, function( response ) {
- // alert('Odpowiedź z serwera ' + response );
- // });
- // });
- // .1
- // 2. Drugi sposób
- $('form#forma').on('submit', function(e){
- e.preventDefault();
- var $this = $(this); // Cache this
- $.ajax({
- type: 'POST',
- dataType: 'json',
- url: ajaxurl.ajaxurl,
- data: {
- action: 'formularz', //calls wp_ajax_nopriv_$your_action
- name: $('form#forma #name').val(),
- email: $('form#forma #email').val(),
- message: $('form#forma #message').val(),
- },
- success: function( response ){
- alert ( response );
- },
- error: function ( response ){
- alert ( response );
- }
- });
- });
- // .2
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement