How to get script variable value in php - javascript

I am using popup for showing message based on the id of click function.so i want get the id when popup is open in php. thanks in advance
<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>
<p> </p>
<div class="modal hide" id="addBookDialog">
<div class="modal-header">
<button class="close" data-dismiss="modal">×</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<p>some content</p>
<?php //here i want to getting script variable value for database purpose?>
</div>
</div>
and my script is
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
});
in ajax call i am getting the id from the next page but i want value in same page
function viwpost(id) {
var pid=id;
$.ajax({
type: "POST",
url: "view_more.php",
data: "pid=" + pid ,
success: function(data)
{
$("#myModal21").html(data);
}
});
}

Since you're already using jQuery framework/API:
you can simply use the
$.get('phpfile.php' { id: myBookId }).done(function (response) { alert(response); });
your PHP file can pick the request up like this:
$_GET['id'];
If you're trying to make a live pop-up to load the data, this is an incorrect method of doing so. PHP script is only loaded once on server running and sending a request will only give you a response so ensure you research.
I'd suggest you create your PHP file to echo out the data you want to pop-up.
Demonstration of PHP file to send a response back to the request (as requested):
if(isset($_GET['id']))
{
echo 'what ever is outputted to the client will be received in the response';
}

Hey there is mistake in getting id of the link. You can use like this -
first create input type hidden and set its id bookId in model body like this:
<input type="hidden" id="bookId" />
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).attr('data-id');
$(".modal-body #bookId").val( myBookId );
});

Related

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

How to create a customised pop up using JavaScript

I have a SendMail button which on click calls the JavaScript function. Which upon validating gives the alert message. But that is a default alert which I am using. How can I create a customised alert in JavaScript.
My HTML Code:
<div id ="sendmail" style="display: none;">
<div class="container">
<div style="text-align:right; width:100%; padding:0;">
<button id ="cancel" style='margin-right:16px' class="btn btnprimary btn-lg pull-right" a href="javascript:window.history.back()">Cancel</button>
<button id ="sendMail" style='margin-right:16px' class="btn btn-primary btn-lg pull-right" onclick="sendMail()">SendMail</button>
And this is my index.js file
function sendMail(){
console.log(employee_id);
var employeeid = employee_id;
$.ajax({
url:'http://localhost:8088/JirasTrackingApp/reporter/
Reportees/JiraNames/'+employeeid,
type:'GET',
success: function(Jiranumbers){
alert("Mail is sent successfully"); //here I need to be able to call the customized alert instead of that default alert
},
error: function(Jiranumbers){
alert("Mail is not sent successfully");
}
});
Please advice, Thanks.
Your question very similar to this and I know you got your answer in this query.
how to change the style of alert box

Pass Data from HTML Table to Modal and then to PHP script

I have a index.php in which i have a Table with data from a MySQL database. Each row in the table has the data for the corresponding data in my database. Each row has a delete button. I want to show up a Modal and ask for permission to delete the entry. If the accepting Button is pressed i want to pass the id of that row to a delete.php script where the deletion is handled. So how do i pass the id for a row from my table to the modal and then to my delete.php. I know that i need jquery and ajax for it but im a total beginner with them. Im using bootstrap.
this is my button:
<a class="btn btn-danger" href="#delModal" data-toggle="modal
data-row-id="<?php echo $row['id'];?>" " >Delete</a>
and my modal:
<div class="modal" id="deleteModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Delete Entry</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<input type="hidden" name="id" value=""/>
<div class="modal-body">
<p>Are you sure that you want to delete the selected Entry? There is no way to restore the deleted data!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="accDelBtn">Yes, delete.</button>
<button type="button" class="btn btn-danger" id="disMdBtn" data-
dismiss="modal">No, abort.</button>
</div>
</div>
my jquery/ajax garbage try:
<script type="text/javascript">
$('#delBtn').on('click', function() {
$('#deleteModal').show();
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
$.ajax({
type: "POST",
url: "delete.php",
data: { id: $row['id'] }
})
});
</script>
Any help is appreciated!
I added an attribute for each ‍button tag called record_id and the record ID should be stored in it.
for example :
<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="delBtn" record_id="1">
<span aria-hidden="true">×</span>
</button>
And when the button ('#delBtn') is clicked, I get the ID and save the variable.
<script type="text/javascript">
var id = null
$('#delBtn').on('click', function() {
id=$("#delBtn").attr("record_id")
$('#deleteModal').show();
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
$.ajax({
type: "POST",
url: "delete.php",
data: { id: id }
})
});
</script>
And when I click on the button ('#accDelBtn'), I will send it.
You need to store the id of the row globally. Add a variable at the beginning of your script:
var rowToDelete = null;
Then, when you click a delete button, update it in the click handler:
rowToDelete = ID_TO_DELETE;
Finally, you can transmit it as:
data: { id: rowToDelete }
})
});
You have placed an hidden field with name attribute as "id", which you can use for doing further actions.
Check below code:
<script type="text/javascript">
$('#delBtn').on('click', function() {
$('#deleteModal').show();
// setting value of hidden input field by using currently clicked link data-row-id attribute
$('#deleteModal').find('input[name="id"]').val($(this).attr('data-row-id'));
});
$('#disMdBtn').on('click', function(){
$('#deleteModal').hide();
});
$('#accDelBtn').click(function() {
// retrieving value of hidden input field
var id = $('#deleteModal').find('input[name="id"]').val();
$.ajax({
type: "POST",
url: "delete.php",
data: { id: id }
});
});
</script>
I have just setted value of hidden field, on anchor tag click. And retrieving that hidden field value when doing ajax call.

