Bootstrap Model Window Not Showing by Calling Through JQuery - javascript

What I am trying to do is that pop up a bootstrap js model by using jquery call that is
$("#id").modal("show")
but it's not working in any case, there are several cases mentioned in this link but none is working in my case.
also I have gone through the following links
bootstrap model is not working
Bootstrap modal window not showing
calling to bootstrap model for a link
Bootstrap modal - popup window not showing
https://getbootstrap.com/docs/4.0/components/modal/
but I am not able to get any help, I can trigger the model by having an extra button and calling click() function of button by jquery, this works fine but not modal case.
My Modal code is here
<div class="modal fade" id="addLocationTagModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabelLocation">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" id="idButtonCloseLocation" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabelLocation">Enter Location</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-lg-9 col-md-9 col-sm-12 col-xs-12">
<div class="form-group">
<?php
$preferredLocation = "";
if (strtolower(getUserPreferredLocation($row_user, $conn)) !== "no") {
$preferredLocation = getUserPreferredLocation($row_user, $conn);
}
?>
<input type="text" class="form-control" value="<?php echo $preferredLocation; ?>" placeholder="Location" id ="locationSuggested" name="locationSuggested" />
<span>
<span id="suggesstionBoxLocation" ></span>
</span>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-12 col-xs-12">
<div class="pLace-order">
<button type="button" name="buttonLocation" onclick="getTagSelected();" class="btn btn-success" value="submit">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
Jquery call is here
<script>
function detachStore(url){
//alert(url);
//document.getElementById("buttonDeleteStore").click(); // Click on the checkbox
// For Testing Purpose to set the data-target
jQuery.noConflict();
$(document).ready(function () {
$("#addLocationTagModel").modal("toggle");
alert("Hello");
//$("#buttonDeleteStore").click();
// $('#addLocationTagModel').appendTo("body").modal('show');
});
}
And HTML and mixed PHP code is here below, I have onclick function on the element call that is working perfectly.
<td>
<?php
$i = 1;
foreach (unserialize($row['store_id']) as $store_id) {
$stores = $conn->query("select * from tb_stores where ID = " . $store_id);
while ($stores_row = $stores->fetch_assoc()) {
$store_price = $conn->query("select * from tb_add_price_of_products where product_id=" . $row["ID"] . " and store_id=" . $stores_row["ID"]);
$store_price_row = $store_price->fetch_assoc();
//echo $store_price_row["price"];
if ($i == 1) {
echo "<a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
} else {
echo ", <a href='#' data-toggle='modal' title='$"
. $store_price_row["price"] . "-" . $stores_row["location"] . "'"
. " onclick=\"detachStore('" . $url . "product-registry?action=delete-store&product_id=". $row["ID"] . "&store_id=" . $stores_row["ID"] . "');\" >"
. $stores_row['name'] . "</a>";
}
$i++;
}
}
?>
<button type="button" id="buttonDeleteStore" data-toggle="modal" data-target="#add_price_modal">Button</button>
</td>
I have spent hours on it, even no JavaScript error, May be I am doing something wrong at some place, if anybody can pull it out that would be appreciated.

I was going through some other post
TypeError: $(...).modal is not a function with bootstrap Modal
and I replaced
$("#id").modal("show")
with
jQuery("#id").modal("show")
and this trick worked here and it started working. Still I don't know the reason like why it wasn't working with $.
One more thing, we need to include the jQuery.noConflict(); above then the statement to avoid repetitions.

Related

How can i know which link I clicked?

I'm deploying a table where you can edit the columns. For that, in each cell there's an <a> to show a modal to change que value in the database and refresh the page. For now it does well the modal appearing but for the moment the modal appears, the code doesn't know which link was clicked. I need to know it to get the id of the row. The JQuery method that calls the last button of the modal ('Guardar') needs to call a php script by AJAX and send the id of the row (to make the UPDATE statement) and the new value of the column.
I tried to use the methods closest() and find() from JQuery and to set a the id of the row in a data-id attribute.
This is where I deploy the table vía PHP(code is simplified to one column to read and understand it better)
if($resHitos->num_rows>0){
while ($columna = mysqli_fetch_assoc($resHitos)) {
$id=$columna['id'];
echo "<tr data-id='$id'>";
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
echo "</tr>";
}
}
This is the modal
<div class="modal fade" id="modalEditarHito" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar objetivo</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="newObjetivo">Objetivo</label>
<textarea class="form-control" rows="5" id="editObjetivo"></textarea><br>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" onclick="editDescripcionHito()">Guardar</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
The expected result is to see the new value inputed in the exact row that was clicked.
Add listener event on your modal when it is displayed.
$(document).on('show.bs.modal','#modalEditHito', function (e) {
var $invoker = $(e.relatedTarget);
//this may help
//var tr = $invoker.closest('tr');
//var tr_id = tr.attr("data-id");
});
You can use a data attribute to uniquely identify rows. or you can simply add id attribute like this
echo '<tr data-id=".$columnna['id'].">';
You should change this line
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito'>".$columna['descripcion']."</a></p></td>";
to
echo "<td style='text-align:center'><p><a data-toggle='modal' data-target='#modalEditHito".$columnna['id']."'>".$columna['descripcion']."</a></p></td>";

