How to display a input button and close the current window - javascript

I have a call to a service using ajax, i would like if everything goes well on the ajax call to enable or display an input (maybe in a div?) on my page that when clicked it will close the current window. What is the best way to do this using javascript?
Here is my function of a javascript class:
MyFunction.prototype.init = function(param1, param2) {
this.MyParams = new Hash();
this.MyParams.set("param1", param1);
this.MyParams.set("param2", param2);
new Ajax.Request('MyService.asmx/MyServiceFunction', {
method: 'post',
onSuccess: //how can i do what i mentioned here?,
onFailure: failureFunc,
onException: ajaxError,
parameters: this.MyParams
});
}
Any help would be much appreciated

On the onSuccess part you have to put something like this:
OnSuccess: function() {
$('div_to_show').show();
}
In the HTML part you will have this:
<div id="div_to_show">
<input type="button" name="close" id="close" value="close" onclick="javascript:window.close();" />
</div>
Of course you have to hide the div on document loading.

Related

JS is working in console but doesn't work in code

I have this button which calls modal window with simple form.
<aui:button-row>
<a style="float: left" onclick="ITD.robomarket.activateKeyModalWindowFunction(
'${activateKeyURL}', '<%=LanguageUtil.get(pageContext, "key-activating")%>', '400', '334')" class="btn btn-green"> </a>
</aui:button-row>
I want to close this modal window after submitting. I have already done this:
function closeModal () {
var id = 'robomarket-activate-key-modal-window'
var dialog = Liferay.Util.Window.getById(id);
dialog.destroy();
}
And this function I call in .jsp:
<script>
$(document).ready(function() {
closeModal();
});
</script>
The problem is this doesn't work BUT that modal window closes when I write this lines in console! What's the problem?
You have to call closeModal from the JSP where the modal was opened.
For exemple A.jsp has a link that open B.jsp in a modal dialog, then you want to close B.jsp when form is submitted
Here is a possible implementation :
In A.jsp :
<portlet:renderURL var="popupUrl" windowState="<%=LiferayWindowState.POP_UP.toString()%>">
<portlet:param name="mvcPath" value="/B.jsp"/>
</portlet:renderURL>
<aui:button href="${popupUrl}" useDialog="true" value="Open in popup" />
and at the bottom of A.jsp :
<aui:script>
Liferay.provide(window, 'closePopup', function(dialogId) {
var A = AUI();
var dialogId = A.one('div.dialog-iframe-modal').get("id");
var dialog = Liferay.Util.Window.getById(dialogId);
dialog.destroy();
});
</aui:script>
Then in B.jsp
You have to say to the opener to close the dialog, here is a possible implementation :
<portlet:actionURL name="/submitForm" var="submitFormURL">
<portlet:param name="action" value="submitForm" />
</portlet:actionURL>
<aui:form action="<%= submitFormURL %>" method="post" name="fm" onSubmit='<%= "event.preventDefault(); " + renderResponse.getNamespace() + "submitForm();" %>'>
...the form
<aui:button name="submitForm" type="submit"/>
</aui:form>
And at the bottom of the B.jsp page :
<script>
function <portlet:namespace/>submitForm(){
AUI().use('aui-io-request', function(A) {
var url = '<%=submitFormURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().closePopup('dialog');
}
}
}
);
});
}
</script>
Hope it helps
Regards
Arnaud
You are calling closeModal () method just after de DOM is ready. Wich mean you are asking to close even before the popUp is opened.
It is not clear what you do in your popUp. If is a partial submit, say an ajax call or similar, you need to call closeModal after you have got a response and treated the returned data.
Otherwise, if you are submiting a full submit, (a full reaload, navigation to a new page, you go through a whole new render phase) the modal window will dissapear with everi thing else in the currently renderes page.

How to receive AJAX (json) response in a divs with same class name individually?