PHP Code into Javascript

I am using fullcalendar.js and the calendar is working as it should right now. If a user clicks on an entry at the calendar, a modal appears with some information. What I need now is, that those information inside the modal are information from the database, so I would like to insert some PHP code but I have no idea how.
Let me show you which PHP code I would like to use so that the data from my database are displayed at the modal:
<?php
$dates=getPcalInfoOfHour($gl_userid,0,0);
for ($x=0;$x<count($dates["id"]);$x++) {
Title: '".$dates["title"][$x]."';
Selected Date: '".$dates["date"][$x]."';
Selected Time: '".$dates["start"][$x]."' '".$dates["end"][$x]."';
Topic: '".$dates["topic"][$x]."';
Location: '".$dates["location"][$x]."';
Address: '".$dates["address"][$x]."';
}
?>
Here is the part of my Javascript Code where I would like to enter my php code:
eventClick: function(calEvent, jsEvent, view) {
//display a modal
var modal =
'<div class="modal fade">\
<div class="modal-dialog">\
<div class="modal-content">\
<div class="modal-body">\
<button type="button" class="close" data-dismiss="modal" style="margin-top:-10px;">×</button>\
<label> <strong>Topic:</strong> Topic</label>\
<label> <strong>Selected Dated:</strong> Date</label>\
<label> <strong>Selected Time:</strong> Time</label>\
<label> <strong>Title:</strong> Title</label>\
<label> <strong>Location:</strong> Location</label>\
<label> <strong>Address:</strong> Address</label>\
<label> <strong>Phone:</strong> Phone</label>\
</div>\
<div class="modal-footer">\
<button type="button" class="btn btn-sm" data-dismiss="modal"><i class="ace-icon fa fa-times"></i> Close Window</button>\
</div>\
</div>\
</div>\
</div>';
var modal = $(modal).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
console.log(calEvent.id);
console.log(jsEvent);
console.log(view);
}
I know that PHP is a server side language and JavaScript is client based language but there must be a way, that my data from the database will be shown inside the modal am I right? I know a little bit about PHP programming but I never wrote something in JavaScript.
I would really appreciate if someone can tell me what my code should look like so that I get my information from the database inside the modal window.
Thanks,
Chris
I believe this would do:
var js_string = "<?php echo $php_string; ?>";
You have to make request to server to php script what will fetch data from DB and generate html.
Example javascript to use with php generated html for modal:
$.post('/script_generating_html.php', params, function(response) {
var modal = $(response).appendTo('body');
modal.modal('show').on('hidden', function(){
modal.remove();
});
});
Think of it this way. PHP generates what the browser will read before sending anything. So if you had the following code
<?php
$data = "Super Important";
?>
<script>
alert("<?php print $data; ?>");
</script>
It would generate for the client
<script>
alert("Super Important");
</script>
If you're going to be working with modifying javascript with php, also look into json_encode()
as another way to acheive the same thing is
<?php
$data = "Super Important";
?>
<script>
alert(<?php print json_encode($data;) ?>);
</script>

Using Bootstrap Modal window as PartialView