Using AJAX to update a dynamic webpage

I made a webpage that consists of projects, where each project consists of a list of files. All of this information is acquired from a MySQL database. I've implemented a feature that allows users to comment on each file and reply to each other's comments. I have a php function called "place comments" which recursively places comments for each file shown below.
This is executed for every file and every file is displaced similarly using a while loop and some statements that echo html code.
However, the issue I'm having is using AJAX to post comments without the page refreshing. Since each file id is different, I would have to update every selector with a particular file id and run placeComments again for every file.
However I'm not sure how to accomplish this. I'm able to update my database through AJAX everytime I submit a comment.
I know you can do something like the following and it will update any selector with the id "id":
$(document).ready(function() {
$.get('comments.php', function (data) {
$('#id').html(data);
});
});
But I'm not sure how I can do this iteratively for every file id where each file id is a php variable?
Is there a way I can communicate with JS through PHP so it updates comments
for all file ids? If so, how?
I realized that this is a terrible design, but I'd like to do this without starting my project from scratch.
Place comments function:
function placeComments($mysqli, $parentId, $fileId) {
$sql = "SELECT * FROM Comments WHERE parent = $parentId AND file = $fileId ORDER BY UNIX_TIMESTAMP(date) ASC";
$comments = $mysqli->query($sql);
while($comment = $comments->fetch_assoc())
{
echo '
<ul class="comments">
<li class="clearfix">
<div class="post-comments">
<p class="meta"> '. $comment['date'] .' '. $comment['username'] .' says : <i class="pull-right">
<p>'
.
$comment['content']
.
'</i></p><br><br>';
echo '<div class = "col-sm-12 reply panel-group">';
echo '<div class="panel panel-default">';
echo '<p><a data-toggle="collapse" href="#'. $comment[
'file'] . '-' . $comment['id'] . '"> Reply </a></p>';
echo '<div id="'. $comment['file'] . '-' . $comment['id'] .'" class="panel-collapse collapse">';
echo '<div class="panel-body">';
if(isset($_POST['submitComment-' . $comment['file'] . '-' . $comment['id']]))
{
$user = $_POST['username'];
$content = $_POST['content'];
$fileId = $_POST['id'];
$parent = $_POST['parent'];
$date = date('Y-m-d H:i:s', time());
filterComment($mysqli, $fileId, $user, $parent, $content, $date);
}
echo '<form method="post" class="form-horizontal" id="commentForm" role="form">
<div class="form-group">
<div class="col-sm-10 form">
<h5><b> Name: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="username" id="username" rows="1"></textarea>
</div>
<div class="col-sm-10 form">
<h5><b> Reply: <b></h5>
</div>
<div class="col-sm-10 form">
<textarea class="form-control" name="content" id="content" rows="3"></textarea>
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['file'] . ' name = "id" id = "id" />
</div>
<div>
<input class = "form-control" type = "hidden" value = '. $comment['id'] . ' name = "parent" id = "parent" />
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10 form">
<button class="btn btn-success btn-circle text-uppercase" type="submit" id="submitComment" name = "submitComment-'. $comment['file'] .'-' . $comment['id'] . '"><span class="glyphicon glyphicon-send"></span> Reply </button>
</div>
</div>
</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div><br><br>';
placeComments($mysqli, $comment['id'], $comment['file']);
echo '</div>';
echo '</li>';
echo '</ul>';
}
$comments->free();
}

PHP Trigger submit on other page from iframe

