Populate Textbox with Session Variable When Opening New Window - ajax

I am attempting to populate a textbox in a new window with a Session variable from a parent window using an ajax call. When using Fiddler, I receive a 200 message, however, when ran from code, I'm getting a 500 Error.
I am aware that the ajax call is only returning an alert with the entire JSON result at this point because I haven't gotten to the step to actually pull the session variable yet.
Please offer any additional solutions to pull the Session variable from the parent window.
My JS from the parent is as follows:
function openRelatedItems(ReportID)
{
window.open('../WebUserProvider/ReportLibraryView.aspx?r='+ ReportID,'mywin','left=50,top=50,location=no,resizable=yes, status=yes, scrollbars=no, titlebar=no, channelmode=no, directories=no');
return false;
}
My JS from the window popup is as follows:
function callAjaxMethod() {
$.ajax({
type: "GET",
url: "ReportLibraryView.aspx/GetSetSessionValue",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
}
});
}
$(function () {
var value = callAjaxMethod();
var b;
});
My codebehind for the AJAX call is as follows:
[System.Web.Services.WebMethod (EnableSession = true)]
public static string GetSetSessionValue()
{
return HttpContext.Current.Session["AppealNo"].ToString();
}

Related

How can i get a value from the controller to my gsp page using AJAX

