pass HTML link id to js AJAX function through modal plugin - javascript

I have over 1.5 million dynamically created (php/html/js) web pages that contain lists of up to 300 people, to whom I need to allow visitors to send messages by using a popup form that is triggered by link next to each person's name. I'm using the PopEasy jquery modals plugin http://thomasgrauer.com/popeasy/ .
All these modals/forms are identical, except for a unique recipient ID associated with each link that needs to be passed through to the AJAX code that fires to save the message to that person's record when the modal's form's Send Message btn is clicked (e.g. "1001', '1002' in the examples below).
For each page, I could dynamically create up to 300 form DIVs, one for each link, but would rather find a clever way to transfer the recipient ID with just one modal/form DIV, to cut down the bandwidth. I should be ok, if I can reference the ID of the link from within the AJAX code (as the "u" var in the example below).
Ideas?
(my competencies: js: "barely any" / html and php: "average".
Here is the code that works for just two links/divs/forms:
<a id="1001" class="modalLink" href="#modal_1001">Send msg</a>
<a id="1001" class="modalLink" href="#modal_1002">Send msg</a>
// the plugin uses the class to fire, and the href to know which of several DIVs of
// that class to use; if the a#id isn't needed, I can strip the "modal_" part out of
// the href to save having to parse it
<div id="modal_1001" class="modal">
<form method="post" action="">
<textarea>(write your msg here)</textarea>
<button type="button" onclick="storeMsgAjax(1001,1234)">Send message</button>
</form>
Close Form
</div>
<div id="modal_1002" class="modal">
<form method="post" action="">
<textarea>(write your msg here)</textarea>
<button type="button" onclick="storeMsgAjax(1002,1234)">Send message</button>
</form>
Close Form
</div>
And here is the js modal plugin function:
$(document).ready(function(){
$('.modalLink').modal({
trigger: '.modalLink', // id or class of link or button to trigger modal
olay:'div.overlay', // id or class of overlay
modals:'div.modal', // id or class of modal
animationEffect: 'slideDown', // overlay effect | slideDown or fadeIn | default=fadeIn
...(other options)...
close:'.closeBtn' // id or class of close button
});
});
And here is the AJAX code:
function storeMsgAjax(s,u)
{
var m = document.getElementById("msgtxt").value;
var url = "http://ifinallyfoundu.com/storeMsg.php?s="+s+"&m="+m+"&u="+u+"&t=" + Math.random();
xmlHttp2 = GetXmlHttpObject();
if (xmlHttp2 == null) {alert("Browser does not support HTTP Request"); return;}
xmlHttp2.onreadystatechange = function()
{
if (xmlHttp2.readyState == 4 && xmlHttp2.status == 200)
{
var formSaveResults = xmlHttp2.responseText;
document.getElementById("modal_"+s).innerHTML = formSaveResults+'<br><br>Close Form' ;
}
}
xmlHttp2.open("GET", url, true);
xmlHttp2.send(null);
}

Looks like I can add an onclick script to each link to put the ID in the innerHTML of a hidden page element, which should be accessible to the AJAX routine. I'm sure there is probably a more elegant solution, but this seems to work.

Related

How to Set Header Text of Modal Dialog According to the Table element and his ID

Hello everyone and sorry in advance for my very bad English.
I'm working on an ASP.NET MVC project with a JavaScript framework as the front-end.
I have a table which contains customer names retrieved from a database. Now I want to show a modal dialog and set the text of its header according to the customer name which has been clicked. At the same time I would like to get the customer Id. For example, when clicking "Georges", the modal dialog pops up and its header text is set to "Georges".
Here is my code.
The customer table look like this:
<div class="col-lg-6">
<div class="container-fluid" id="DailyTask">
<h4>Daily Tasks</h4>
#if (Model != null)
{
List<SchedulerTool.Models.spGetDailyBatchTask_Result> batches = Model.DailyTask;
foreach (var batch in batches)
{
<div class="bs-callout bs-callout-warning" id="dailybatch">
<input name="currentdailyBatchId" id="#batch.BatchId" hidden type="text" value="#batch.BatchId" />
<input name="currentdailyBatchName" id=" #batch.BatchName " hidden type="text" value=#batch.BatchName />
<button class="btn btn-group-justified" id="dailybatchTask" data-title="#batch.BatchName" data-target="#dailybatchTaskModal" data-toggle="modal" data-bid="#batch.BatchId">
<span class="fa-bitbucket-square" id="name">#batch.BatchName</span>
</button>
</div>
}
}
</div>
The JavaScript code is:
$('dailybatchTask').on('click', function ()
{
var batchId = $(this).data('bid');
var batchName = $(this).data('title');
// Here I set the table name a template table
$("h4 a#bathDailyTaskModalLabel").html(batchName);
// Here I set the Id to a template table
loadMasterTable("LoadObjectsNotBatched", batchId, DailyBatchElementUrl, "DailyBatchCollapseElementId");
});
Customers table:
The modal that is popover when clicked on customer:
The problem is: when I clicked on the first element of the customer table, the modal is correctly shown (the header and id are correct) but when I clicked on the others elements the JavaScript code is not executed.
Hope someone can try to understand my problem and will help me!
You are trying to catch all buttons by ids. But in HTML ids must be unique. Because that jquery your click event only matches first data. You need to fix ids before jquery part. If you really need it you can define a counter for loop and use it like this;
id="dailybatchTask-#counter"
But you already defined data-bid so basically, you can just add a class name for the button like this;
class="btn btn-group-justified daily-batch-button"
then only you need to;
$('daily-batch-button').on('click', function () {
...
...
...
});

Why is this dynamically assigned id using a loop only showing the first assignment? javascript, AJAX & JSTL

Have a Java based web application with a page where a feed of posts is dynamically generated with the help of JSTL. The user can currently 'like' any post in the feed but this has proved much more difficult to implement using AJAX. I know i'm really close here but can't quite figure out what's wrong.
It works but only for the first item in the array.. So any like button that is pressed in the feed, only updates the first like button in the feed. Why is it that the dynamically assigned div value (input name=likesDivCount) only registers the first assignment?
index.jsp
<c:forEach items="${idFeedArray}" var="posts" varStatus="count">
...feed item (such as image, text etc..)...
<form id="likesform" action="../AddLike" method="post" style="display:inline;">
// the value of this input below is supposed to change...(i.e. #likesSize0,#likesSize1,#likesSize2)
<input name="likesDivCount" value="#likesSize${count.index}" type="hidden">
<input name="postUser" value="${userpost[count.index]}" type="hidden">
// this button sends the AJAX request
<button style="padding-right: 0;" type="submit" class="btn btn-link"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</form>
// The span in the button below updates with the response from the AJAX
<button style="padding-left: 0;" class="btn btn-link"><span id="likesSize${count.index}">${likesArraySize[count.index]}</span></button>
</c:forEach>
<script>
$(document).on("submit", "#likesform", function(event) {
var $form = $(this);
var likesDivCount = $("input[name=likesDivCount]").val();
//this alert below is for testing, everytime the like button is pressed it displays '#likesSize0' and i need it to spit #likesSize1,#likesSize2,#likesSize3 etc...
alert(likesDivCount);
$.post($form.attr("action"), $form.serialize(), function(response) {
// only updates the first item :( (#likesSize0)
$(likesDivCount).text(response);
});
event.preventDefault(); // Important! Prevents submitting the form.
});
</script>
Looks like you have multiple forms with the same ID: '#likesform'. This is because your forms are generated in a loop.
I suggest you to remove the ID, replace it with a css class (or something else) and rewrite the JS to search for elements inside the target form, e.g.:
var $form = $(this);
var likesDivCount = $form.find("input[name=likesDivCount]").val();
Once you have valid html it will be easier to troubleshoot

Posting Div Content in Php

I have two php pages. In the first.php page user choose orders and a div is filling with this content, no problem. And there is a confirm button to confirm these list. When the user click this button, second.php page should be opened and the contents of the div should be displayed on that page. This is my html code for the first.php div and confirm button.
<form method="post">
<div class="col-md-5" id="orderList">
<h3 align="centre">Order List</h3>
</div>
</form>
<form role="form" method="post" action="second.php">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" id="firstConfirmButton" class="btn btn-primary btn-lg">Confirm</button>
</div>
</form>
This is the javascript code to post the contents to second.php. First alert is working fine but second alert is not.
$("#firstConfirmButton").click(function() {
var content = $('#orderList').html();
alert(content);
$.post("second.php", { html: content})
.done(function(data) {
alert(data);
$('#confirmForm').empty().append(data);
});
});
Second.php page has the confirForm div and I want to display the contents in this.
<div id="confirmForm"> </div>
Where is the problem?
Your button is a submit button, so if you don't cancel the default event, the form will be submitted the regular way as well.
You need to capture the event and cancel it:
$("#firstConfirmButton").click(function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
Or in modern versions of jQuery:
$("#firstConfirmButton").on('click', function(e) {
var content = $('#orderList').html();
e.preventDefault();
// the rest of your code
You submit the form to the page second.php by using the POST method, so the data can be retrieved from the second page by using this PHP code:
var_dump($_POST);
So basically, the data is stored within the $_POST array.
Regarding your second question. You need to avoid that you submit the default form if you first need to grab a value form a Javascript. You can do that by something like that:
$("#firstConfirmButton").click(function(e) {
var data = $('#orderList').html();
e.preventDefault();
//...
}
This will avoid that your submit button submits the form without adding the desired POST data to it.

What do I need to use to submit a form while opening up a modal?

I'm trying to create an 'edit' button for a post that when clicked will both submit the form which will pass in the post id and call a modal(I'm using bootstrap modal). The modal that opens up will show the content from the passed in post id.
however, I' having trouble coming up with a tag that will both submit and call the modal(href). I have tried combinations of anchor tags, input tags and button tags but neither really seem to work together to achieve the goal. I'd appreciate any advice. Thanks
<form>
<a class="btn" data-toggle="modal" title="edit" id="editbtn" href="#myeditModal">
<input type="submit" name="edit" id="edit"></a>
</form>
----the modal div -------
<div class="modal hide" id="myeditModal">
If I've understood your question correctly, I'd simply use a JQuery click function on a submit button, so for example:
User clicks submit button on form
JQuery click function opens modal
Return true
Form gets submitted
If you need the modal to remain open during an Ajax post, then just serialize the form using the same click function, post, wait for response, and return false.
UPDATE:
For example:
$(".your-submit-button").click(function() {
// Do something with modal box
$("#your-modal-box").show();
// Do ajax request
var url = $(this).parents("form").attr("action");
var params = $(this).parents("form").serialize();
$.post(url, params, function(output) {
// Optionally do something with the output of ajax request
});
return false;
});

Hide, load, and show div with javascript

I have a few pages from each other to interact with page with id load, as below:
inside process.html
<div id="guest_details"> </div>
<div id="first_start"> </div>
<script>
<! -
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
$('#guest_details').hide('slow');
$('#first_start').SlideUp('slow')
->
</Script>
inside guest_details.html
<form action="guest_details.php" <form method="POST" id="guest">
<!-- Some cell here -->
<a onclick="$('#guest').submit();" class="button" id="first_start"> <span> <?php echo $button_submit;?> </span> </a>
</Form>
That I want is when the submit button is clicked then:
data sent to guest_details.php
If the data has been sent then hide < div id="guest_details"> < /div>
showing the show < div id="first_start"> < /div>
but when I make it like the above, that not work, Could someone give a clue how to correct?
Thanks a lot
Looking at your previous question and your tags, I assume you are not much aware of AJAX.
You need to
1.post the form asynchronously (without reloading the page, using AJAX).
2. On successfully sending the data, do the dom manipulations.
I suggest using jquery for doing an AJAX post.
Here is a sample code, using jquery:-
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
function ajaxPostForm()
{
$.post('guest_details.php',
function(data) {
//Dom manipulation
$('#guest_details').hide('slow');
$('#first_start').SlideUp('slow')
});
}
And your form html inside guest_details.html needs to be like:-
<form method="POST" id="guest">
<!-- Some cell here -->
<a onclick="ajaxPostForm();" class="button" id="first_start"> <span> <?php echo $button_submit;?> </span> </a>
</Form>
The $.post given above is a very basic AJAX post. You may add further features as give in Jquery Post.
Also if you want to post the entire form, you can refer jQuery Form Plugin
Updates
I think I understood your problem better this time. Inside your update where you say this-
by default guest_details.html is
showing and first_start.html is hiding
referring to the sections as guest_details and first_start would make more sense because guest_details.html may mean the page guest_details.html which you might have opened in another window.
Anyway, I am sure you mean the sections inside the page process.html as you have used jquery .load(). Let's call the first_start.html and guest_details.html as sections first_start and guest_details respectively.
As per your updates do you mean the following:-
Initial state
Section guest_details is shown and first_start is hidden
Cases/Situations
When form inside guest_details section is submitted, then hide the section guest_details and show first_start section.
At this state when guest_details is hidden and first_start is shown, the button on first_start can be clicked and on doing so the guest_details section shows again.
During these states where one section is hidden and another is shown reloading/refreshing the page should preserve the states.
If above is the complete scenario, here is the code:-
<script>
<! -
initiateSections(<?php echo $this->session->data['display_state']; ?>);
//state can have "display_first_start" or "display_guest_details"
function initiateSections(state)
{
$('#guest_details').load('?p=guest_details.html');
$('#first_start').load('?p=first_start.html')
if(state == "display_first_start")
{
displayFirstStart();
}
else
{//If chosen or by default
displayGuestDetails();
}
}
function ajaxPostGuestDetails()
{
$.post('guest_details.php', //In this post request - set $this->session->data['display_state'] = 'display_first_start'; in php
function(data)
{
//Dom manipulation
displayFirstStart();
});
}
function ajaxPostFirstStart()
{
$.post('first_start.php', //In this post request - set $this->session->data['display_state'] = 'display_guest_details';
function(data)
{
//Dom manipulation
displayGuestDetails();
});
}
function displayGuestDetails()
{
$('#first_start').hide('slow');
$('#guest_details').slideUp('slow');
}
function displayFirstStart()
{
$('#guest_details').hide('slow');
$('#first_start').slideUp('slow');
}
->
</Script>
You need to implement ajax to post the data to php
http://api.jquery.com/jQuery.ajax/
use ajax success to do your post success activities.
Once ajax is successful do the HTML manipulations
success: function(data) {
}

Categories