Why is an empty ajax form submitting?

  • 0
    Hello everyone.
    The usual form is:
    <form id="modul-form_10" data-form-validate="true">
    ....
    </form>

    To submit forms in Bitrix24 I use the following php:
    <?
    define('CRM_HOST', 'my_host.bitrix24.ru'); // Ваш домен CRM системы
    define('CRM_PORT', '443'); // Порт сервера CRM. Установлен по умолчанию
    define('CRM_PATH', '/crm/configs/import/lead.php'); // Путь к компоненту lead.rest
     
    define('CRM_LOGIN', 'my_login'); // Логин пользователя Вашей CRM по управлению лидами
    define('CRM_PASSWORD', 'my_password'); // Пароль пользователя Вашей CRM по управлению лидами
     
    $tema = $_POST['title'];; //получаем значение полей из формы и записываем их в переменные методом POST 
    
    $name = $_POST['name'];
    $phone = $_POST['field'];
    $promo = $_POST['promo'];
    $size = $_POST['size'];
    $sum = $_POST['sum'];
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
    	$leadData = $_POST['DATA'];
    	
    	$postData = array(
    		'TITLE' => $tema,		
    		'NAME' => $name,
    		'PHONE_MOBILE' => $phone,
    		'UF_CRM_1539439128' => $promo,
    		'UF_CRM_1539440067' => $size,
    		'OPPORTUNITY' => $sum,
    		
    	);
    
    	if (defined('CRM_AUTH'))
    	{
    		$postData['AUTH'] = CRM_AUTH;
    	}
    	else
    	{
    		$postData['LOGIN'] = CRM_LOGIN;
    		$postData['PASSWORD'] = CRM_PASSWORD;
    	}
    
    	$fp = fsockopen("ssl://".CRM_HOST, CRM_PORT, $errno, $errstr, 30);
    	if ($fp)
    	{
    		$strPostData = '';
    		foreach ($postData as $key => $value)
    			$strPostData .= ($strPostData == '' ? '' : '&').$key.'='.urlencode($value);
    
    		$str = "POST ".CRM_PATH." HTTP/1.0\r\n";
    		$str .= "Host: ".CRM_HOST."\r\n";
    		$str .= "Content-Type: application/x-www-form-urlencoded\r\n";
    		$str .= "Content-Length: ".strlen($strPostData)."\r\n";
    		$str .= "Connection: close\r\n\r\n";
    
    		$str .= $strPostData;
    
    		fwrite($fp, $str);
    
    		$result = '';
    		while (!feof($fp))
    		{
    			$result .= fgets($fp, 128);
    		}
    		fclose($fp);
    
    		$response = explode("\r\n\r\n", $result);
    
    		$output = '<pre>'.print_r($response[1], 1).'</pre>';
    	}
    	else
    	{
    		echo 'Не удалось подключиться к CRM '.$errstr.' ('.$errno.')';
    	}
    }
    else
    {
    }
    ?>


    And ajax with validation
    $("form[data-form-validate='true']").each(function() {
    	$(this).validate({
    		 
    		errorPlacement: function(error, element) {
                if (element.attr("name") == "checkeds") {
    
                    error.insertAfter(element.parent());
                } else {
                    error.insertAfter(element);
                }
                return true;
            },
    		highlight: function(element) {
    			$(element).parent().addClass("error-check");
    		},
    		unhighlight: function(element) {
    			$(element).parent().removeClass("error-check");
    		},
             rules: {
                 name: {
                     required: true,
                     minlength: 2
                 },
                
    			 field: {
    			  required: true,
    			  number: true,
    			  minlength: 11
    			},
    			checkeds: {
                    required: true
                },
                 subject: {
                     required: true
                 }
             },
    		  messages: {
    			 name: {
    			 required: "Не заполненное поле",
    			 minlength: "Введите не менее 2-х символов"
    			 },
    			 field: {
    			 required: "Не заполненное поле",
    				minlength: "11-значный номер телефона",
    				number:"Введите в формате 89876543210"
    			 },
    			 checkeds: {
                    required : ""
                },
    			
    			 },
          submitHandler: function (form) {
    		var formID = $(this).attr('id'),
    		 formNm = $('#' + formID);
    		 $.ajax({
    			type: "POST",
    			url: 'integration.php',
    			data: formNm.serialize(),
    			success: setTimeout((function(data){
    					if (data == 'yes'){
    						location.href = "http://my_site/thank-you"
    						
    						}
    					}).bind(this), 1500, "yes")	,
    			error: function (jqXHR, text, error) {
    		 $(formNm).html(error);
    		 }
    		 });
    		 return false;
    	 }
         });
         });

    But the form in Bitrix24 comes empty. Without ajax request:
    <form id="modul-form_10" data-form-validate="true" action="integration.php" method="post">
    ...
    </form>

    everything is recovering normally. Tell me what could be the problem?
    jQuery Anonymous, Sep 28, 2020

  • 1 Answers
  • 0
    Solved the issue. Maybe someone will come in handy, corrected js:

    $("form").each(function() {
    var formID = $(this).attr('id'),
    formNm = $('#' + formID + '[data-form-validate="true"]');

    formNm.validate({
    errorPlacement: function(error, element) {
    if (element.attr("name") == "checkeds") {

    error.insertAfter(element.parent());
    } else {
    error.insertAfter(element);
    }
    return true;
    },
    highlight: function(element) {
    $(element).parent().addClass("error-check");
    },
    unhighlight: function(element) {
    $(element).parent().removeClass("error-check");
    },
    rules: {
    name: {
    required: true,
    minlength: 2
    },

    field: {
    required: true,
    number: true,
    minlength: 11
    },
    checkeds: {
    required: true
    },
    subject: {
    required: true
    }
    },
    messages: {
    name: {
    required: "Не заполненное поле",
    minlength: "Введите не менее 2-х символов"
    },
    field: {
    required: "Не заполненное поле",
    minlength: "11-значный номер телефона",
    number:"Введите в формате 89876543210"
    },
    checkeds: {
    required : ""
    },

    },
    submitHandler: function (form) {

    $.ajax({
    type: "POST",
    url: 'integration.php',
    data: formNm.serialize(),
    success: setTimeout((function(data){
    if (data == 'yes'){
    location.href = "http://my_site/thank-you""

    }
    }).bind(this), 1500, "yes")

    });


    }

    });
    });
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!