Grails render gsp page after popup window - javascript

I have a popup window using twitter bootstrap, then I have a javascript that call a controller action. On that controller action I render a string to be displayed in the popup window. And on that action I have another render, It render the gsp page itself because a value is added in a textarea. How to make the second render work?
GSP:
<g:javascript>
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
}
}).success(function(data) {
$('.modal-body').html(data);
$('#myModal').modal('show');
});
}
</g:javascript>
<g:textField name="inputField" />
<!-- Button to trigger modal -->
+
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Members</h3>
</div>
<div class="modal-body">
</div>
</div>
<textArea name="listField" id="listField" rows="50" cols="6" readonly>${params.Result}</textarea></td>
Controller:
def addEG_Create = {
def LdapName
def result
def membersString = ''
def members = ''
result = proxy.getWLSGroupParticipants(params.inputField)
if(result != null){
params.egId = params.id
LdapName = proxy.getWLSGroupsForUser(result[0])
int index
if (LdapName.size()>1){
index = 0
//find the index number for the correct Ldap name
for (int i = 0; i < LdapName.size(); i++) {
if (LdapName[i].toUpperCase() == params.inputField.toUpperCase()){
index = i
}
}
}else{
index = 0
}
if(params.listField.find(LdapName[index])){
params.Result = params.listField.trim()
membersString = params.listField.replace('\n',',')
flash.message = params.inputField + " exist in the list!"
}else{
flash.message = ""
if(params.listField!=''){
if(params.listField.charAt(params.listField.length()-1)=='\n'){
params.listField = params.listField.substring(0,params.listField.length()-1)
}
params.Result = params.listField.trim() + '\n' + LdapName[index].trim()
membersString = params.Result.replace('\n',',')
//membersString = params.listField.replace('\n',',') + LdapName[index]
} else{
params.Result = LdapName[index].trim()
membersString = LdapName[index]
}
}
for (int i = 0; i < result.size(); i++) {
if(i == 0){
members = result[i].trim()
}
else {
members = members + '\n' +result[i].trim()
}
}
params.Members = members
} else {
flash.message = params.inputField + " not found in LDAP. Please contact TECH CUST CARE"
params.Result = params.listField.trim()
membersString= params.listField.replace('\n',',')
//println "Not Found"
}
membersString = membersString.replace('\r','')
MGExecutingGroupInstance.members = membersString.trim()
render(members)
render(view:'create')
}