I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!
UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.
I've been using jquery and vanilla JS as well but seems I just can't get it done!
This is how I currently trigger the button with jquery:
$('.trigger_button_inside_divs').click(my_ajax_function);
And this is how my ajax looks like:
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
$('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
$('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
$('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}
HTML looks like this:
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.
Thanks a lot people, I really hope to get this done!
Cheers.
PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.
(function(){
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
var xhr = new XMLHttpRequest();
var el;
function SetDataInTheForm()
{
var resp = JSON.parse(xhr.response)
var pt=0
var ct=0
var gt=0
Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
e.innerHTML=resp[i].name
})
Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
e.innerHTML=parseFloat(resp[i].p).toFixed(0)
pt+=parseFloat(resp[i].p)
})
Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
e.innerHTML=parseFloat(resp[i].c).toFixed(0)
ct+=parseFloat(resp[i].c)
})
Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
e.innerHTML=parseFloat(resp[i].g).toFixed(0)
gt+=parseFloat(resp[i].g)
})
el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit
el.querySelector(".pt").innerHTML=pt.toFixed(0)
el.querySelector(".ct").innerHTML=ct.toFixed(0)
el.querySelector(".gt").innerHTML=gt.toFixed(0)
}
function HandleSubmit(e)
{
el=e.currentTarget
e.preventDefault();
xhr.open("POST","/url_here.php",true)
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.onload=SetDataInTheForm
var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
button.removeAttribute("clicked")
xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}
[].forEach.call(document.querySelectorAll("._form_"),function(form){
form.addEventListener("submit",HandleSubmit,false);
})
})()
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.
Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.
$('.your-button').on('click', function () {
const myButton = $(this);
$.ajax({
// ...
success (data) {
myButton.parent().html(data.PHP_JSON_RECEIVED);
// or if you need to find a parent further up in the chain
// myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
}
});
});
The problem is that your class selector is indeed selecting all your divs at the same time.
Solution, set identifiers for your divs as such:
<div class="my_div" id="my_div_1">
and then you can use those id's to fill in the data:
$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);
and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:
$('.trigger_button_inside_divs').click(my_ajax_function);
var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}

bootstrap popover update content

