Simindey
2/14/2017 - 7:34 AM

Отправка формы AJAX ом с прикреплением файла.

Отправка формы AJAX ом с прикреплением файла.

<? if(!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED!==true)die();?>

<?
foreach ($arResult['ITEMS'] as $row) {
	$comment[(int) $row['PROPERTY_ANSWER_TO_VALUE']][] = $row;
}

function commentPrint($comment, $parent=0) {

    if (empty($comment[$parent]))
        return;

	global $USER;
    foreach ($comment[$parent] as $vItem) {
        echo '<div class="tender_item_answer">';
			echo '<a class="img" href="#"><img src="'.$vItem['PROPERTY_USER_VALUE']['PHOTO']['src'].'" width="'.$vItem['PREVIEW_PICTURE']['width'].'" height="'.$vItem['PREVIEW_PICTURE']['height'].'" alt="image"></a>';
			echo '<div class="nofloat">';
				echo '<div class="tender_item_answer_title">';
					echo '<div class="tender_item_answer_top">';
						echo '<a class="name" href="#">'.$vItem["PROPERTY_USER_VALUE"]["USER_NAME"].'</a>';
						echo '<div class="date_ico">';
							echo $vItem["DATE_CREATE"];
						echo '</div>';
					echo '</div>';
					echo '<div class="rating_star">';
						echo '<div class="active"></div>';
						echo '<div class="active"></div>';
						echo '<div class="active"></div>';
						echo '<div class="active"></div>';
						echo '<div class="active_half"></div>';
						echo '<span class="rating_star_num">25</span>';
					echo '</div>';
					echo '<div class="hot">';
						echo 'pro';
					echo '</div>';
				echo '</div>';
				echo '<div class="txt">'.$vItem['PREVIEW_TEXT'].'</div>';
					if($GLOBALS["VJWEB"]["ACCESS"] == "Y" && $USER->GetID() != $vItem["PROPERTY_USER_VALUE"]["ID"]){
						echo '<a class="btn answer_comm" data-idAnswer="'.$vItem["ID"].'" data-idUser="'.$vItem["PROPERTY_USER_VALUE"]["ID"].'" href="#form_answer">'.GetMessage("VJWEB_ANSWER").'</a>';
							if ($USER->IsAdmin() && empty($vItem["PROPERTY_ANSWER_TO_VALUE"])){
								echo '<a class="btn add_cand" href="javascript:void(0);" onclick="vjweb_SendForm("'.$vSubItem["ID"].'", "13")">'.GetMessage("VJWEB_ADD_TO_CANDIDATES").'</a>';
								echo '<a class="btn btn_red add_execut" href="javascript:void(0);" onclick="vjweb_SendForm("'.$vSubItem["ID"].'", "11")">'.GetMessage("VJWEB_SELECT_ EXECUTIVE").'</a>';
							}
					}
			echo '</div>';

        if (isset($comment[$vItem['ID']]))
            commentPrint($comment, $vItem['ID']);
        echo '</div>';
    }

}
?>

<?$ajaxPath = $templateFolder.'/ajax.php'?>
<section class="tender_item_sect">
<section class="tender_item_answer_sect">
		<div class="container" id="tender" data-tenderid="<?=$arResult['ITEMS'][0]['PROPERTY_TENDER_VALUE']?>">
			<h2 class="h2">ответов</h2>
			<?commentPrint($comment);?>
		</div>
		<!-- end .container -->
	</section>

	<?if($GLOBALS["VJWEB"]["ACCESS"] == "Y"):?>
	<form id="form_answer" class="tender_answer_form" action="javascript:void(0);" method="post" style="display:none;" onsubmit="vjweb_SendForm('form', 'answer_form')">
		<div class="container">
			<div class="tender_answer_form_hold">
				<h4 class="h4"><?=GetMessage("VJWEB_RESPONSE_TENDER")?></h4>
				<textarea name="text"></textarea>
				<div class="clearfix">
					<input type="file" class="outtaHere inputfile" id="upload"
						   data-multiple-caption="{count} files selected" multiple/>
					<div class="vjweb_hidden">
					<input name="CHR" value="" type="text">
					</div>
					<label class="btn btn_upload" for="upload"><span><?=GetMessage("VJWEB_ATTACH_FILE")?></span></label>
					<button class="btn btn_red_big"><?=GetMessage("VJWEB_RESPONSE")?></button>
				</div>
				<!-- end .clearfix -->
			</div>
			<!-- end .tender_answer_form_hold -->
		</div>
		<!-- end .container -->
	</form>
	<?endif;?>