Jeka, you can't render two thinks like this
render(members)
render(view:'create')
the better way i see you can do this is something like this:
In your controller you can render your data as JSON:
def addEG_Create () {
...
...
render([members:members, openWin:'create'] as JSON)
}
And in your .gsp you should do shomething like this:
function callEgCreate(){
$.ajax({
type: "GET",
url: "${createLink(controller: 'MGExecutingGroup', action: 'addEG_Create')}",
data: {
"inputField="+$("[name='inputField']").val()
"listField="+$("[name='listField']").val()
},
dataType: 'json',
success(function(data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
$('#myModal').modal('show');
});
}
I don't have tested this code, maybe it can have some errors, but the logic is this.
Updated
function callEgCreate() {
$.ajax({
type: "GET",
url: "testeChamada",
data: {"inputField": $("[name='inputField']").val(), "listField" : $("[name='listField']").val()},
dataType: 'json',
success: function (data) {
window.open(data['openWin']);
$('.modal-body').html(data['members']);
console.log(data['members']);
}
});
}
Ps1: In your controller when you say render render([members:members, openWin:'create'] as JSON) you have to receive the data in your page with the key of map [key:value]
Ps2: In your data: you have made a mistake. It should be a map with Key:Value

Related

How to get a value from controller and use this in javascript using MVC?

In my project , I get the error and success notifications as TempData from controller and in view , if they're not null I show user a notification seperately. Ever since I start to use FilePond , my TempData values became invisible. Hence, I try to add if-else conditions to javascript so I can show the notifications again. But the problem is , I can't get the TempData value to use in javascript. I researched and tried all recommendations but it still returns null. Any Idea how can I fix this ? I'm so close to end this but the only problem is TempData now.
My Controller (I made it shorter but in debug , I can get the tempdata value so nothing is wrong in here)
[HttpPost]
public async Task<IActionResult> Create(SaveCommand command)
{
TempData["error"] = _localizationService.GetLocalizedHtmlString("error");
return View();
}
View / Javascript Part (var test returns null)
<script type="text/javascript">
var myJsVariable = null;
var test = #Json.Serialize(#TempData["error"]);
$(document).ready(function (e) {
pond = FilePond.create(
document.querySelector('#ImageUrl'), {
allowMultiple: true,
instantUpload: false,
allowProcess: true
});
var frm = $('#form2');
if (myJsVariable != null) {
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal3").modal('show');
})
}
else if(myJsVariable ==null){
console.log("fail")
frm.submit(function (e) {
e.preventDefault();
var formdata = new FormData(this);
pondFiles = pond.getFiles();
for (var i = 0; i < pondFiles.length; i++) {
formdata.append('ImageUrl', pondFiles[i].file);
}
pond.removeFiles(pondFiles);
$.ajax({
url: "/test/create/",
data: formdata,
processData: false,
contentType: false,
method: "post"
}).done(function (response) {
});
$("#modal2").modal('show');
})
}
});
</script>
}
ps : This was a problem for a while so I created a random myJsVariable to understand where the problem is. But instead of using this , I need to use my tempdata values. (I cant even show my tempdata values inside my modals.)
This was a problem for a while so I created a random myJsVariable to
understand where the problem is. But instead of using this , I need to
use my tempdata values. (I cant even show my tempdata values inside my
modals.)
Well, the way are you trying to Retrieve value from temp data is incorrect. Here '' is very important. You could use below pattern to extract your #TempData["error"] then bind to javascript easily.
var tempData = ('#TempData["error"]');
Working Example For You:
Controller:
public IActionResult TempDataView()
{
TempData["error"] = "Temp Data From Controller";
return View();
}
Modal:
<div class="modal" tabindex="-1" role="dialog" id="formModal">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header" id="formModal">
<h5 class="modal-title"></h5>
</div>
<div class="modal-body"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<a onclick="BindTempDataToJavascript('#Url.Action("TempDataView","Todo",null,Context.Request.Scheme)','Bind Temp Data To Javascript')" class="btn btn-success text-white"><i class="fas fa-random"></i> Bind Temp Data To Javascript</a>
Script:
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script>
<script type="text/javascript">
BindTempDataToJavascript = (url, title) => {
//Retriving Temp Data and Binding to Javascript variable
var tempData = ('#TempData["error"]');
alert(tempData);
console.log(tempData);
$("#formModal").find(".modal-body").html(tempData);
$("#formModal").find(".modal-title").html(tempData);
$("#formModal").modal('show');
};
</script>
Output:

Modal Not Show Before ajax

I have an Javascript on click event that will loop all of the json to store it to database with ajax and before that i already add some modal to popup before the loop is running. but the problem is the modal doesn't pop up before the loop is running and pop up after the loop is running this is my code
this i my javascript
$.fn.dataTable.ext.buttons.Mapping = {
text: 'Save To Database',
action: function (e, dt, node, config) {
$('#modal-respondent-upload').modal('show');
var filename = $("#xlf").val().replace("C:\\fakepath\\", "");
var obj = jQuery.parseJSON(output);
$.each(obj.hasil, function (key, value) {
var dataRespondent = {
json: JSON.stringify(value),
importSessionDataID: 1
}
console.log(dataRespondent);
var respondentID = simpleAjaxRequest(dataRespondent, "/UploadExcel/CreateRespondent/", "Import Respondent Data");
});
}
};
function simpleAjaxRequest(data, url, text) {
var id = 0;
$.ajax({
type: 'POST',
url: url,
data: data,
async: false,
success: function (data) {
//moveProgressBar(10, text);
id = data;
}
});
return id;
}
and my modal is like this
<div class="modal fade" role="dialog" id="modal-respondent-upload">
<div class="modal-dialog">
<div class="modal-content">
<h1><span id="kondisi-data-modal">0</span>/<span id="jumlah-data-modal">0</span></h1>
</div>
</div>
</div>

