Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 22.08.2014, 14:13
Интересующийся
Отправить личное сообщение для roma88 Посмотреть профиль Найти все сообщения от roma88
 
Регистрация: 20.05.2014
Сообщений: 19

ajax + php + json + отправка на почту
Здравствуйте. Прошу сильно не ругать)
Вопросик.
Имеется скрипт для отправкий данных из формы на сервер
function __(data){
    if( typeof( console ) != 'undefined' ){
        console.log(data);
    }
}

//
// LeadiaForm Class
//

var LeadiaForm = function(params){

    var root = this;

    var errorCallback = false;
    var successCallback = false;

    var submitUrl = false;

    this.data = {};

    //
    // Constructor
    //

    this.init = function(params){

        root.submitUrl = params['url'];
        root.successCallback = params['success'];
        root.errorCallback = params['error'];
        root.callbacks = params['callbacks'];

        //root.data['question'] = '';

        // Triggered on submiting a form, may be a part of a form

        jQuery('[data-form]').submit(function(event){
            event.preventDefault();
            root.post(jQuery(this));
        });

        // Remove error class from modified input

        jQuery('[data-form-field]').change(function(){
            jQuery(this).removeClass('error');
        });

        // Go to step

        jQuery('[data-goto-step]').click(function(){
            var step = jQuery(this).data('goto-step');
            root.goto(step);
        });

        jQuery('[data-form-submit]').removeAttr('disabled');

       
    }

    //
    // Calling constructor
    //

    this.init(params);

    //
    // Validate Form
    //

    this.post = function(form){

        var fields = form.find('[data-form-field]');
        var nextStep = form.data('next-step');
        var error = false;

        fields.each(function(){

            var field = jQuery(this);
            var fieldName = field.data('form-field');
            var fieldVal = field.val();

            if(typeof(root.data[fieldName]) == 'undefined'){

                if(fieldVal.length){ // If valid field

                    root.data[fieldName] = fieldVal;

                    var field_desc = field.data('form-field-desc');
                    if(typeof(field_desc) != 'undefined'){
                        root.data['question'] += ' ' + field_desc + ': ' + fieldVal + ' ';
                    }


                }else{
                    if( field.data('necessary') ){
                        error = true;
                        field.addClass('error');
                    }
                }
            }


        });

        // Going to the next step

        if( !error ){

            try {
                var target = form.data('target');
                yaCounter22529122.reachGoal(target);
                console.log('Target hit: '+target);
            } catch (e) {
            }

            try {
                var callback = form.data('callback');
                console.log('Callback: '+callback);
                root.callbacks[callback]();
            } catch (e) {
            }

            // If this is the last step, send the lead

            if( form.data('send-lead') ){

                // Prepare form data

                var additional_fields = ['userid', 'subaccount', 'client_ip', 'template', 'product'];

                for( field in additional_fields ){
                    var field_val = jQuery('body').data(field)
                    if( typeof( field_val ) != 'undefined' && field_val.length > 0 ){
                        root.data[field] = field_val;
                    }
                }

                if(jQuery('body').data('user-id'))
                    root.data['userid'] = jQuery('body').data('user-id');
                if(jQuery('body').data('subaccount'))
                    root.data['subaccount'] = jQuery('body').data('subaccount');
                if(jQuery('body').data('client-ip'))
                    root.data['client_ip'] = jQuery('body').data('client-ip');

                //root.data['userid'] = jQuery('body').data('user-id');
                //root.data['subaccount'] = jQuery('body').data('subaccount');
                //root.data['client_ip'] = jQuery('body').data('client_ip');
                //root.data['template'] = jQuery('body').data('template');
                //root.data['product'] = jQuery('body').data('product');

                root.send();

                jQuery('[data-form-submit]').attr('disabled', 'disabled');

            }else{
                root.goto(nextStep); // Go to next step
            }

        }

        return error;

    }

    // Send Lead

    this.send = function(){

        __(root.data);
        jQuery.ajax({
            url: root.submitUrl,
            data: root.data,
            type: 'post',
            success: root.successCallback
        });
    }

    // Go To Step

    this.goto = function(step){
        jQuery('.step').removeClass('active');
        jQuery('[data-step="'+step+'"]').addClass('active');
        if (step==='finish') window.location.replace(thank_you_url);
    }
}