I am new to AJAX and grails so any help is appreciated. on my GSP page, on button click I am trying to retrieve a variable from the controller:
$.ajax({
url:'${createLink(controller: 'store', action: 'getNum')}',
type: 'GET',
dataType: 'json',
data: {num: num}, // the num is defined before and access properly
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
this is my controller function:
def getNum(){
String num = params.num
Long locnum = num as Long
int result = storeService.getNum(locnum)
String json = JsonOutput.toJson([count: result])
return json
}
I am going into the error and getting an "error" alert. I was wondering how I could utilize AJAX to get the number I need for my GSP page?
Thank you.
I would modify your JavaScript code like so:
$.ajax({
url:'store/getNum',
method: 'POST'
data: {'num': num}, // the num is defined before and access properly
error: function() {
alert("error");
},
success: function(data) {
alert(data);
}
});
And then modify your Grails controller code like so:
def getNum() {
Long locnum = = params.long('num')
int result = storeService.getNum(locnum)
return render([count: result] as JSON) // you will need to import grails.converters.JSON
}
A tip for the future is to set a breakpoint in your Grails controller method and run the application in Debug mode to ensure that the controller method is being called. If it is not being called, click on the Network tab on your internet browser's Developer Tools and then press the button on your GSP page to inspect the HTTP request being made by the AJAX call.

ASP.NET Core 2.2 Razor Pages - AJAX Call to page model not returning data

I am new to AJAX and cant even get the basics to function correctly.
I run an AJAX call from within a function in the javascript section from razor page but I cannot get the required string value to be returned.
The result I get in the alert box simply shows the HTML layout of the razor page as the message, as opposed to the actual string I want to return. I've spent hours trying to incorporate a X-CSRF-TOKEN in the header, but this makes no difference. I'm not sure the anti forgery token is required here and therefore the issue is before this step.
Razor Page:
$.ajax({
type: "GET",
url: "/Maps?handler=CanvasBackgroundImage",
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
Page Model:
public JsonResult OnGetCanvasBackgroundImage()
{
var result = "test message";
return new JsonResult(result);
}
Below is the code that is now working for me. Thanks for everyone's input.
Razor Page (script section):
function getMapBackgroundImagePath() {
// Get the image path from AJAX Query to page model server side.
$.ajax({
type: "GET",
url: "/Maps/Create?handler=MapBackgroundImagePath",
contentType: "application/json",
data: { imageId: imageId, }, // Pass the imageId as a string variable to the server side method.
dataType: "json",
success: function (response) {
copyText = response;
// Run the function below with the value returned from the server.
renderCanvasWithBackgroundImage();
},
});
}
Page model:
public JsonResult OnGetMapBackgroundImagePath(string imageId)
{
// Get the image full path where the id = imageId string
int id = Convert.ToInt32(imageId);
var imagePath = _context.Image.Where(a => a.ID == id)
.Select(i => i.ImageSchedule);
// return the full image path back to js query in razor page script.
return new JsonResult(imagePath);
}

How do I request views from a layout using AJAX?

In my MVC application I don't want the layout page to reload everytime a view is selected. It would be great if the views could be loaded using ajax to keep things nice and fast and allow me to persist certain interface states that are wiped out when you move around.
My initial approach was to add some ajax to the _Layout.cshtml and then whent he view was requested pass that request to the controller method which will grab that page. All I ended up doing however was returning the WHOLE view again.
Here is the code I have so far, am I on the right tracks here or is this totally wrong?
Layout Ajax Script
<script>
$(function () {
var content = document.getElementById('content');
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
console.log("Data Attrib : " + page);
$.ajax({
type: 'GET',
url: '#Url.Content("~/Home/")' + page,
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
</script>
As I say, this sort of works, but it's not perfect as it returns the whole page into the content area including layout, ideally I just want the core view data.
you can create a Single Page Application that have 1 layout and in home controller and index action method create menu or user setting or another things
and now you can load other action with Ajax call with data-content html that does not have layout file and append that in container
when user click another menu clean older content and add new or you can create tab strip or window
Layout.cshtml
<script>
$(function () {
//When a user selects a link, pass the data attribute and
//use it to construct the url
$('#sidebar a').on("click", function () {
var page = $(this).data('page');
$.ajax({
type: 'POST',
url: '/Home/Pages',
data: { pageValue: page },
success: function (data) {
$('#content').html(data);
console.log("Success");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("Error: " + thrownError);
}
})
})
});
Controller
public class HomeController : Controller
{
[HttpPost]
public string Pages(string pageValue)
{
string result = //Whatever
return result;
}
}
Controller
public ActionResult SomeAction(String someparams)
{
//Make the model
SomeModel someModel = new SomeModel();
someModel.someparams = someparams;
return PartialView("SomePartialView", someModel);
}
In View
$.ajax({
url: "/Home/SomeAction",
type: "POST",
dataType : "html",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
$('#SomeDivID').html(data);
}
});

Sapui5 navTo not working in ajax statement

I have a form in my page. When a user clicks a button if have no problem this code must navigate my Tile page. I am taking this problem:Uncaught TypeError: Cannot read property 'navTo' of undefined.
This my code:
onPressGonder: function (evt) {
var sURL = "xxxxxx";
$.ajax({
url: sURL,
dataType: "json",
success: function(data) {
if (data.ResultCode === 7) {
sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ;
} else {
sap.m.MessageToast.show("Login succesfull.");
sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile");
}
}
});
}
You are having a scope problem. The function provided as a success callback is a anonymous function called later on by jQuery.ajax. Therefore it is NOT a method of your controller and thereby does not know this. By default (as in your anonymous function) this refers to the window object. So what your basically doing is:
sap.ui.core.UIComponent.getRouterFor(window).navTo("Tile");
And the window object obviously does not have a router or a navTo method ;)
The easiest workaround is to make this available via the closure scope as follows:
onPressGonder: function (evt) {
var sURL = "xxxxxx",
that = this;
$.ajax({
url: sURL,
dataType: "json",
success: function(data) {
if (data.ResultCode === 7) {
sap.m.MessageToast.show("Error:" +data.Alerts[0].Message+"") ;
} else {
sap.m.MessageToast.show("Login succesfull.");
sap.ui.core.UIComponent.getRouterFor(that).navTo("Tile");
}
}
});
}
Another probably more elegant solution is to use the context property of jQuery.ajax. It will ensure that any ajax callback will be executed with the provided context (meaning whatever you pass as a context will be referred to as this inside your callbacks):
$.ajax({
...
success: function(data) {
...
sap.ui.core.UIComponent.getRouterFor(this).navTo("Tile");
},
context: this
});

jquery live() appending click events causing multiple clicks

I have some strange behaviour going on with the jQuery ajax functionality in my asp.net MVC3 application.
I have several boxes of data each containing a link to open a popup and change the data in each box. To do this I've added a jquery live() click event to process the data via a jQuery ajax call. In the "success" method of the ajax call, i take the return data and open a UI Dialog popup (a partial view) which contains a list of radio buttons. I select a different radio button and press 'close' - the close button fires another live() click event, processes that new data via an ajax call which refreshes the data in the box on the main page.
This works perfectly first time. If you then click to change it again, the popup opens, allows you to select a new value, but this time pressing close on the popup triggers two click events which throws an null error in my MVC controller.
If you repeat this process it triggers 3 click events, so it's clear that live() is appending these events somewhere.
I've tried using on() and click(), but the page itself is made up of panels loaded in via ajax so I used live() to automatically bind the events.
Here is the code I'm using:
HTML
<p><!--Data to update goes here--></p>
Update Data
First Click event calling popup with Partial View
$('a.adjust').live('click', function (e) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true
}
});
}
});
e.preventDefault();
});
Second click event the takes the new info to return updated partial view
$('a#close').live('click', function (event) {
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
$('#box-' + #column).html(response); //this refreshes the box on the main page
},
error: function () {
}
});
$('#ModalDialog').dialog('close');
event.preventDefault();
});
Anybody know what might be happening here, and how I could resolve it?
Use namespaces to unbind previous click binds like this:
$('a.adjust').unbind('click.adjustclick');
Then bind the click action to a.adjust:
$('a.adjust').bind('click.adjustclick', function(){
//your code here
//note the return false, this prevents the browser from visiting the URL in the href attribute
return false;
});
If i understand you correctly, you try to run the second click action when the dialog is closed. Therefor I would use the build in close function for the dialog like this:
$('a.adjust').bind('click.adjustclick', function(){
var jsonData = getJsonString(n[1]);
var url = '#Url.Action("ChangeOptions", "Search")';
var dialog = $('<div id="ModalDialog" style="display:none"></div>').appendTo('body');
// load the data via ajax
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (response) {
dialog.html(response);
dialog.dialog({
bgiframe: true,
modal: true,
close: function(){
var jsonData2 = getJsonString(n[1]);
var url2 = '#Url.Action("GetChangeInfo", "Search")';
$.ajax({
url: url2,
type: 'POST',
contentType: "application/json; charset=utf-8",
data: jsonData2,
success: function (response2) {
$('#box-' + #column).html(response2); //this refreshes the box on the main page
},
error: function () {
}
});
}
}
});
}
});
});
If you are using your own button a#close, bind a click event to it to close the dialog, it will automatically fire the close function for the dialog.
$('a#close').unbind('click.closedialog');
$('a#close').bind('click.closedialog', function () {
$('#ModalDialog').dialog('close');
return false;
}
Try this:
$('a#close').unbind('click').bind('click', function (event) {
//Your Code
});

Resources