PHP - Submit button and Modal Pop-up AJAX on 2 browsers PHP - javascript

I am new to php AJAX coding, my problem is I have TWO BROWSERS, first is I want to click the submit button and after that I want a modal to popup on the other browser so the final output will be a 2 browsers. just like a chat system. but it is different because I only want a button and a pop up modal.
so for example here is my button
<button type="button" class="btn btn-primary">CLICK TO POPUP</button>
My Modal
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
How can I popup this modal to the other localhost browser

Concurrent snapshots with php socket, you can run the results in all open windows.
PHP Socket
WebSocket

A simpler method is also controlled by ajax, which records the operation in a database every second, and popUp is shown with data from ajax if it needs to be shown in popUp.
But not a highly recommended method
Click Button
$.ajax({ url: "saveClickButton.php" })
setTimeout(function() {
$.ajax({ url: 'isClickButton' }).done(function(data) {
if ( data === "true" ) {
// Open Pop Up
}
});
}, 1000)

First, we are writing the listener in a php file.
then it writes a javascript process that will get the listener to tap and get feedback.
I'm sending the socket e 'getOpenPopUp' message that we're connected to with javascript. The socket on the php side is sending the openPopUp message to all clients after verifying it. this message is received on the javascript side popUp opens. my English is not good at all. I'm sorry I couldn't tell.
socket.php - Ratchet Class Ratchet
<?php
require __DIR__.'/vendor/autoload.php';
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
class Application implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
}
public function onMessage(ConnectionInterface $from, $msg) {
if ( $msg === 'getOpenPopUp' ) {
foreach ($this->clients as $client) {
$client->send('openPopUp');
}
}
}
public function onClose(ConnectionInterface $conn) {
}
public function onError(ConnectionInterface $conn, \Exception $e) {
}
}
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Application()
)
),
8080
);
$server->run();
App.js - WebSocket MDN Writing WebSocket client applications
var socket = new WebSocket('ws://localhost:8080');
var button = document.getElementById('button');
button.addEventListener('click', function() {
console.log('click')
socket.send('getOpenPopUp');
});
socket.onmessage = function(e) {
console.log(e)
if ( e.data === 'openPopUp' ) {
UIkit.modal.confirm('UIkit confirm!');
}
}

Related

Ajax / JQuery - Displaying flash message on success

I have a fully working flash system in PHP and am using it to send the user a success message once I create an entry in the DB.
On one of my forms I have a select field which I want the user to be able to seamlessly add entries too it without directing them away from a semi-completed form. The code I'm using is working well. The user clicks on 'add a category' (in the select label) it opens a modal, the user creates a new category, it updates the DB and the select field and closes the modal using AJAX. All working.
What I need to do is use or adapt my flash system to give the user a message to say all good your entry was added. I am very new to AJAX and on a steep learning curve!
This is my AJAX / JQUERY code: (I followed a tutorial to get here. The idea is to make this usable across the site when I need to add entries to a select, by adding 'ajax' to the form class.)
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index,value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$('#select').load(document.URL + ' #select');
$('#addCategoryModal').modal('hide');
$('#siteMessage').toast('show');
}
});
return false;
});
And this is the PHP setting the DB record (working) and how I normally trigger a flash message on page reload (messages also work):
//create record in db
$newCategory = $this->blogModel->createCategory($formFields);
if ($newCategory) {
flash('siteMessage', 'Blog category added successfully');
} else {
flash('siteMessage', 'Something went wrong', 'bg-danger');
}
And this is the flash code:
function flash($name = '', $message = '', $class = 'bg-success') {
if (!empty($name)) {
if (!empty($message) && empty($_SESSION[$name])) {
if (!empty($_SESSION[$name])) {
unset($_SESSION[$name]);
}
if (!empty($_SESSION[$name.'_class'])) {
unset($_SESSION[$name.'_class']);
}
$_SESSION[$name] = $message;
$_SESSION[$name.'_class'] = $class;
} elseif (empty($message) && !empty($_SESSION[$name])) {
$class = !empty($_SESSION[$name.'_class']) ? $_SESSION[$name.'_class'] : '';
echo '
<div id="siteMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
<div class="toast-header '.$class.'">
<i class="fas fa-envelope mr-2 pt-1 text-white"></i>
<strong class="mr-auto text-white">Site Message</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
'.$_SESSION[$name].'
</div>
</div>
';
unset($_SESSION[$name]);
unset($_SESSION[$name.'_class']);
}
}
}
My PHP processing page, creates the entry in the DB and I set the flash message as normal. I think I don't understand the interaction with how AJAX gets the returned success and setting a flash message.
Any thoughts?
Thanks to CBroe who pointed out the inherent problems with using a flash message mechanism I've added the following div at the bottom of the page and am now calling that direct with toast.show to give the message to the user.
I am not sure if that is the most affective way to do this but it works.
<div id="categoryMessage" class="toast shadow" data-delay="8000" role="alert" aria-live="assertive" aria-atomic="true" style="position: absolute; top: 19px; right: 45%; z-index:10">
<div class="toast-header bg-success">
<i class="fas fa-envelope mr-2 pt-1 text-white"></i>
<strong class="mr-auto text-white">Site Message</strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span class="text-white" aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
The category was added successfully
</div>
</div>