how do you update the content of bootstrap popover after ajax success, I specifically need to change the value of the input field that I have but once I close the popover and click on it, the original value of the input field shows up? can someone help me out?
<button class="btn btn-primary edit" data-content='<input type="text" id="name" value="some value">
<button class="btn btn-primary save">Save</button>'>Edit</button>
JavaScript:
$('.edit').popover({
placement: 'left',
html: true,
});
$('body').on("click", ".save", function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "test.php",
data: {
name: name
},
cache: false,
success: function(response) {
if (response.indexOf("success") != -1) {
$('#name').val(name);
$('.edit').popover('hide').next('.popover').remove();
}
}
});
});
after the data is saved the popover is closed and when I click edit again the old value shows in the input box.
Please find enclosed a working demo of a popover that will be updated with the response from an ajax request.
I've removed your request parameters just for the demo to be able to do the request with mocky.io.
The trick was to use .attr('value', text) instead of .val(text). I'm not exactly sure what's going on here. Maybe someone can explain why that's different.
But with attr it changes the popover and it works.
Another thing that is required is to recreate the popover. I also wanted to destroy the first popover but that doesn't work. So I created the same popover again.
You can also find the same code here at jsFiddle.
There is a bug in the code here at SO. If you get the data from the server and then close the popover, the data will be reset to initial value.
Don't know what's wrong, because it works at jsFiddle with-out that bug.
Update 04.12.2014:
I've improved the code a bit. Now there is a close button in the popover and the data is stored so the data from server is still available when the popover is re-opened.
The bug mentioned above was probably not a SO issue, it was because the data from server was not properly stored. That is also fixed now.
I've also removed some not needed script tags in the demo because tooltip and popover are already included in bootstrap 3.
Update 05.12.2014:
I have another improvement to the code.
The line $(this).parent().find('.close').click(...) is not working like I wanted it. I wanted to add the handler only to the close button of the current popover. But it adds it to all elements with class .close.
Because $(this).parent() is the body element. I think it is better to do it like this:
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click({});
With aria-describedby you'll get the id of the current popover and then you can find the close button of that popover.
$(function () {
var editData = 'new value';
var doPopover = function (item, text) {
$('#name').attr('value',text); // use set attr and not val()
//$('#name').val(text); //<<<< not working here doesn't set DOM properly
var $pop = $(item);
$pop.popover({
placement: 'right',
title: 'edit <a class="close" href="#">×</a>',
trigger: 'click',
html: true,
content: function () {
return $('#popup-content').html();
}
}).on('shown.bs.popover', function(e) {
// console.log('triggered');
// 'aria-describedby' is the id of the current popover
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click(function(){
//console.log('close triggered');
$pop.popover('hide');
});
});
return $pop;
};
// enable popover
doPopover('.edit', editData);
// edit button click handler to show popover
$('.edit').click(function() {
doPopover('.edit', editData);
});
$('body').on("click", ".save", function (e) {
e.preventDefault();
var name = $('#name').val();
//console.log($popover);
$.ajax({
type: "GET", //"POST",
url: "http://www.mocky.io/v2/547f86501713955b0a8ed4da", //"test.php",
data: {
//name: name
},
cache: false,
success: function (response) {
editData = response.data;
doPopover('.edit', editData);
console.log('response: ', editData);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button class="btn btn-primary edit" data-html="true" data-toggle="popover" class="edit" data-title="Edit">Edit</button>
<div id="popup-content" class="hide">
<input type="text" id="name" value="some value" />
<button class="btn btn-primary save">Save</button>
</div>

Only slideUp the deleted message

I'm using a PM system and added the delete-message feature. I've got a form which checks for the message_id and message_title. The form posts to delete_message.php page which contains the query to delete the message. This has been done via Javascript as I dont want the page to refresh.
I've got two functions for this:
function deleteMessage() {
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(data,textStatus,jqXHR){ finishDeleteMessage(data,textStatus,jqXHR); }
});
}
function finishDeleteMessage( data , textStatus ,jqXHR ) {
$(".inboxMessage").slideUp('slow');
}
Currently when I click on the delete button (image of a trashcan) it deletes the message without reloading the page, as a finishing touch, it slidesUp the divclass (inboxMessage) the message is in. Since I tell it to slide up this class, it slides up every message. This is my piece of code containing the classes and the form:
<div class="inboxMessage">
<div class="inboxMessageImg NoNewMsg"></div>
<div class="inboxMessageHeader">
<a id="ajax" class="inboxMessageLink" onclick="showMessage('.$row['message_id'].')">'.$row['message_title'].'</a>
<p class="inboxMessageStatus Read">'.$inboxMessageStatus_Read.'</p>
</div>
<div class="inboxMessageDescription">'.$inboxMessageDescription.'</div>
<div class="inboxMessageActions">
<form id="delMsgForm" name="delMsgForm" action="message/delete_message.php" method="post">
<input type="hidden" id="msgTitle" value="'.$row['message_title'].'" name="message_title">
<input type="hidden" id="msgID" value="'.$row['message_id'].'" name="message_id">
</form>
<input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage()">
</div>
</div>
What I want it to do is to slideUp only the message which has just been deleted by the user. I know this has to be done by telling javascript to only slideUp the deleted message which contains the message_id and/or message_title.
I've tried several things, but no love whatsoever. I'm also not that familiar with javascript/ajax. Any help would be highly appreciate.
Cheers :)
where do you call deleteMessage from? indirect the function call through another function which knows the parent of your "trash can", and can call slide up on that specific one.
function deleteMessage (element) {
//element will be clicked button
var container = $(element).closest("div.inboxMessage"),
//container div including the trashcan
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(data,textStatus,jqXHR){
finishDeleteMessage(container);
}
});
});
and this will be your button
<input type="submit" id="ajax" value="" name="deleteMessageButton" class="deleteMessageIcon" onclick="deleteMessage(this)">
Apparently, you've got more divs with class inboxMessage. Since you're adding this code:
$(".inboxMessage").slideUp('slow');
.. all divs with that class will remove. If you want just one div to remove, give it a unique ID or data-attribute and hide it that way.
For example: add the message-id to the div..
<div class="inboxMessage" id="(message_id)">
..and use..
$(".inboxMessage#message_id").slideUp('slow');
.. to slide up the right div.
Edit:
Add your message ID to the div and to the function deleteMessage(), so it will be deleteMessage(message_id).
function deleteMessage(message_id) {
$.ajax({
url: "message/delete_message.php",
type: "POST",
data: $("#delMsgForm").serialize(),
success: function(){ finishDeleteMessage(message_id); }
});
}
function finishDeleteMessage(message_id) {
$(".inboxMessage#"+message_id).slideUp('slow');
}

Refresh a div in javascript

I wonder if it is possible to refresh a div tag in javascript?
My ajax script
<script type="text/javascript">
function actualiserDLIS()
{
var url = 'administration/gestionUtilisateurs.do?method=actualisationDLIs';
var params = 'DR='+encodeURIComponent(document.getElementById('selectDR').value);
var myAjax = new Ajax.Request(
url,
{ method: 'post',
parameters: params,
onComplete: majDLIS
});
}
function majDLIS(retour)
{
if (retour.status == 200)
{
document.getElementById('tableDLI').outerHTML = retour.responseText;
}else
{
document.getElementById('tableDLI').innerHTML = "uncool";
}
}
</script>
My html body
<h2 class="surlignageHaut">Restriction d'accés aux données</h2>
<label for="selectDR" >DR de l'utilisateur</label>
<html:select property="utilisateur.DR" size="1" styleId="selectDR" styleClass="saisie" style="position:relative;top:2px;left:5px;" onchange="actualiserDLIS();">
<html:optionsCollection property="optionsDRS" label="libelle" value="code"/>
</html:select>
<br/>
<br/>
<div id="tableDLI">
</div>
</div
when i select a data in my list, i do my ajax request and i have a table, when I reselect a different value in my list, my table does not update
for sure! by using ajax you can load content into your DIV-tags, as well as into many other DOM-Elements live.
Use the name of function which you describe inside the div.
Function to call the method:
window.setTimeout("name_of_the_function_present_in_div()",30000);
Here 30000 show 30 seconds, now you can modify the contents according to you requirement.

Categories