I am trying to submit the page inside the iframe using the submit button from modal of Page1.php to trigger the submit button of Page2.php. Can I ask for a help if what is the best way to execute this?
The reason why my submit is in modal is to execute multiple functions from Page1.php, and the Page1.php codes is some part of the button from dataTable just incase you notice those single (')s
Page1.php
<a class='btn btn-md btn-warning' data-toggle='modal' data-target='#editModal' >View</a>
<div class='modal fade' id='editModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-dialog' style='width:95%; height:100%'>
<div class='modal-content' style='height:100%'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='myModalLabel'>EDIT HERE</h4>
</div>
<div class='modal-body'>
<iframe src='page2.php' id='info' class='iframe' name='info' seamless='' height='100%' width='100%'></iframe>
</div>
<div class='col-lg-12' style='text-align: center' ><button type='submit' name='outerSubmit' id='outerSubmit' value='Submit' class='btn btn-lg btn-danger'>SAVE</button></div>
</div>
</div>
</div>
Page2.php
<form id="getedit" name="getedit" action="someaction..." method="POST" class="form-horizontal" onSubmit="if(!confirm('Are you sure you want to save changes?')){return false;}" >
<div class="col-sm-3">
<label for="exampleInputtext1">Name:</label>
<input type="text" class="form-control" id="dogr" value='somename'readonly/>
</div>
<div class="col-lg-12" style="text-align: center" ><button type="submit" name="getData" id="getData" value="Submit" class="btn btn-lg btn-danger" hidden>SAVE</button></div>
</form>
I just want to let the readers understand the whole process because I think I already have the correct codes but I dont know how to apply it properly in this situation. so here is my whole function:
function suysing_search($data)
{
$sEcho = intval($data["sEcho"]);
$sSearch = $data["sSearch"];
$iDisplayStart = intval($data["iDisplayStart"]); //start of record
$iDisplayLength = intval($data["iDisplayLength"]); //display size
$pageNum = ($iDisplayStart/$iDisplayLength)+1; //page num
$colSort = $data['iSortCol_0'];
$dirSort = strtoupper($data['sSortDir_0']);
$qString = "CALL suysing_list(";
$qString .= " " . $colSort . ",";
$qString .= "'" . $dirSort . "',";
$qString .= "" . $pageNum . ",";
$qString .= "" . $iDisplayLength . ",";
$qString .= "'" . $sSearch . "',";
$qString .= "" . $sEcho . ")";
//$res = $this->db->query($qString);
//$res = $res->result();
$res = $this->db->query($qString)->result();
//print_r($res);
//$res = $res->result();
$iTotalDisplayRecords = 0;
$iTotalRecords = 0;
//echo intval($res[0]->TOTAL_ROWS);
if(count($res) > 0)
{
$iTotalDisplayRecords = intval($res[0]->TOTAL_ROWS); //used for paging/numbering; same with iTotalRecords except if there will be search filtering
$iTotalRecords = intval($res[0]->TOTAL_ROWS); //total records unfiltered
}
$output = array(
"sEcho" => intval($sEcho),
"iTotalRecords" => $iTotalRecords,
"iTotalDisplayRecords" => $iTotalDisplayRecords,
"aaData" => array()
);
$countField = "<input type='hidden' name='ctd_count' id='ctd_count' value='".$iTotalRecords."' />";
//print_r($res);
setlocale(LC_MONETARY, 'en_PH');
if(count($res) > 0)
{
foreach($res as $row)
{
$output['aaData'][] = array(
$row->ref_no,
"
<script>
function sample(){
alert('Outer submit triggered!');
window.frames['innerframe'].document.forms['getedit'].submit();
}
</script>
<a class='btn btn-md btn-warning' data-toggle='modal' data-target='#editModal".$row->ref_no ." ' >View</a>
<div class='modal fade' id='editModal". $row->ref_no ."' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-dialog' style='width:95%; height:100%'>
<div class='modal-content' style='height:100%; '>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='myModalLabel'>EDIT HERE</h4>
</div>
<div class='modal-body' style='background:url(".base_url()."images/animal.gif) center center no-repeat; height:85%'>
<iframe id='innerframe' src='".base_url()."index.php/suysing/view_profile/".$row->ref_no."/a/ASHAJSHAKS'class='iframe' name='innerframe' seamless='' height='100%' width='100%'></iframe>
</div>
<div class='col-lg-12' style='text-align: center'><button name='outerSubmit' id='outerSubmit' class='btn btn-lg btn-danger' onClick='sample();'>SAaaaaaVE</button></div>
</div>
</div>
</div>
"
);
}
}
echo json_encode($output);
}
One way you can do this is using only javascript to add a javascript function to page1.php that will submit your form on page2.php. Add this code to the top of page1.php
<script type="text/javascript">
function sumbit_up_form()
{
window.frames["info"].document.forms["getedit"].submit();
}
</script>
Then Modify the button on page1.php to run the function when clicked by using:
<button type='submit' name='dateData' id='dateData' value='Submit' class='btn btn-lg btn-danger' onclick='sumbit_up_form();'>SAVE</button>
instead of
<button type='submit' name='dateData' id='dateData' value='Submit' class='btn btn-lg btn-danger'>SAVE</button>
EDIT -- ADDITION
If you want this to work using your jquery script then use:
window.frames["info"].document.forms["getedit"].submit();
instead of
$('#info').contents().find('#getData input[type="submit"]').click();
Breakdown of how the code works:
window. is a reference to the browser window object. In order for this code to work Page1.php will need to be the top document in the browser window. If Page1.php is in an iframe itself then you will need to reference the iframe or leave window. out of the code. However, leaving out the window. could make your site/app more easy to hijack.
frames["info"]. is a reference to the iframe object using the name attribute.
document. is a reference to the document inside the iframe.
forms["getedit"]. is a reference to the form object using the name attribute. If you prefer to use the ID then use getElementById("getedit"). instead. NOTE: In XHTML, the name attribute is deprecated. Use the id attribute instead.
submit() calls the submit method for the form object.
When you submit your form with i frame,after successful submission set value in session flash data.
session()->flash('operation_status', 'success');
and then get that flash data in your iframe.
Inside Your Iframe
$operation_status = session()->get('operation_status', false)
if ($operation_status == 'success')
var p = window.parent;
p.jQuery('body').trigger('refreshPage');
}
In parent page
$('body').on('refreshPage', function (e) {
window.location.reload();
});
This code is from laravel