C# MVC Razor Partial to Upload a File in a Modal with Postback Message also in a Modal

I have a simple partial page to upload a file nested in a modal. I am not using ajax for the actions. There are 2 items in the controller
[HttpGet]
public ActionResult UploadFile()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Server.MapPath("~/UploadedDocuments"), _FileName);
file.SaveAs(_path);
}
ViewBag.Message = "File Uploaded Successfully!!";
return PartialView("UploadFile");
}
catch
{
ViewBag.Message = "File upload failed!!";
return PartialView("UploadFile");
}
}
The problem I am having is on postback it returns the partialView and not in the modal. I actually would like to see the postback message in a new modal dialog box.
I read an article that gave the idea of making a separate partial page with the message in it. To me that seems like a waste. Any idea how I can accomplish this with what I have or do I just have to do the form using JavaScript / Ajax?
Here is the form
#{
ViewBag.Title = "UploadFile";
Layout = null;
}
#Scripts.Render("~/Scripts/jquery-3.3.1.min.js")
<!-- MODAL -->
<div class="modal-header">
<h4 class="modal-title" id="exampleModalLabel"> <span class="glyphicon glyphicon-upload"></span> Upload File </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
#using (Html.BeginForm("UploadFile", "Document", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
#Html.TextBox("file", "", new { type = "file" }) <br />
<input type="submit" value="Upload" />
#ViewBag.Message
</div>
}
This is where the Modal is initiated - on index page with button.
<button type="button" class="btn btn-primary" id="Upload" onclick="createModal('#Url.Action("UploadFile", "Document")')">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
//////////
/////////
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content" id="modelContent">
</div>
</div>
</div>
<script type="text/javascript">
function createModal(url) {
$('#modelContent').load(url);
$('#myModal').modal('show');
}
$(function () {
// when the modal is closed
$('#myModal').on('hidden.bs.modal', function () {
// remove the bs.modal data attribute from it
$(this).removeData('bs.modal');
// and empty the modal-content element
$('#myModal .modal-content').empty();
});
});
</script>

How to call a partial view within a Modal using Jquery

I have a list of products and you want to display a modal window to edit the parameters of these products
for this you have in each row a button that calls the modal ....
my Edit button in Index.cshtml:
<td>
Editar
</td>
my script in Index.cshtml:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
my modal Bootstrap in Index view:
<div class="modal fade" id="myModalEditar">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Editar Producto</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="EditModalBody">
</div>
</div>
</div>
</div>
my ActionResult in controller:
public ActionResult EditarProducto (int Kn_CodigoProducto)
{
Producto model = new Producto();
if(Kn_CodigoProducto >= 0)
{
var producto = db.Productoes.Where(c => c.Kn_CodigoProducto == Kn_CodigoProducto).FirstOrDefault();
model.v_Nombre = producto.v_Nombre;
}
return PartialView("_PartialEditar", model);
}
and my partial view that receives the model sent from the controller:
#model Dominio.Producto
<div class="jumbotron">
<label>Esto es una prueba #Model.v_Nombre</label>
</div>
I have the partial view inside the folder along with the Index.cshtml view
Also I have referenced the corresponding scripts, what is happening? What is missing? It is the first time that I work with partial and modal views ... am I doing it correctly?
Expected behavior: when you click on the edit button, the modal opens
Behavior obtained: although when clicking on the edit button it enters the action of my controller, it does not show the modal
any help for me?
Instead of this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$("#EditModalBody").load(url, function () {
$("#myModalEditar").modal("show");
})
}
</script>
Can you try this:
<script>
var EditarProducto = function (codigoProducto) {
var url = "/Productoes/EditarProducto?Kn_CodigoProducto="+codigoProducto;
$.ajax({
url: url,
type: 'GET',
success: function (result) {
$('#EditModalBody').html(result);
$("#myModalEditar").modal("show");
},
error: function (xhr, status) {
alert(status);
}
});
}
</script>
You don't need to write jquery to invoke modal popup, instead you can use data-toggle and data-target attribuites.
Editar

