Forum Posts

Salman2301
Dec 16, 2020
In Wix code Advance
Wix release the new wix-realtime which allow developers to build interactive apps like chat app, multi-player game etc. So, In this example i will discuss how we can build a chat app where a user can send a message to person B and person B immediatly get the message. If you want to test it live here is the link: https://test.salman2301.com Overview Front-end we use custom element, which allows to show the message side by side and also with custome element, we can have a fix height and scroll bar so user can scroll to previous messages. We can use repeater for this but we need to use pagination or infinite scrolling which is why i didn't. On the Backend, we use wix-realtime API with datahook - datahook runs the code when a new row is inserted in the database. - realtime API allow us to do pub/sub ( publish/ subscriber) where sender or publisher send message to a channel and the reciever or subscriber can reciver the message. Dataflow If a user Person A send a message to Person B, the message will be inserted in the database and this runs the afterInsert data hook and the data hook use realtime api to publish to a channel, the name of the channel is same as the Person B user id. In this way, only the person B recieve the message and On the front-end, let's assume that the person B is online and we subscribe to the channel and the name of the channel Is the current user id. We get the user id from wix-user module wixUser.currentUser.id. Database Database Name: message Fields: field_key data from - USER_ID to - USER_ID message - Message Code // backend/data.js import {publish} from 'wix-realtime-backend'; // datahook runs when a new row is inserted in the database // item contains inserted row information { from: "uuid", to:"uuid", message:"hello"} export function message_afterInsert(item, context) { const { from, to, message, _id } = item; const channel = { name : to}; let data = {         message, from,          _id     };  // publish which take a channel name and data. publish(channel, data, {includePublisher: true}); return item; } // Page code import * as realtime from "wix-realtime"; import wixUsers from "wix-users"; import wixData from "wix-data"; import { getUsers, getMe } from "backend/getUsers.jsw"; let lastUserId, lastLoginEmail, lastPicture; let userId = wixUsers.currentUser.id; let owner; $w.onReady(function () { // $w('#dataset1').onReady(init);   init();   $w("#inSearch").onKeyPress((e) => {     setTimeout(() => { if (e.key === "Enter") filterMem(); if (e.key === "Escape") {         $w("#inSearch").value = "";         filterMem();        }     }, 40);   });   $w("#ChatElement").setAttribute( "append-msg",     JSON.stringify({       user: {         name: "salman",       },       msg: " Hello this is a test",       date: new Date().toISOString(),       isOwner: true,     })   );   getMe().then((data) => {     owner = data;   }); }); function init() { // wix real time const channel = { name: userId };   realtime.subscribe(channel, newMessage); // update UI   filterMem(); // events   $w("#repeaterUser").onItemReady(($item, itemData, i) => { let { loginEmail, picture } = itemData;     $item("#image1").src = picture;     $item("#textEmail").text = loginEmail;   });   $w("#containerUser").onClick((e) => {     switchUser(e.context.itemId);   });   $w("#btnSend").onClick(sendMessage);   $w("#inMessage").onKeyPress((e) => { const { ctrlKey, key } = e; if (key === "Enter" && !ctrlKey) {       sendMessage();     }   }); } async function filterMem() { let inMember = $w("#inSearch").value || undefined;   getUsers(inMember)     .then((data) => {       $w("#repeaterUser").data = data.items; if (!lastUserId) {         switchUser(data.items[0]._id);       }     })     .catch(console.error); } async function switchUser(toUserId) {   lastUserId = toUserId;   $w("#repeaterUser").onItemReady(($item, itemData, i) => { let { _id, loginEmail, picture } = itemData; if (_id === toUserId) {       $item("#imgCurrUser").show();       $w("#textHeadUser").text = `Connected to ${loginEmail}`;       lastLoginEmail = loginEmail;       lastPicture = picture;       refreshMsg();     } else {       $item("#imgCurrUser").hide();     }   }); } async function newMessage({ payload }) {   appendMsg(payload._id); } async function refreshMsg() {   $w("#ChatElement").setAttribute("messages", "[]"); let resMsgs = await wixData     .query("message")     .eq("from", userId)     .eq("to", lastUserId)     .or(wixData.query("message").eq("from", lastUserId).eq("to", userId))     .ascending("_createdDate")     .find(); let msg = resMsgs.items; let username = lastLoginEmail.split("@")[0];   msg = msg.map((el) => { let isOwner = userId === el.from; let userImage = isOwner ? owner.picture : lastPicture;     userImage = encodeURI(userImage); if (!userImage.startsWith("https://")) userImage = undefined; return {       _id: el._id,       isOwner: isOwner,       user: {         name: username,         image: userImage,       },       msg: el.message,       date: el._createdDate,       data: el,     };   });   $w("#ChatElement").setAttribute("messages", JSON.stringify(msg)); if (msg.length === 0) {     $w("#textNoMsg").show();   } else {     $w("#textNoMsg").hide();   } } async function appendMsg(msgId) { let resMsgs = await wixData.query("message").eq("_id", msgId).find(); let message = resMsgs.items[0];   console.log({ resMsgs }); let username = lastLoginEmail.split("@")[0]; let isOwner = userId === message.from; let userImage = isOwner ? owner.picture : lastPicture;   userImage = encodeURI(userImage); if (!userImage.startsWith("https://")) userImage = undefined; let msg = {     _id: message._id,     isOwner: isOwner,     user: {       name: username,       image: userImage,     },     msg: message.message,     date: message._createdDate,     data: message,   }; if (!(lastUserId === message.from || lastUserId === message.to)) {     console.error(" No for the current user show alert!"); return;   }   $w("#ChatElement").setAttribute("append-msg", JSON.stringify(msg)); } async function sendMessage() { try {     $w("#btnSend").disable(); let msg = $w("#inMessage").value; if (!msg) return; let toInsert = {       from: userId,       to: lastUserId,       message: msg,     }; let inserted = await wixData.insert("message", toInsert);     appendMsg(inserted._id);     $w("#btnSend").enable();     $w("#inMessage").value = "";   } catch (e) {     console.log("ERROR : ", e.message);     $w("#btnSend").enable();     $w("#inMessage").value = "";   } } For the custome element check my github https://github.com/Salman2301/wix-chat-component
2
2
173
Salman2301
Jun 12, 2020
In Wix code Advance
This post is to demo, how to add a alert at the side of the screen? Prerequisite This only work in domain connected premium wix site To test the app live goto https://www.test.salman2301.com/alert-web-component Check the video to quick demo For now the alert can only be trigger via code You can trigger the alert, in just few lines. Three steps 1) Add a Custom element 2) Add the Alert wix block to the site 3) Use code to trigger the app 1) Add a Custom element 1. Click on the add icon 2. Select Embed 3. Drag and Drop Custom element Setup custom element Click on the Custom element Select Choose Source Select Server URL for "Add your script file with:" Copy and paste the below URL for Server URL https://cdn.jsdelivr.net/gh/salman2301/wix-alert-component@master/dist/index.js Copy and paste "alerts-component" Tag Name Change the Custom element id to "CustomAlert" 2) Add the Alert wix block to the site 1) Click on this link -> http://wix.to/QcCAC7M 2) It will redirect to select the website to add, Select the site (see image below) 3) Select "I Understand" checkbox and click on "Confirm and Install"(see image below) 4) Now you can add from (+) > my Widget > "alertBySalman2301"(see image below) 5) Once the element is added to the page, Change the element ID to "widgetAlert" from propert panel 3) Use code to trigger the app : We Use code to trigger the alert to show a default alert // show alert $w('#widgetAlert').alert("Your Alert message here!" ) If you want to customise it, you can pass the Object {} instead of string //alert option, see below for more options let alertOption = { title: "Form failed", message: "Form didn't submit please try again" } // pass the alert options $w('#widgetAlert').alert(alertOption); Available Alert options, not only message is required property { // required field, message display in the alert message : "Alert message!.", // set color of alert based on success type:"success", // "error" | "info" | "warn"|"success" // if it's false, user need to click on the close button autoClose : true, // you can also use any word e.g: "ACTION"| "Yes"|"No" closeLabel : "X", // wait for 8 sec before autoClose, if it's set to true wait : 8, // custom css style style:"", // callback function trigger on autoClose or button click onClose: function(){}, // callback function trigger on button click onAction: function(){}, // brandColor set any hex, rgb color, refeclt the border brandColor:"#4BB543", // redirect url on title or message clicked! knowMoreUrl: "https://salman2301.com" } You can goto the below URL to test the app https://www.test.salman2301.com/alert-web-component // You can either pass string or object // you can call any of the following property to show the alert // if you want to customise it, set more time or call for action // instead of string pass the object with the configuration $w('#widgetAlert').alert("your alert message"); $w('#widgetAlert').alertError("your alert message"); $w('#widgetAlert').alertWarn("your alert message"); $w('#widgetAlert').alertInfo("your alert message"); $w('#widgetAlert').alertSuccess("your alert message"); Note : to Use Alert up you need to select and set the custom element Just add this line to set the custom element on page ready $w('#widgetAlert').setCustomElement($w('#CustomAlert')); Demo Code snippet : Let's show an warning on button click // wait for page ready $w.onReady(function () { // connect the web component with wix block $w('#widgetAlert').setCustomElement($w('#CustomAlert')); // add a button $w('#button2').onClick(()=>{ // show alert warning with message on click $w('#widgetAlert').alertWarn("Warning button is clicked!!" ) }); }); So, with just two line of code you can show the alert message Protip : If you are gonna use the alert app in multiple pages Right click the web component and select show on all page switch Also do the same for the Custom element. Now on the site page, connect the wix block and site element // wait for page ready $w.onReady(function () { // connect the web component with wix block $w('#widgetAlert').setCustomElement($w('#CustomAlert')); }); and on any page code call call the method ( alert | alertError | alertWarn | alertSuccess ) with the string or object $w('#widgetAlert').alert("Alert message here!!" ) Links Test Link - https://www.test.salman2301.com/alert-web-component Github Link - https://github.com/Salman2301/wix-alert-component Custom element - https://www.wix.com/corvid/reference/$w.CustomElement.html That's it, if you encounter any issue feel free to message me via salmanhammed77@gmail.com Happy Coding!
Wix Alert Web App content media
0
3
246
Salman2301
Feb 23, 2019
In Code Snippets
Check the tag of post #public or #backend If it's public Create a public .js file in your Wix account Name it as a "template.js" copy the main code function fullName(firstName, lastName){ return firstName + ' ' + lastName } and past it on template.js Final Public file //in template.js export function fullName(firstName, lastName){ return firstName + ' ' + lastName } Now you can reuse this function in any page Just by importing the module name import { fullName } from 'public/template'; // general import syntax import { moduleName } from 'public/filename.js'; Let say we have 2 input element with first name and last name After a button click We will show the full name in a text Final Page code //Importing module from template js file import { fullName } from 'public/template' $w.onReady(()=>{ $w('#btn').onClick(()=>{ let firstName = $w('#inFirstName').value; let lastName = $w('#inLastName').value; //Calling the module $w('#textDisplayFullName').text = fullName(firstName, lastName); }) }); - inFirstName - id of an input element - inLastName - id of an input element - textDisplayFullName - id of text element - btn - id of a button element
0
0
109
Salman2301
Dec 11, 2018
In Wix code Advance
Send a template email to a client using sendgrid npm and Wix code under 20 lines of code. https://salman2301.wixsite.com/npmsendgrid Requirements 1. Sendgrid account i) Sendgrid Sign up for sendgrid account > select "transactional" option under "Templates" Click on the "Create Template" button on top right. Type the name, Click the "Save" button. Click "Add version" select "Design Editor" and Select "Continue" Design the email using Drag and Drop options To create a variable you need to use two open and close brackets {{name}} One of helpful thing is we can test the email using test Data. To do this goto Preview mode in the email editor then click on the "Show Test Data" Copy the template id under "Transactional Template" Get the API KEY on setting > API Keys Click on the Create API Key and get the KEY ii) Wix code Create a form. (No code required) Check this video how to create a form submission using dataset in Wix code I have created a Database "form" which then i am going to use ""hook" hook - hook will trigger the backend code based on the changes in the Database like insert, update, etc. To create a hook select the Database the on the top right select "Add hook" then add "After Insert" So, everytime if the data is inserted in the DB the code will be triggered on the "event.js" backend code Before adding the code in the backend Install the Npm Click on the plus icon on the backend side bar and select "Install Node Package" And search and install "@sendgrid/mail" npm To know more about the npm click here Open the "event.js" backend now and paste the code import sgMail from '@sendgrid/mail'; export function Form_afterInsert(item, context) { sgMail.setApiKey('<API KEY>') const msg = { to: item.email, from: 'salmanhammed77@gmail.com', templateId: '<TEMPLATE ID>', dynamic_template_data: { name: item.title, email: item.email, detail: item.detail, }, }; sgMail.send(msg); } Replace the <API KEY> , <TEMPLATE ID> and the variable on the dynamic_template_data Test the live site
Send a template email using sendgrid npm and wix code content media
0
1
137
Salman2301
Dec 07, 2018
In Wix code Advance
Check this link - https://salman2301.wixsite.com/wix-store-search Four elements used to create a simple search bar 1. Input element Input element property Id is "inSearch" Uncheck "Enabled by default" on the properties panel 2. Text to display the status Text property Id is "textResult" Check "collapsed on load" on the properties panel 3. Vector Image to close the searched results Vector Image property Id is "vectorImageClose" Check "collapsed on load" on the properties panel 4. Repeater to display the searched result Repeater property id is "repeater1" Container property id is "container1" Check "collapsed on load" on the properties panel Inside repeater there are four element (ie. For each container there are four element) i). Image to display the product Image property name is "imagePro" ii). Text to display the property name Text property name is "textProName" iii). Text to display the description Text property name is "textProDetail" Check "collapsed on load" on the properties panel (The max character to show is 40, so if the character is more than 40 the the text will be cut and add "..." dots at the end) iv). Vector Image to shows arrow Vector Image property name is "vectorImg" Paste the code in the "site" page Attach the input element on the header And rest of the elements just below the input element not on the header Right click the element and select to "show on All pages" to display it on all page import wixData from 'wix-data'; import wixLocation from 'wix-location'; //Salman2301 //Limit controls the maximum number of searched result to show let limit = 10; //maximum character the can be displayed for the search details let maxChara = 40; $w.onReady(function () { wixData.query('Stores/Products') .ascending('name') .limit(limit) .find() .then(res => { $w('#inSearch').enable(); $w('#repeater1').data = res.items; $w('#inSearch').onFocus(() => { $w('#repeater1').expand(); $w('#vectorImageClose').expand() }); $w('#inSearch').onMouseIn(() => { $w('#repeater1').expand(); $w('#vectorImageClose').expand(); }); $w('#vectorImageClose').onClick(() => { $w('#repeater1').collapse(); $w('#vectorImageClose').collapse(); }); $w('#repeater1').onMouseOut(() => { // $w('#repeater1').collapse(); }); }); $w('#repeater1').onItemReady(($item, itemData, i) => { // console.log(itemData) $item('#textProName').text = itemData.name; $item('#imagePro').src = itemData.mediaItems[0].src; let des = itemData.description; if (des.length > maxChara) { des = des.slice(0, maxChara) + '...'; } $item('#textProDetail').text = des; $item('#container1').onClick(() => { wixLocation.to(itemData.productPageUrl); $w('#repeater1').collapse(); }); $item('#container1').onMouseIn(() => { $item('#textProDetail').expand(); $item('#vectorImg').show() }); $item('#container1').onMouseOut(() => { $item('#textProDetail').collapse(); $item('#vectorImg').hide(); }); }); let query; $w('#inSearch').onKeyPress(async () => { setTimeout(async () => { let search = $w('#inSearch').value; console.log(search) if (search) { $w('#textResult').text = 'Searching for ' + search + ' ...'; $w('#textResult').expand(); let res = await wixData.query('Stores/Products').ascending('name').contains('name', search).or(wixData.query('Stores/Products').contains('description', search)).limit(limit).find() $w('#textResult').text = res.items.length + ' result has found!'; console.log(res.items.length) $w('#repeater1').data = res.items; $w('#vectorImageClose').expand(); if (res.length === 0) { $w('#textResult').text = 'No result found for ' + search; $w('#textResult').expand(); $w('#vectorImageClose').collapse(); } } else { console.log('No value') } }, 200) }); }); Property names Check this link - https://salman2301.wixsite.com/wix-store-search There are bugs we can fix it if you updated the code let me know in the comment section.
Wix store search bar! using wix code content media
0
4
84
Salman2301
Dec 05, 2018
In Code Snippets
There is a popular Wix code snippet most of the Wix code community uses thanks to Nayeli and Totally codeable platform but the problem started is when the code is repeatedly use. Why you shouldn't repeat the code? What is DRY(Don't Repeat Yourself)? 1. It will be easy to maintain the code. 2. Improve the performance of the site To know more about the uses of DRY, Check this thread from stack exchange In this example you can set the dropdown options as many you want just adding one more line ( Without rewriting the whole function again )with the detail about the collection name , dropdownPropertyId and the column (filed Key) of that database uniqueDropdown('DatabaseName1' , 'dropdown2' , 'fieldKey'); Youtube link - Conditional Filtering Dropdowns Wix Code Example #WIXCODE #TOTALLYCODEABLE #DROPDOWN
1
1
236
Salman2301
Nov 30, 2018
In Wix code Advance
A PDF is created and downloaded when the user submited a form. Usage: Create a Invoice, Create a certificate for the user etc. on form submission. Sample Website link Requirement: 1. Free account in pdfgeneratorapi Overall Layout:i) PDF GENERATOR API ii) Wix code Backend (npm - pdf-generator-api) iii)Page Code iv) HTML Embed code (Convert Base64 into PDF file) i) PDF GENERATOR API1. Goto pdfgeneratorapi 2. Sign In and goto Dashboard 3. Select the "Template" on the left side bar 4. Click on the "New Template" button, A new window open to edit the pdf File 5. Design the PDF and to create a variable use open and close Curly brackets as shown on this image [This is a image of the pdf generator Editor {Name} where the variable will be later assign using wix code And there is one more variable,{Detail} to add the message] 6. Publish the template and Goto the "Templates" from the Dashboard 7. Copy the Template Id from the "Templates" 8. Copy the APIKey and APISecret from the "Account Settings" 9. Copy the WorkSpace Identifier from the "Admin Panel" ii) Wix code Backend 1. Search and Install "pdf-generator-api" npm (Check this link for Installation guide and Node package manager npm) 2. Create a Backend Web Module "pdf.jsw". 3. Copy and paste the code import PDFGeneratorAPI from 'pdf-generator-api'; export async function pdf(name, detail) { let Client = new PDFGeneratorAPI( '<APIkey>', '<APISecrect>' ); Client.setWorkspace('<WorkSpace identifier>'); let obj = { "Name" : name, "Detail" : detail, } let response = await Client.output('<Template Id>', obj) return response.response } 4. Replace the <APIkey> , <APISecrect> , <WorkSpace identifier> and <Template Id> to your corresponding value grab from the pdfgeneratorapi site 5. Create a object for the variable in this case i have create an object "obj" with two Key "Name" and "Detail" and the corresponding value directly from the parameter of this async function "name" and "detail" iii)Page Code1. Drag and drop Input element, Text box element and Button in a new page 2. Also Drag and drop the "HTML embed" element from "more" section 3. Change the Property name as shown in the image 4. Copy and paste the below code import { pdf } from 'backend/pdf.jsw'; $w.onReady(function () { var base64; $w('#btnSubmit').onClick(() => { let name = $w('#inName').value; let detail = $w('#inDetail').value; pdf(name, detail).then(e => { base64 = e; base64 = 'data:application/pdf;base64,' + base64 let msg = { "conv": true, "dataUrl": base64 } $w('#html1').postMessage(msg); }); }); }); iv) HTML Embed code1. Click on the HTML embed element 2. Click on "Edit code" button 3. Paste the following code [updated 02-dec-2018] <script> window.onmessage = event => { if(event.data.conv) { if(document.getElementById('Download') === null || document.getElementById('Download') === undefined){ var pn = document.createElement('a') pn.download = 'Download.pdf'; pn.title = 'Download pdf document'; pn.textContent = 'Download'; pn.id ='Download' var s = document.getElementsByTagName('body')[0].appendChild(pn); pn.href = event.data.dataUrl; } else { let d = document.getElementById('Download') d.href = event.data.dataUrl; } document.getElementById('Download').click() } } </script> Overall codes Congrats! That's it Test this site right here #npm #wixcode
Create PDF using Wix code and pdf-generator-api content media
3
56
3k
Salman2301
Nov 30, 2018
In Wix code Advance
It’s good to have you here! Feel free to share anything - ideas, Code snippet or whatever is on your mind. Here you can start discussions, connect with members, reply to comments, and more. Have something to say? Leave a comment or share a post!
2
2
23

Salman2301

Admin
More actions