Этот скрипт отправляет на сервер
Код:
Object {question: "123123", first_last_name: "123123", phone: "123123", region: "123123", email: "123123"}
Подскажите пожалуйста, как мне на сервере получить этот массив и отправить его на почту.

Читал что-то про JSON но так и не разобрался

Заранее всем спасибо
Ответить с цитированием
  #2 (permalink)  
Старый 22.08.2014, 14:20
Аватар для ixth
Профессор
Отправить личное сообщение для ixth Посмотреть профиль Найти все сообщения от ixth
 
Регистрация: 19.01.2010
Сообщений: 354

С какими параметрами инициализируется LeadiaForm? Тут простой post-запрос на submitUrl, никакого json'а. question, phone — они все лежат в $_POST.
Ответить с цитированием
  #3 (permalink)  
Старый 22.08.2014, 14:28
Интересующийся
Отправить личное сообщение для roma88 Посмотреть профиль Найти все сообщения от roma88
 
Регистрация: 20.05.2014
Сообщений: 19

спасибо, вот я дурак
сделал так
$header.="Content-type: text/plain; charset=\"utf-8\"";

$question = $_POST["question"];
$first_last_name = $_POST["first_last_name"];
$phone = $_POST["phone"];
$region = $_POST["region"];
$email = $_POST["email"];