How to get the id and name of an object on button click and display them in a modal in asp.net view

I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>

ajax notification alert popup or sound when new data insert into mysql

I have a website which sells some products to customer.
I want to have a alert notification popup or sound when ever a new order is inserted into mysql db.
I was searched several hours to find a solution with ajax but i'm new to ajax implementation stuck now.
I don't need a complicate method if i can get only a notification it would be ok for me.
If anyone give me hint or more detail reference or guide ... much appreciate!
This is mysql insert query:
$result2 = mysqli_query($con, "INSERT into user (emailPrefix,password1,address,address2,orderRnd,dateEmail,name5,phone, date)
VALUES ('$emailPrefix','$password1','$address','$address2','$orderRnd','$dateEmail','$name5','$phone','$date')");
ajax.js
var interval = setInterval( function() {
$.ajax ({
url: "user.php",
success: function(data) {
$("#users").html(data);
}
});
}, 3000);
Above syntax refreshes pages every 3 seconds. You can compare old id of table in every 3 seconds. If new id is there eventually its new inserted values. So popup like below
$result2 = mysqli_query($con, "SELECT id FROM user ORDER BY id ASC");
while($rows = mysqli_fetch_assoc($result2)) {
$NEW_id = $rows["id"];
}
if($NEW_id > $_SESSION["OLD_id"]) {
$_SESSION["destination_OLD"] = $id_flexi;
echo '<audio controls="controls" autoplay>
<source src="beep.wav" type="audio/wav">
<embed src="beep.wav">
Your browser is not supporting audio
</audio>';
}
I have same problem as yours and this is my solutions. Experts recommend other things but I have only this much knowledge.
Good day.
if($result2){
echo '<script type="text/javascript">alert("' . $msg . '")</script>';
} // define $msg as you like
Try this:
Put this html audio tag & modal on a page where you want a beep sound.
<audio id="playMusic" playcount="2">
<source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531135120/beep.mp3" type="audio/mpeg">
</audio>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" onclick="javascript:window.location='dashboard.php?page=5'">×</button>
<h4 class="modal-title"><i class="fas fa-bell" ></i> Incoming Order!</h4>
</div>
<div class="modal-body">
<p>Find out the new order by: <a href="dashboard.php?page=5" class="text-info" >Click Here!</a></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="javascript:window.location='dashboard.php?page=5'">Take me there!</button>
</div>
</div>
</div>
</div>
JS
The js code will fetch number of newly order from php page and see if there is any new order.
var old_count = 0;
var i = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "<?php echo 'folder/count_new_order.php'; ?>",
success : function(data)
{
if (data > old_count)
{
if (i == 0)
{old_count = data;}
else
{
$(document).ready(function() {
$("#playMusic").get(0).play();
});
$("#myModal").modal("show").on("shown", function () {
window.setTimeout(function () {
$("#myModal").modal("hide");
}, 1000);
});
old_count = data;
}
} i=1;
}
});
},500);
count_new_order.php
As a example, the table has 12 rows already.
include('config.php'); //db connection
$sql = "SELECT count(*) as count FROM table";
$qry = mysqli_query($conn,$sql);
$rowq = mysqli_fetch_assoc($qry);
echo $rowq['count']; // output: 12

Categories