var SendMessageForm = function(formid,fn_ok,fn_err){ console.log("Got form id"); form = document.getElementById(formid); form.addEventListener('submit', function(e){ e.preventDefault(); fields = ['contact_name','contact_phone','contact_message','contact_sendmsg'] if(data = validate(fields.slice(0,3))){ disable(fields,true); data['hkey'] = '855f938d67b52b5a7eb124320a21a139'; data['chatid'] = form.elements.namedItem('chatid').value; ajax({ method: 'POST', url: '/sendmessage/send', payload: data }).then(result =>{ if( result['status'] == 'error' ) { fn_err(result['error']); return; } fn_ok(); }).catch(err=>{ console.log(err); fn_err("Script processing error"); }); } }); function disable(f,d){ for(i in f ){ document.getElementById(f[i]).disabled = d; } } function validate(f){ fields = ['contact_name','contact_phone','contact_message']; data = {} for(i in f ){ el = document.getElementById(f[i]); console.log(el); console.log(el.value); el.parentNode.classList.remove("error"); if( el.value == "" ){ el.parentNode.classList.add("error"); el.focus(); el.scrollIntoView(); return false; } data[f[i]] = el.value; }; return data; } const ajax = async (config) => { const request = await fetch(config.url, { method: config.method, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(config.payload) }); response = await request.json(); return await response } }