If you have used WhatsApp Web, you may encounter a situation where if you open the web.whatsapp.com in multiple tabs in the same browser, you will get the error that “it is already being opened in another tab”. So in this article, we are going to teach you how you can detect multiple tabs opened at the same time using vanilla Javascript.
This is done for various reasons, top of the most is security. So how you can add this feature to your website ? The following code will display an alert message if a 2nd tab is opened at the same time:
<script>
// Broadcast that you're opening a page.
localStorage.openpages = Date.now();
window.addEventListener('storage', function (e) {
if(e.key == "openpages") {
// Listen if anybody else is opening the same page!
localStorage.page_available = Date.now();
}
if(e.key == "page_available") {
alert("One more page already open");
}
}, false);
</script>
“window.addEventListener(‘storage’, function (e) {});” This listener will be called only when the local storage value is updated from an external source, which means the other tab has made any changes in the local storage.
[do_widget id=custom_html-4]
How it works:
You might need to read the following steps 2 or 3 times to grab the concept properly.
When you open the 1st tab, line # 3 will create a local storage value named “openpages”.
Storage listener will NOT be called because the local storage value is updated from this tab.
When you open the second tab, line # 3 will also create a local storage value named “openpages”.
Storage listener from the 1st tab will be called because the local storage is updated from the 2nd tab.
1st tab will receive the value of “e.key” as “openpages”.
So it will create another local storage value “page_available” at line # 7.
Now this will call the storage listener from the 2nd tab. Because for the 2nd tab, it is called from the 1st tab.
2nd tab will receive the value of “e.key” as “page_available”, so it will display an alert message.
That’s how you can detect multiple tabs opened by the user at the same time. Let me know if you have any problem understanding this.
Either you are sending an email in Laravel via normal form POST request or via AJAX. This tutorial will help you add functionality where you can preview Laravel email before sending it. If you are adding functionality to your Laravel project where you need to send an email, it is very important during the development to check the preview of mail before sending.
Normally, when you receive the email in your inbox, you can see how it will look to users. But if you haven’t set up your SMTP server for sending emails, then following this tutorial will save you a lot of time during development.
Create a new Laravel project
To create a new Laravel project, open your command prompt or Terminal and run the following command in it:
This will create a folder named “example-app”. Now, you need to enter this folder using the following command:
cd example-app
When your Terminal is inside this folder, run the following command to start the server:
php artisan serve
Typically, this starts your project at host 127.0.0.1 and port 8000. So you can access it from the URL:
http://127.0.0.1:8000
Create controller and mailer
Create a new controller using the following command, you can also use your own controller if you want:
php artisan make:controller UserController
Now, open your “routes/web.php” file and create a new route:
// include controller
use App\Http\Controllers\UserController;
// create route
Route::get("/send-mail", [UserController::class, "send_mail"]);
Create a mailer to send mails by running the following command in your Terminal:
php artisan make:mail SendMail
Now, we need to create the following function in “App\Http\Controllers\UserController”:
use Mail;
use App\Mail\SendMail;
class UserController extends Controller
{
// create method
public function send_mail()
{
// send email
// preview with dynamic variable data
$data = "This is a variable.";
// pass as a parameter
$mailable = new SendMail($data);
// Mail::to("recipient@gmail.com")->send($mailable);
// preview email
return $mailable->render();
}
}
Following will be the content of your “App\Mail\SendMail”. You can add all the variables you want to pass in this mailer:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendMail extends Mailable
{
use Queueable, SerializesModels;
// class data member
public $data;
/**
* Create a new message instance.
*
* @return void
*/
// parametrized constructor
public function __construct($data)
{
// assign value
$this->data = $data;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
// create this folder mails
// and file test.blade.php
// pass value in view
return $this->view('mails/test', [
"data" => $this->data
]);
}
}
At line #40, we need to create a new file in views folder, “resources/views/mails/test.blade.php” and in this file you can write the content of your email. For the sake of understanding, I am writing simple text with variables:
<h1>This is mail:</h1>
<!-- display in mail view -->
Data = {{ $data }}
If you access your browser at “http://127.0.0.1:8000/send-mail”, you will see the content of email with all variables rendered on it.
Preview email from AJAX
If you are sending an email via an AJAX request, then it might be difficult for you during the development to check how the email will look like. You might be sending an email on each test and viewing it from your Gmail inbox to preview the email. But there is a shorter method to do that, and it will surely save your time.
First, create a new route that will render a view file.
Create a file named “send_mail_ajax.blade.php” inside the “resources/views” folder and paste the following code into it:
<!-- meta tag for CSRF token -->
<meta name="_token" content="{{ csrf_token() }}">
<!-- hidden input field for base url -->
<input type="hidden" id="base_url" value="{{ url('/') }}" />
<!-- send ajax -->
<script>
var ajax = new XMLHttpRequest();
ajax.open("POST", document.getElementById("base_url").value + "/send-mail-ajax", true);
// when the response is received
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
// display in browser
document.write(this.responseText);
}
// handler error
if (this.status == 500) {
console.log(this.responseText);
}
}
};
var formData = new FormData();
formData.append("_token", document.querySelector("meta[name=_token]").content);
ajax.send(formData);
</script>
We have created a meta tag for saving CSRF token which is required for each POST request in Laravel, and a hidden input field that will save the website’s base URL. Then we are sending an AJAX request, and when the response is successfully received then we are displaying that in current web page.
Don’t worry, it will be used just during the development process. Once it is reviewed, then you can comment out that code at line #17.
Create a POST route in “routes/web.php” and it will use the same method in UserController, only the method is set to POST:
Try to access the URL at “http://127.0.0.1:8000/send-mail-ajax”, you will first view an empty page then after few seconds, you will see the content of email in your web page.
Let me know if you need any help in following this tutorial.
A Laravel blog website along with an Android app is created with an admin panel. It uses the design template from https://bootstrapmade.com/. It has the following key features:
Google Adsense approved
The project is tested with Google Adsense and it was approved by Google for monetization. You just have to link with your Google account and you will start receiving money once you reach the Google payment threshold.
User side
70 built-in blog posts.
Random quotations.
Total users display.
Custom advertisement to generate revenue.
Share posts on Twitter and Facebook.
Limit access to some features for registered users only.
Registration with Email Verification.
Secure Login.
Comment on Post.
Reply to the comment.
Related Posts.
Subscribe to the newsletter.
Social Links.
A section to sell items directly.
Amazon affiliate links.
Realtime Chat with admin (Firebase).
Manage Profile.
Change Password.
Custom Advertisement.
Admin panel
Dashboard Statistics.
Add/Edit blog posts.
Add/Edit items that sell directly.
Manage Inbox.
Manage Comments.
Realtime Chat with users (Firebase).
Android app
We also developed an Android App for this project which your users can download from Google Play Store and read your blog posts from that app. Here is the demo of the Laravel blog android app:
In this article, we are going to teach you how you can create a real-time customer support chat widget on your website. Users will be able to chat with the admin and get instant replies. All messages will be stored in the MySQL database.
By real-time, we mean that users or admins do not have to refresh the page to see new messages. Also, the admin will be able to view the navigation history of the user. For example, how many and which pages the user has visited, what was the last page the user has visited etc.
Tutorial:
Source code:
After buying this project, you will get the complete source code and use it in as many websites as you want.
In this article, we will teach you how to create a feedback pop-up bootstrap modal for users on the bottom right of the screen when the page is fully loaded. The pop-up modal will be created in bootstrap and will display a star rating and an input field to get the user’s feedback. Once submitted, it will display a thank you message and the user’s feedback will be saved in a database along with his IP address and browser information. If you are working on localhost, you might see the IP address as ::1. Don’t worry about it, on the live server it will save the actual IP address of the user.
Once the feedback is sent, the user will not see that pop-up again. If the user changes the browser or visits the site after a long time, then he will see that pop-up again.
Download jQuery, bootstrap, and font-awesome
First, you need to download jquery, bootstrap, and font-awesome. You can download all of them from the attachment below. Paste the CSS and JS files of bootstrap into your project. You may also need to copy-paste the jQuery JS file as well. Make sure to copy the font awesome fonts and CSS file as well.
Now you need to include these files in your project. Create <link> tag for adding CSS files and <script> tag for adding JS files.
Refresh the page, and if you did not see any error in the browser’s console window, then it means that it is included correctly.
Feedback modal/pop-up
Now, create a bootstrap modal for feedback. Give your modal a unique ID that will be used to show and hide the modal programmatically. The modal will have a heading, and one button to close the modal. And a body, where we will create the form to get the feedback.
On form submit we will call an AJAX to save the feedback. A <div> to show stars, an input field to enter feedback in text, and a submit button. Right now, you will not see the stars, it will be done in the next section.
We need to show the modal on the bottom right, so apply some CSS styles to it.
This will give it some width for the form, set the position on the bottom right, and remove the margin from the bottom and right of the screen.
Star ratings (starrr)
Now, to create stars, we are going to use a library called starrr. Goto, this GitHub link to download the library and download it in your system. Inside this library, go to the distribution folder named dist and copy the CSS and JS files in your project’s CSS and JS folder separately. Now include its CSS and JS files and make sure to include the JS file after jQuery. I am putting it even after bootstrap JS.
If you still see the stars missing, even though you have included font-awesome in your project, it is because you need to initiate this library using Javascript.
var ratings = 0;
window.addEventListener("load", function () {
$(".starrr").starrr().on("starrr:change", function (event, value) {
ratings = value;
});
if (localStorage.getItem("feedback_1") == null) {
$("#feedbackModal").modal("show").on('hidden.bs.modal', function (e) {
localStorage.setItem("feedback_1", "1");
});
}
});
Setting the default value of ratings to 0. We will initiate the library when the page is fully loaded. When the user selects any star, we are going to save its value in the ratings variable. Now I need to show the modal automatically but only if the user has not given his feedback. So I will use local storage for this purpose. In line #8, I am checking if the local storage has feedback_1 value. If not, then I am going to show the modal, and when this modal is closed by the user, I am going to save the feedback_1 value in local storage. So next time the user visits this page, the feedback_1 value will be found in local storage, thus it will not show the modal pop-up.
Refresh the page and now you will see that a feedback pop-up, that is created via a bootstrap modal, will be displayed automatically.
Submit form using AJAX
Now, we need to create a Javascript function named saveFeedback() which will be called when the form is submitted. This function will create an AJAX object, set its method to POST, and URL to the page that will save the feedback, and make the request asynchronous.
Then attach an event that will be called whenever the state of request is changed. The ready state will be 4 when the request is completed and a response is received. The status will be 200 if the response was OK and there was no error. You can simply show the response sent from the server using the responseText property. Then show the thank you message in the modal pop-up, and save the value in local storage.
If the request’s status is 500, it means there is an internal server error. In that case, you can view the error using the responseText property. To send the AJAX request, you need to create a FormData object using your form and append the ratings variable value in it, and then send the request and attach the form data object to it. return false at the end of the function will prevent the form from submitting and refreshing the page.
function saveFeedback(form) {
var ajax = new XMLHttpRequest();
ajax.open("POST", "save-feedback.php", true);
ajax.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
console.log(this.responseText);
document.querySelector("#feedbackModal .modal-body").innerHTML = "Thank you for your feedback.";
localStorage.setItem("feedback_1", "1");
}
if (this.status == 500) {
console.log(this.responseText);
}
}
};
var formData = new FormData(form);
formData.append("ratings", ratings);
ajax.send(formData);
return false;
}
Handle AJAX request
Now create a server file named save-feedback.php that will handle this request. As the requests need to be saved in the database, so we need to create a table in our database. I am creating a table named feedbacks. It will have 6 columns (id, IP, browser, ratings, feedback, created_at). The first will be auto increment ID. The second is an IP address whose data type is TEXT. Third is browser information, also TEXT. The fourth is ratings” data type DOUBLE. Next is feedback, also TEXT. And finally, created_at will store the date and time when the feedback is sent and its data type will be DATETIME.
You can find the SQL file in the attachment below.
Save feedback in MySQL
First, connect with the database. My database name is “tests”. Then get ratings and feedback from the request. You can get the user’s IP address using the PHP built-in global $_SERVER variable, and the associative index will be REMOTE_ADDR. You can get the user’s browser information by calling a PHP built-in function named get_browser() and it has a property named browser_name_pattern. Then run the INSERT query to save the record in the database. MySQL has a built-in function named NOW() that will return the current date and time of the server. PHP echo will send the response back to the client.
Initially, the feedback table will be empty. When you refresh the page, give ratings using stars, enter feedback and hit submit button, then a “Thank you” message will be displayed. When the response is successfully received from the server, close the modal and check your “feedbacks” table using phpMyAdmin. You will see a new row created in the database. If you refresh the page again, you won’t be able to see this modal because you have already given your feedback. You can try it in another browser. The first time you will see the pop-up on the bottom right corner. Once feedback is given, then you will not see that pop-up again. And your ratings will be saved in the database.
That’s how you can create a bootstrap modal that will be used to collect feedback from the users using a pop-up.
In this article, I am going to teach you, how you can get the URL query parameter value in Javascript. You can easily get the URL parameter in PHP using PHP’s built-in global $_GET array and pass the associative index as the name of the parameter. But getting that value in Javascript is a bit tricky. So I am going to show you a method that is very simple and will always work.
Create a hidden input field.
Give it a unique ID so it can be accessible in Javascript.
Set its value as the variable you are receiving from the URL using the $_GET array.
Array index will be the name of the parameter as in the URL
Suppose, you are receiving a parameter named “data” in your URL.
Now, create a Javascript tag. You should execute all your Javascript code when the page is fully loaded. So, attach a “load” listener to the window object. You can also use the onload event but it will override the previous event. I have written a detailed post on the difference between onload event and “load” event listener.
window.addEventListener("load", function () {
var data = document.getElementById("data").value;
console.log(data);
});
The callback function in the second parameter of the addEventListener function will be called when the page is fully loaded. Now you simply need to get the value of this hidden input field using its ID and get the value attribute. I am logging the value of the data variable in the console.
Now, if you refresh the page then you will see this parameter (data) value in the console using Javascript. That’s how you can get the query parameter from the URL in your Javascript code.
WP Carousel Slider is a WordPress plugin developed by Sayful Islam. This plugin allows you to create carousel images in your blog post. You can display your media images, gallery, custom URLs, blog posts, or WooCommerce products in the carousel.
It works as sliders, so you need to create a new slider, and add images to that slider. A shortcode will be generated for each slider, you just need to place that shortcode in your post where you want to show the slider. Sliders created from this plugin can also be used as widgets.
In this article, I am going to discuss a solution to a problem that occurs when you try to add images with different heights in your slider under the following configurations:
Setting
Value
Carousel Image size
Original uploaded image
Auto Width
Disabled
Columns
1
Columns: Desktop
1
Columns: Small desktop
1
Columns: Tablet
1
Columns: Small tablet
1
Columns: Mobile
1
If you are using the above settings and if you upload the images with different heights in a slider, then you might see that slider has been given a height of the largest image which will create a lot of empty space at the bottom of the smaller height images.
Moreover, when you scroll between carousel items, the height of the carousel is not auto-adjusted. Let me explain how you can solve this.
Solution:
You need to make 1 change in the plugin file. When it comes to editing the plugin files, there are 2 options.
1. WordPress admin panel
From your WordPress admin panel, go to “Plugins > Plugin Editor” and select the “Carousel Slider” plugin. When this plugin is selected, go to the following path:
assets/js/frontend.js
2. File manager
If you prefer to use file manager instead of making the changes from the WordPress admin panel, then you need to go to the following path:
After replacing the above code, you need to refresh your browser cache in order to see the effect. Press the following keys to remove the browser cache:
Windows / Linux
ctrl + shift + delete
Mac
command (⌘) + shift + delete
When you hit the above keys, you will see a pop-up asking which data you want to delete. You will have 3 options and you need to check the “Cached files and images” option. Also, make sure to select “All time” from the “Time range” option.
Now refresh the post where you have placed the shortcode for the WP Carousel Slider plugin, and you will know that the carousel will adjust itself dynamically with the height of the currently active image.
When people use someone else’s computer and try to log in to their account on any website, they are afraid that the other person might have installed a Keylogging software that tracks all the keys pressed, and hence they will know his password. But if you show a custom keyboard view for a password field on your website, it will create a whole new level of confidence in users towards your website.
So let’s learn how you can do this.
This is what we are going to create:
First, you need to create a password field, you probably also have a username or email field as well.
We have written the normal key in the <span> tag and the shift key directly in <td>. Also, we have given data-shift and data-initial attribute so we can know which character to use when the shift key is pressed and which character to use when the shift key is released.
1st row (QWERTY):
This will be the very first row on your keyboard. You can compare it with your keyboard. Create a new <tr> tag in your table:
It also has data-shift and data-initial attributes that tell that the character will be uppercase when the shift key is pressed, and lowercase when the shift key is released.
2nd row (ASDF):
Similarly, we are going to create a second row of the keyboard.
This will make your keyboard look nice and readable.
Javascript
The real power of this keyboard view comes with Javascript. Following is the complete Javascript code that will make this static keyboard view functional.
var isShift = false;
window.addEventListener("load", function () {
var tds = document.querySelectorAll(".keyboard td");
for (var a = 0; a < tds.length; a++) {
tds[a].addEventListener("click", function () {
/* get key node */
var node = this.querySelector("span");
if (node == null) {
return;
}
if (node.innerHTML == "delete") {
simulateBackspace(document.getElementById("password"));
} else if (node.innerHTML == "shift") {
/* toggle the isShift variable */
isShift = !isShift;
toggleShift();
} else {
/* check if it is an alphabet */
if ((/[a-zA-Z]/).test(node.innerHTML)) {
document.getElementById("password").value += node.innerHTML;
} else {
/* show initial value if the shift is off.
* show shift value if shift is on. */
if (isShift) {
document.getElementById("password").value += node.getAttribute("data-shift");
} else {
document.getElementById("password").value += node.getAttribute("data-initial");
}
}
if (isShift) {
isShift = false;
toggleShift();
}
}
});
}
});
function toggleShift() {
/* make all alphabets capital or small based on new isShift value */
var keys = document.querySelectorAll(".keyboard span");
for (var b = 0; b < keys.length; b++) {
/* keys must not be shift or delete */
if (keys[b].innerHTML != "shift" && keys[b].innerHTML != "delete" && keys[b].innerHTML != "") {
/* check if it is an alphabet */
if ((/[a-zA-Z]/).test(keys[b].innerHTML)) {
if (isShift) {
keys[b].innerHTML = keys[b].innerHTML.toUpperCase();
} else {
keys[b].innerHTML = keys[b].innerHTML.toLowerCase();
}
}
}
}
/* highlight the shift button if on. */
if (isShift) {
document.getElementById("key-shift").className = "active";
} else {
document.getElementById("key-shift").className = "";
}
}
function simulateBackspace(element) {
var start = element.selectionStart, end = element.selectionEnd, event;
if (!element.setRangeText) { return; }
if (start >= end) {
if (start <= 0 || !element.setSelectionRange) { return; }
element.setSelectionRange(start - 1, start);
}
element.setRangeText("");
event = document.createEvent("HTMLEvents");
event.initEvent("input", true, false);
element.dispatchEvent(event);
}
That’s how you can create a fully functional custom numeric keyboard view. Comments have been added with each line for an explanation. You can customize this as much as you want. If you face any problems feel free to ask in the comment section below.
Whether you are creating an E-commerce website or simply wanted to receive payments from your website using PayPal and Stripe, this script already contains all the source code you need to show Stripe and PayPal payment buttons and receive payments directly in your Stripe and PayPal accounts.
It also has a full shopping cart implementation, where you can add products to the cart, update quantities, remove products from the cart and move to checkout.
Demo
Home page
Here you can add products to the shopping cart and also you can remove products from the shopping cart.
When you add or remove a product from the shopping cart, you will see the shopping cart badge on top updating its values in real-time.
Shopping cart
On clicking the above “Cart” button you will be redirected to the shopping cart page where you can change the number of products and can also remove the product from the shopping cart.
You can also see the grand total at the bottom right that changes in real-time as you change the quantity of product or when you remove a product from the shopping cart.
Checkout
Here you can make the payment using Stripe or Paypal.
Fully documented code
Comments have been added with each line of code for explanation.
Separate file for each function
To manage the code, each payment method is separated in its own file. So you can easily change and modify the code as per your needs.
Suppose you have a form in your Laravel project that when submit sends the data to the server for processing. But when the form is submitted, your browser has to refresh the whole page which means that it needs to load all the CSS, JS, and image files again and also render all the HTML in the browser again. So you need to convert this POST request into an AJAX request to prevent the page from reloading.
I am using a form with a text field and an input type file so you can know how to send an image in an AJAX request.
CSRF field is required in Laravel for POST requests. onsubmit event is attached to the form and it will call a Javascript function to send an AJAX request. Now we need to create that function in Javascript that will send an AJAX request to the server along with all the data in the form:
<script>
// create function in Javascript
function onsubmitForm(form) {
// create AJAX instance
var ajax = new XMLHttpRequest();
// open the request
ajax.open("POST", form.getAttribute("action"), true);
// listen for response from server
ajax.onreadystatechange = function () {
// when the request is successfull
if (this.readyState == 4 && this.status == 200) {
// convert the JSON response into Javascript object
var data = JSON.parse(this.responseText);
// show the response
alert(data.status + " - " + data.message);
}
// if the request fails
if (this.status == 500) {
alert(this.responseText);
}
};
// create form data object
var formData = new FormData(form);
// send the request
ajax.send(formData);
// prevent the form from submitting
return false;
}
</script>
Comments have been added with each line for an explanation. Now we need to create a route in our web.php file inside the routes folder in Laravel 9.
use Illuminate\Http\Request;
Route::get('/', function () {
return view('welcome');
});
// this is the route I will make it to return JSON data
Route::post("/form-submit", function (Request $request) {
$request->validate([
"name" => "required",
"file" => "required|image"
]);
DB::table("users")->insert([
"name" => $request->name
]);
$request->file("file")->storeAs("/public", $request->file("file")->getClientOriginalName());
// return redirect()->back();
// return the response in JSON
return response()->json([
"status" => "success",
"message" => "Task has been done"
]);
});
First, we are validating that the request must have name and file fields and the file must be an image. Then we are inserting the data from the text field in the users table. You can find the sample database in the attachments below.
Then we are storing the image in a public/storage folder. You need to run the following command in order to make this work:
php artisan storage:link
Lastly, we are sending the response back in JSON format. That’s how you can convert a POST request into an AJAX request in Laravel.