</section>

<script>
var files;
BX.ready(function(){
	$('input[type=file]').change(function(){
		files = this.files;
		console.log(files);
	});
});

function vjweb_SendForm(formId, action) {

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

	var fd = new FormData();
	if(isNumeric(formId)){

		fd.append('id', formId);
		fd.append('action', action);

	}else{
		var text = $('textarea[name=text]').val();
		var tenderId = $('#tender').attr('data-tenderid');
		var idAnswer = $('form.tender_answer_form').attr('data-idAnswer');
		var idUser = $('form.tender_answer_form').attr('data-idUser');

		fd.append('text', text);
		fd.append('id', idAnswer);
		fd.append('idSec', '<?=$arParams[VJWEB_COMMENTS_IBLOCK_ID]?>');
		fd.append('tenderId', tenderId);
		fd.append('idUser', idUser);
		// загрузка файла
		fd.append('file', $('input[type=file]')[0].files[0]);
	}

$.ajax({
  type: 'POST',
  url: '<?=$ajaxPath?>',
  data: fd,
  processData: false,
  contentType: false,
  dataType: "html",
  success: function(data) {
			alert(data);
		$('#form_answer').trigger("reset");
		$('#form_answer').hide();
		location.reload();
  },
  error: function(data) {
    console.log(data);
  }
});

}
</script>
BX.ready(function(){
/*
//передаем нажатие кнопки на прикрепление
$('.btn_upload').on('click', function () {
	$('input#upload')[0].click();
});

*/
$("a.answer_comm").click(function(event) {
    event.preventDefault();

	var idAnswer = $(this).attr('data-idAnswer');
	var idUser = $(this).attr('data-idUser');
	$('form.tender_answer_form').show().attr('data-idAnswer', idAnswer).attr('data-idUser', idUser);

	//анимируем переход
	var id  = $(this).attr('href'),
	top = $(id).offset().top;
	$('body,html').animate({scrollTop: top-50}, 1500);

});
});
<?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/prolog_before.php");

if(empty($_POST["CHR"]) && !empty($_POST["id"])){

global $USER;
	if(CModule::IncludeModule("iblock")){
		if(array_key_exists('action',$_POST)){

			$PROPERTY_VALUE = $_POST["action"];
			$ELEMENT_ID = $_POST["id"];  // код элемента
			$PROPERTY_CODE = "STATUS";  // код свойства
			// Установим новое значение для данного свойства данного элемента
			CIBlockElement::SetPropertyValuesEx($ELEMENT_ID, false, array($PROPERTY_CODE => $PROPERTY_VALUE));

			if($_POST["action"] == 13) echo 'Назначен кандидатом';
			if($_POST["action"] == 11) echo 'Назначен исполнителем';
		}else{

		$arFilter = array("ID" => $USER->GetID());
		
		$arRes = CUser::GetList($by,$desc,$arFilter,$arParams);
		if ($res = $arRes->Fetch()) {}

		$name = $res[NAME].' '.$res[LAST_NAME];
		$text = iconv("UTF-8", "WINDOWS-1251", $_POST[text]);

		$el = new CIBlockElement;
		$PROP = array();
		$PROP[65] = $res[ID];  // свойству с кодом 65 присваиваем значение "ID"
		$PROP[64] = $_POST[tenderId];
		$PROP[69] = $_POST[id];
		if($_FILES[file])$PROP[66] = $_FILES[file]; // прикрепляем файл

		$arLoadProductArray = Array(
			"IBLOCK_ID"      => $_POST[idSec],
			"NAME"           => $name,
			"PREVIEW_TEXT"   => $text,
  			"PROPERTY_VALUES"=> $PROP,
			"ACTIVE"         => "Y",  
		);

		if($PRODUT_ID = $el->Add($arLoadProductArray)){
			echo "ok";
		}else{
			echo "Error: ".$el->LAST_ERROR;
		}

			print_r($_POST);
		}
	}
}