I was looking to using the Twitter Bootstrap Modal windows as a partial view. However, I do not really think that it was designed to be used in this fashion; it seems like it was meant to be used in a fairly static fashion. Nevertheless, I think it'd be cool to be able to use it as a partial view.
So for example, let's say I have a list of Games. Upon clicking on a link for a given game, I'd like to request data from the server and then display information about that game in a modal window "over the top of" the present page.
I've done a little bit of research and found this post which is similar but not quite the same.
Has anyone tried this with success or failure? Anyone have something on jsFiddle or some source they'd be willing to share?
Thanks for your help.
Yes we have done this.
In your Index.cshtml you'll have something like..
<div id='gameModal' class='modal hide fade in' data-url='#Url.Action("GetGameListing")'>
<div id='gameContainer'>
</div>
</div>
<button id='showGame'>Show Game Listing</button>
Then in JS for the same page (inlined or in a separate file you'll have something like this..
$(document).ready(function() {
$('#showGame').click(function() {
var url = $('#gameModal').data('url');
$.get(url, function(data) {
$('#gameContainer').html(data);
$('#gameModal').modal('show');
});
});
});
With a method on your controller that looks like this..
[HttpGet]
public ActionResult GetGameListing()
{
var model = // do whatever you need to get your model
return PartialView(model);
}
You will of course need a view called GetGameListing.cshtml inside of your Views folder..
I do this with mustache.js and templates (you could use any JavaScript templating library).
In my view, I have something like this:
<script type="text/x-mustache-template" id="modalTemplate">
<%Html.RenderPartial("Modal");%>
</script>
...which lets me keep my templates in a partial view called Modal.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<div>
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>{{Name}}</h3>
</div>
<div class="modal-body">
<table class="table table-striped table-condensed">
<tbody>
<tr><td>ID</td><td>{{Id}}</td></tr>
<tr><td>Name</td><td>{{Name}}</td></tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<a class="btn" data-dismiss="modal">Close</a>
</div>
</div>
I create placeholders for each modal in my view:
<%foreach (var item in Model) {%>
<div data-id="<%=Html.Encode(item.Id)%>"
id="modelModal<%=Html.Encode(item.Id)%>"
class="modal hide fade">
</div>
<%}%>
...and make ajax calls with jQuery:
<script type="text/javascript">
var modalTemplate = $("#modalTemplate").html()
$(".modal[data-id]").each(function() {
var $this = $(this)
var id = $this.attr("data-id")
$this.on("show", function() {
if ($this.html()) return
$.ajax({
type: "POST",
url: "<%=Url.Action("SomeAction")%>",
data: { id: id },
success: function(data) {
$this.append(Mustache.to_html(modalTemplate, data))
}
})
})
})
</script>
Then, you just need a trigger somewhere:
<%foreach (var item in Model) {%>
<a data-toggle="modal" href="#modelModal<%=Html.Encode(item.Id)%>">
<%=Html.Encode(item.DutModel.Name)%>
</a>
<%}%>
I have achieved this by using one nice example i have found here.
I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.
Complete and clear example project
http://www.codeproject.com/Articles/786085/ASP-NET-MVC-List-Editor-with-Bootstrap-Modals
It displays create, edit and delete entity operation modals with bootstrap and also includes code to handle result returned from those entity operations (c#, JSON, javascript)
I use AJAX to do this. You have your partial with your typical twitter modal template html:
<div class="container">
<!-- Modal -->
<div class="modal fade" id="LocationNumberModal" 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">
Serial Numbers
</h4>
</div>
<div class="modal-body">
<span id="test"></span>
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">
Close
</button>
</div>
</div>
</div>
</div>
</div>
Then you have your controller method, I use JSON and have a custom class that rendors the view to a string. I do this so I can perform multiple ajax updates on the screen with one ajax call. Reference here: Example but you can use an PartialViewResult/ActionResult on return if you are just doing the one call. I will show it using JSON..
And the JSON Method in Controller:
public JsonResult LocationNumberModal(string partNumber = "")
{
//Business Layer/DAL to get information
return Json(new {
LocationModal = ViewUtility.RenderRazorViewToString(this.ControllerContext, "LocationNumberModal.cshtml", new SomeModelObject())
},
JsonRequestBehavior.AllowGet
);
}
And then, in the view using your modal: You can package the AJAX in your partial and call #{Html.RenderPartial... Or you can have a placeholder with a div:
<div id="LocationNumberModalContainer"></div>
then your ajax:
function LocationNumberModal() {
var partNumber = "1234";
var src = '#Url.Action("LocationNumberModal", "Home", new { area = "Part" })'
+ '?partNumber='' + partNumber;
$.ajax({
type: "GET",
url: src,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$("#LocationNumberModalContainer").html(data.LocationModal);
$('#LocationNumberModal').modal('show');
}
});
};
Then the button to your modal:
<button type="button" id="GetLocBtn" class="btn btn-default" onclick="LocationNumberModal()">Get</button>
Put the modal and javascript into the partial view. Then call the partial view in your page.
This will handle form submission too.
Partial View
<div id="confirmDialog" class="modal fade" data-backdrop="false">
<div class="modal-dialog" data-backdrop="false">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Missing Service Order</h4>
</div>
<div class="modal-body">
<p>You have not entered a Service Order. Do you want to continue?</p>
</div>
<div class="modal-footer">
<input id="btnSubmit" type="submit" class="btn btn-primary"
value="Submit" href="javascript:"
onClick="document.getElementById('Coordinate').submit()" />
<button type="button" class="btn btn-default" data-
dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
Javascript
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#Coordinate").on('submit',
function (e) {
if ($("#ServiceOrder").val() == '') {
e.preventDefault();
$('#confirmDialog').modal('show');
}
});
});
</script>
Then just call your partial inside the form of your page.
Create.cshtml
#using (Html.BeginForm("Edit","Home",FormMethod.Post, new {id ="Coordinate"}))
{
//Form Code
#Html.Partial("ConfirmDialog")
}

Categories

Resources