Ajax passing value to PHP

I would like to pass multiple values to php via ajax (on same page), here's my code:
HTML (user_list.php):
<button type="submit" class="button button-block savebutton" name="save_changes"/>
Save changes</button>
Javascript (user_list.php):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
PHP (user_list.php):
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['delete_selected'])) { // Button to delete selected user(s)
if (!empty($_POST['check_list'])) {
foreach ($_POST['check_list'] as $id) {
$sql = "DELETE FROM users WHERE id=$id";
$mysqli->query($sql);
header("Refresh:0"); //Refresh page
}
}
}
// Other if above works fine
elseif (isset($_POST['result'])){
// I want to get the js array with the values here after ajax
}
else {
// But I get here, and I don't get the js array
}
}
So I have 2 problems, the first is that I pass the elseif, and the second is that I dont get the array. I think the problem is with ajax, since filling the array works properly
EDIT: I moved the php to a different page, now it's working.
Though your Ajax request is initiated, a "normal" submit request is also started, when you press the button. To prevent the second request (thus keeping only the Ajax request), you have to return false; at the end of your onclick callback.
Solution #1:
$(".savebutton").on("click", function () {
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
return false;
});
Solution #2 (as also suggested by #charlietfl):
$(".savebutton").on("click", function (event) {
event.preventDefault();
var js = [];
var i = 0;
$('select').each(function () {
var a = {"id": "", "permission": ""}
a.id = $(this).val();
a.permission = $(this).children(":selected").text();
js.push(a);
alert(js[i].permission + " - "+js[i].id);
i++;
});
$.ajax({
type: "POST",
url: "user_list.php",
data: {result: JSON.stringify(js)}
});
});
It seems that when you're submitting the POST request, the data is coming as their own POST fields. Simply check for the values of what you submitted. For example, if you had done the same, but put foo as bar and hello as world, you could check for foo and hello with something like this:
elseif (isset($_POST['foo'], $_POST['hello']) {
# your code
}
$('.savebutton').click(function (e) {
e.preventDefault()
var js = []
var i = 0
$('select').each(function (i) {
var a = {}
a.id = $(this).val()
a.permission = $(this).children(':selected').text()
js.push(a)
alert(js[i].permission + ' - ' + js[i].id)
})
js = JSON.stringify(js)
$.post('user_list.php', {result: js}
})
Try with this
<button type="submit" class="button button-block savebutton" name="save_changes[]"/>Save changes</button>

display json in popup returning ActionResult

I have a custom controller in mvc and the ActionResult is:
[HttpPost]
public ActionResult Details([DataSourceRequest]DataSourceRequest command, int id)
{
//var userDetail = _CustomerDetail.GetAllCustomers();
var genericDetail = _GenericDetail.Table.Where(x => x.EntityId == id).Select(z => new { z.Key, z.Value }).ToList().AsQueryable();
//var userData = from ud in userDetail
// join gd in genericDetail
// on ud.Id equals gd.EntityId
// select new { gd.Key, gd.Value };
DataSourceResult result = genericDetail.ToDataSourceResult(command);
return Json(result, JsonRequestBehavior.AllowGet);
}
which is returned an object like this:
{"Data":[{"Key":"Gender","Value":"F"},{"Key":"FirstName","Value":"h"},{"Key":"LastName","Value":"h"},{"Key":"DateOfBirth","Value":"1914-05-03"}],"Total":4,"AggregateResults":null,"Errors":null}
and my ajax and bootstrap popup codes are:
$.ajax({
type: "POST",
url: "/UserDetails/Details",
data: { id: dataItem.Id },
success: function (result) {
$('#dvDetail').html(result);
$('#myModal').modal('show');
},
error:function(){
alert('fail');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">User Detail</h4>
</div>
<div class="modal-body">
<div id="dvDetail"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I want to display my json object returning in 2 columns which are Key and Value and try many solutions of stackoverflow but did not success.
can anybody help me?
You need to give that object a template to render the data as a two column table/div, etc.
You can define a template function like this:
userDetailTemplate = function(data){
var renderRow = function(val){
return "<tr>" + val + "</tr>";
}
var renderCol = function(val){
return "<td>" + val + "</td>";
}
var renderContent = function(val){
return "<table>" + content + "</table>";
}
var content = [];
for(i=0; i<data.length; i++){
var key = renderCol(data[i].Key);
var val = renderCol(data[i].Value);
content.push(renderRow(key+val));
}
return renderContent(content.join(''));
}
In the Ajax callback, you need to call this template function.
success: function (result) {
$('#dvDetail').html(userDetailTemplate(result.Data)); // or this should be result. You need to try either of these.
$('#myModal').modal('show');
},

Nested $.getJSON() can not get correct answer? [duplicate]

This question already has answers here:
Calling an asynchronous function within a for loop in JavaScript
(10 answers)
Closed 6 years ago.
I am just learning Jquery from freecode.camp and I am writing some code to Use the Twitchtv JSON API ( https://www.freecodecamp.com/challenges/use-the-twitchtv-json-api).
When I want to get five channels logo on Twitch.tv ,but when I write the code ,I just found there was four same logo ,it was never what I want .
I have a codepen at http://codepen.io/zhangolve/pen/JKOXwW?editors=1111 ,if you like ,please check it out.
this is the JS code:
$("#click").on("click", function() {
var channel = ['OgamingSC2', 'FreeCodeCamp', 'terakilobyte', 'storbeck', 'RobotCaleb'];
for (var i = 0; i < channel.length; i++) {
var url = 'https://api.twitch.tv/kraken/streams/' + channel[i] + '?callback=?';
var thechannelurl = 'https://api.twitch.tv/kraken/channels/' + channel[i] + '?callback=?';
$.getJSON(url, function(data) {
if (data.stream == null) {
$.ajax({
dataType: "json",
url: thechannelurl,
//data: data,
type: "GET",
success: function(w) {
$("#content").append('<img src=' + w.logo + '> </img>')
}
});
} else {
var logo = data.stream.channel.logo;
//console.log(logo);
$("#content").append('<img src=' + logo + '></img>');
}
})
}
})
I forked your pen ...
Here is the code working:
http://codepen.io/rafaelcastrocouto/pen/rLYWXV
One channel in your list has no logo ... so I used a placeholder image.
var channelAPI = 'https://api.twitch.tv/kraken/';
var channels=['OgamingSC2',
'FreeCodeCamp',
'terakilobyte',
'storbeck',
'RobotCaleb'];
var getJSONCallback = function (data, url) {
if (data && data.logo) {console.log('1', data.logo)
appendLogo(data.logo);
} else if (data &&
data.stream &&
data.stream.channel &&
data.stream.channel.logo) {console.log('3', data.stream.channel.logo)
appendLogo(data.stream.channel.logo);
} else if (url && url.channel) {console.log('2', url.channel.toString())
$.getJSON(channelAPI+'channels/'+url.channel, getJSONCallback);
} else {
appendLogo('https://placeholdit.imgix.net/~text?txtsize=63&bg=FF6347&txtclr=ffffff&txt=No Logo Found&w=302&h=302');
}
};
var appendLogo = function (logo) {
$("#content").append('<img class="img" src="'+logo+'"></img>');
};
var clickFunction = function() {
for(var i=0;i<channels.length;i++) {
var channel = channels[i];
$.getJSON(channelAPI+'streams/'+channel, function (data) {
getJSONCallback(data, {channel: this});
}.bind(channel));
}
};
$("#click").on("click", clickFunction);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click" class="btn btn-primary" >click</button>
<div id="content"></div>

Categories

Resources