if(!isset($hasError)) {
    $emailTo = 'Сюда введите Ваш email'; //Сюда введите Ваш email
    $subject = "Тема письма";
    $body = "Имя: $first_last_name\n\nГород: $region\n\nТелефон: $phone\n\nE-mail: $email\n\nВопрос: $question";

    mail($emailTo, $subject, $body, 'Content-type: text/plain; charset=utf-8' . "\r\n" . 'From: Заявка <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email);
    $emailSent = true;
} else {
    echo ("Ошибка");
}

все работает
Ответить с цитированием
  #4 (permalink)  
Старый 22.08.2014, 15:02
Интересующийся
Отправить личное сообщение для roma88 Посмотреть профиль Найти все сообщения от roma88
 
Регистрация: 20.05.2014
Сообщений: 19

возникла другая проблема, страница после отправки перезагружается, не подскажете в чем может быть проблема?
Ответить с цитированием
  #5 (permalink)  
Старый 22.08.2014, 15:17
Аватар для ixth
Профессор
Отправить личное сообщение для ixth Посмотреть профиль Найти все сообщения от ixth
 
Регистрация: 19.01.2010
Сообщений: 354

Как инициализируется LeadiaForm? Как вешается на саму форму? Приведенный код сам по себе ничего не делает, это просто объявление конструктора класса и его методов.
Ответить с цитированием
  #6 (permalink)  
Старый 22.08.2014, 15:22
Интересующийся
Отправить личное сообщение для roma88 Посмотреть профиль Найти все сообщения от roma88
 
Регистрация: 20.05.2014
Сообщений: 19

может сдесь

function genCount() {
    var def = 460152;
    var ts = 1379591528;
    var ti = new Date().getTime();
    var tsi = parseInt(ti.toString().substring(0, 10));

    var rand = 5 + Math.floor(Math.random() * 10);

    var ta = def + parseInt((tsi - ts) / 5);
    jQuery('.counter').text(ta);
}

function step1Callback(){

    window.my = 0;

    jQuery(document).mousemove(function(e){
        window.my = e.pageY - window.scrollY;
    });

    window.onmouseout = function(evt){
        var cookie = jQuery.cookie('show_modal');
        if (evt.toElement == null && evt.relatedTarget == null && window.my<50 && typeof(cookie) == 'undefined' && cookie != 'false' && !window.lead) {
            jQuery('#dontLeaveMe').modal('show');

        }

        jQuery('#dontLeaveMe').on('hide.bs.modal', function (e) {
            jQuery.cookie('show_modal', 'false');
        })
    }
}

function modalCallback(){
    jQuery('#dontLeaveMe').modal('hide');
}

function leadCallback(){
    window.lead = true;
    form.goto('finish');
}

jQuery(document).ready(function () {

    $('#free_quest').focus();

    var form = new LeadiaForm({
        url: './lead.php',
        success: function (data) {
            form.goto('finish');
            jQuery('[data-toggle="tab"]').removeAttr('data-toggle');
        },
        callbacks: {
            'step1': step1Callback,
            'modal': modalCallback,
            'lead-sent': leadCallback
        }
    });

    genCount();
    setInterval(genCount, 6478);

    jQuery('.city-input').keyup(function () {
        if (jQuery(this).val().toLowerCase() == 'москва') {
            jQuery('[data-form-field="district"]').removeAttr('disabled');
        }
    });

    jQuery('.modal-about').click(function () {
        jQuery('#about').modal('show');
    });

    jQuery('.do-consult').click(function () {
        var text = jQuery(this).data('text');
        var textarea = jQuery('#consult .description');
        textarea.val(text);
        jQuery('#form-tabs a[href="#consult"]').tab('show');
        jQuery('html, body').animate({
            scrollTop: 0
        }, 200);
    });

    jQuery('.tab-control').click(function (e) {
        e.preventDefault();
        jQuery('.navbar-static-top li').removeClass('active');
        jQuery(this).parent().addClass('active');
        var tab = jQuery(this).attr('href');
        console.log(tab);
        jQuery('#form-tabs a[href="' + tab + '"]').tab('show');
        jQuery('html, body').animate({
            scrollTop: 0
        }, 200);
    });


    jQuery('.wrong').click(function () {
        jQuery(this).hide();
        var cityinput = jQuery('.city-input');
        cityinput.removeAttr('disabled');
        cityinput.val('');
    });


    /*last_tab*/
    $('#question').prop('disabled', true);
    $('.question').hide();
    $(document).on('change', '#category', function () {
        $('#question').children('option').show();
        var currentCategory = $(this).children('option:selected').attr('class');
        $('#question').prop('selectedIndex', 0);
        if (currentCategory == 'init_option') {
            $('#question').prop('disabled', true)
        } else {
            $('#question').prop('disabled', false);
            var needQuestions = $('#question_all').children('option').filter('.' + currentCategory).clone();
            $('#question').html(needQuestions)
            //console.log(needQuestions)
        }
        if (currentCategory == 'custom_question') {
            jQuery('#form-tabs a[href="#consult"]').tab('show');
            jQuery('#category option').removeAttr('selected');
            jQuery('#category option:first-child').attr('selected', 'selected');
            jQuery('#question').attr('disabled', 'disabled');
            //$('#question, #category, .category_title, .question_title').hide();
            //$('.question').show();
            //$('.question_title').text('Задайте свой вопрос:')
        }
    })


    $('#free_consult a').on('click', function () {
        $('#free_quest').focus();
    })


    //Scrolling to Main Form
    $('#quest_jurist').on('click',function(e){
        e.preventDefault();
        $("html, body").animate({ scrollTop: 135 }, 1000);
        $('#form-tabs').find('li').removeClass('active');
        $('#form-tabs').children('li.consult').addClass('active');
        $('.tab-pane').removeClass('active');
        $('#consult').addClass('active');
        $('#free_quest').focus();
    });

    //Scrolling to Main Form (second_tab)
    $('#call_jurist').on('click',function(e){
        e.preventDefault();
        $("html, body").animate({ scrollTop: 135 }, 1000);
        $('#form-tabs').find('li').removeClass('active');
        $('#form-tabs').children('li.callmeback').addClass('active');
        $('.tab-pane').removeClass('active');
        $('#callmeback').addClass('active');
        $('#free_quest').focus();

    });

    //Replacing the Main form area
    $('#replace_val').on('click', function(){
        var bottomValue = $('#bottom_val').val();
        $("html, body").animate({ scrollTop: 135 }, 1000);
        $('#form-tabs').find('li').removeClass('active');
        $('#form-tabs').children('li.consult').addClass('active');
        $('.tab-pane').removeClass('active');
        $('#consult').addClass('active');
        $('#free_quest').val(bottomValue).focus();
    });


});
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Как ajax (ом) обработать json из файла php Nevrali Events/DOM/Window 7 27.07.2014 19:25
отправка письма на почту (php) cyber Серверные языки и технологии 25 24.02.2014 12:37
Книги по Ajax BaVa Учебные материалы 18 18.08.2013 14:05
Очень нужно.. Отправка HTML куски в JSON от сервера используя Ajax bivnikus jQuery 8 26.10.2010 23:54
Что выбрать XML или JSON для передачи Ajax - ом из PHP в JS Gozar Общие вопросы Javascript 20 16.08.2009 23:36