Showing a Bootstrap modal after form is submitted

I want to display a "thank you" modal when the page is reloaded after successful form submission.
Here's my PHP at the bottom of the <head>:
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist (email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript"> $('#thankyouModal').modal('show'); </script>
<?php
}
?>
That all works fine except for showing the modal, which doesn't happen. I don't get any errors in the JS console.
Here's my modal at the bottom of the <body>:
<div class="modal fade" id="thankyouModal" tabindex="-1" role="dialog" aria-labelledby="thankyouLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Thank you for pre-registering!</h4>
</div>
<div class="modal-body">
<p>You'll be the first to know when Shopaholic launches.</p>
<p>In the meantime, any feedback would be much appreciated.</p>
</div>
</div>
</div>
</div>
Try wrapping a $(document).ready around the javascript.
<?php
if (isset($_POST["email"]) && !empty($_POST["email"]))
{
$response_text = "Thanks, we'll be in touch soon!";
include('connect.php');
mysqli_query($con, "INSERT INTO sh_betalist
(email, ip_address, signup_loc) VALUES ('" . $_POST['email'] . "', '" .
$_SERVER['REMOTE_ADDR'] . "', '" . "homepage')");
?>
<script type="text/javascript">
$(document).ready(function(){
$('#thankyouModal').modal('show');
});
</script>
<?php
}
?>

Jquery ajax add to mysql database

I want to save data from input fields to mysql database so first I create a modal window and input fields:
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add new</button>
<div id="output"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
......
<div class="input-group">
<span class="input-group-addon">Ime</span>
<input type="text" id="Ime" class="form-control" placeholder="Upisi ime">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Pol</span>
<input type="text" id="pol" class="form-control" placeholder="Pol (male/female)">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Godine</span>
<input type="text" id="godine" class="form-control" placeholder="Godine starosti">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Broj pojedenih krofni</span>
<input type="text" id="krofne" class="form-control" placeholder="Pojedene krofne">
</div>
</br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="newData" class="btn btn-primary">Add new data</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now I write jQuery AJAX code to add data to database:
<script>
//add data to database using jquery ajax
$("#newData").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#ime").val()!="") {
$.ajax({
url: "add.php",
type: "POST",
async: true,
data: { Name:$("#ime").val(), Gender:$("#pol").val(), Age:$("#godine").val(), Donuts_eaten:$("#krofne").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
</script>
and finally I create a php file (add.php)
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
$query .= mysql_real_escape_string($_POST['Gender']) . ", ";
$query .= mysql_real_escape_string($_POST['Age']) . ", ";
$query .= mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= ")";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Now, when I try to add data I just get this error: an error occurred saving your data!.
What is the problem here exactly? I try to find the error whole day...
You are not quoting your strings:
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
should be:
$query .= "'" . mysql_real_escape_string($_POST['Name']) . "', ";
(for all string values)
By the way, it would probably make your life easier if you switched to PDO or mysqli and prepared statements. Then you would not have to escape and quote your variables and the mysql_* functions are deprecated anyway.
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
Put all the values in single quotes.

Categories