jQuery.ajax({type:'POST' in grails - javascript

First of all thanks to you all for your valuable suggestion.I got stuck one problem that is in jQuery ajax call in grails remote function call on controller.
The plug-ins installed in my project are: jQueryUi - 1.10.3, jQuery - 1.11.0.
My controller this method:
def loadamount(){...}
And for ajax call method:
def ajaxCallBalance(long id){
def userBalances=loadamount(id)
def userBalance=userBalances[0] //it returns in array
return [usreBalance:userBalance]
}
These are nothing but my database call to load user amount in his a/c that should load on page load inside user profile html page. So for that i use this:
Point 677:
<g:if test="${session.LogedUser}">
<script>
${remoteFunction(
controller:'user',
action:'ajaxCallBalance',
update:[success:'uresult',failure:'uresult'],
id:session.LogedUser.id
)}
</script>
In HTML:
<li id="uresult"><!-- Want to see hare what result either value or error it returns --></li>
In firebug console I see get this error:
SyntaxError: syntax error
<script>
jQuery.ajax({
type:'POST',
url:'/...../..../ajaxCallBalance/10000000',
success:function(data,textStatus) {jQuery('#uresult').html(data);},
error:function(XMLHttpRequest,textStatus,errorThrown)
jQuery('#uresult').html(XMLHttpRequest.responseText);
}
});
</script>
[Note:This is generated by grails ajax plugin what i have wrote is see point 677.]
Here is my Question:
Why is this $#39; appearing even though I have no space, nor any symbol. Is it a bug or my mistake?
Is there any way to handle this kind of scenario as user onLoad/(document).ready() call for such conditions. If Yes, then what I will do?

You can't just use the grails construct of ${remoteFunction...} in js directly. use ajax:
$.ajax({
type: 'POST',
url: "${createLink(action:'ajaxCallBalance', controller:'user')}",
data: { id: id },
success: function (dataCheck) {
//Do stuff
}
........
});
or use g:remoteFunction like this way
$('mydiv').onclick = <g:remoteFunction action="ajaxCallBalance" controller="user" id="${id}" />

Related

How to parse JsonResult object from controller in MVC?

I am trying to learn asp.net. I am making a demo website in which there would be an admin panel. The admin would update the Daily Messages which will get reflected in the main homepage. I am using MVC.
I have created the table in database as
create table DailyMsg(Sno int primary key, msg varchar(max));
This is my controller
public class DailyMsgsController : Controller
{
private amenEntities db = new amenEntities();
// GET: DailyMsgs
public ActionResult Index()
{
return Json(db.DailyMsgs.ToList(),JsonRequestBehavior.AllowGet);
}
}
On running the following URL, I am successfully able to see the data in JSON format.
https://localhost:44329/DailyMsgs
[{"Sno":1,"msg":"Hi!"}]
Now, I am stuck. I know that I would have to add another class for Data Access Layer, but I am confused as how should I parse this data and print it to the main HTML page.
From my research on the internet, I have found out that I might have to use JQuery. So, I wrote the following(with what I could understand from the internet as I am not familiar with JQuery) -
$.ajax({
url: "/DailyMsgs/Index",
type: "GET",
success: function (data) {
$("#div1").html(data);
}
});
This, of course, is not working and I can't see anything on my webpage.
My Homepage.html
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
</body>
</html>
<script src="../Scripts/jquery-1.8.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
<link href="../Content/bootstrap.css" rel="stylesheet" />
<script src="../JQuery/DailyMsgsJQ.js"></script>
All I want is to read and parse msg from JSON and display it on webpage.
Could you guide me as how should I proceed or is there any other way to achieve the purpose? Thanks a lot!
Try this
$.ajax({
url: "/DailyMsgs/Index",
type: "GET",
success: function (data) {
$.each(data, function (index, element) {
$("#div1").append(element.msg);
});
}
});
If you still have error please get console.log(data); and send for me.
Your <script> tags are outside your <html> tag. That means the scripts are probably not even executed, or not loaded in the correct order. You want jQuery and Bootstrap to be loaded first, so put them in the <head>. Put your custom script just before the closing </body>, so it is loaded last.

jQuery-ui Autocomplete not finding control on Master page

I'm struggling with the jQuery-UI Autocomplete on a master page.
I've loaded the jQuery.js and jQuery-ui.js in that order, in the head section of the master page.
What I need to do is very common, I'm sure, but perhaps the idea it's on a master page is getting in the way.
Here is <body> code that will fill the autocomplete input (id=autocomplete) with hard-coded values outside an ajax call.
I realize it's useless to call ajax for data and not use it, but I'll deal with that later...baby steps
<%-- Trying some autocomplete stuff --%>
<label for="autocomplete" style="color:yellow;">Language: </label>
<input id="autocomplete" />
<script type="text/javascript">
var wsUrl = '<%= ResolveUrl("http://localhost/CommonContent/CCWebService.asmx/HelloWorld") %>';
var fillMe = "[id$='autocomplete']";
$.ajax({
type: "POST",
url: wsUrl,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (dave) {
alert(dave);
//FillAutocomplete(fillMe);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("1!\n" + errorThrown + "\n" + jqXHR + "\n" + textStatus);
}
});
FillAutocomplete(fillMe);
function FillAutocomplete(id) {
autodata = ["c++-001", "java-002", "php-003", "coldfusion-004", "javascript-005", "asp-006", "ruby-007"];
alert(autodata);
//$("[id$='autocomplete']").autocomplete({
$(id).autocomplete({
source: autodata,
select: function (event, ui) {
var label = ui.item.label.split('-')[0];
alert(label);
var value = ui.item.value.split('-')[1];
alert(value);
//store in session
document.valueSelectedForAutocomplete = value
}
});
alert("Filled");
}
</script>
Again, this WORKS (but the data is hardcoded). I get the alerts in the following order: success from ajax, then the autodata, then the filled notice.
Additionally, it works if I use the fillMe variable set to "#autocomplete" or if I hard code it in the FillAutocomplete function.
Obviously, since it works, the input is able to have the autocomplete property.
Here's everywhere else where I tried that I simply get
Object doesn't support property or method 'autocomplete'
Putting the autocomplete code directly inside the success
Call the filling of the autocomplete INSIDE the success of the ajax call (uncomment //FillAutocomplete) (comment the other call)
Starting with $(function() {
$('#autocomplete).autcomplete({...
Using some form of <#='autocomplete.ClientID()'#>
I have a sneaking suspicion it's not finding the control, not really that the control doesn't have support it.
Any ideas?
UPDATE: More Information
I've added the screenshot below to show the error in its full glory. And sorry for repeating myself but I'm wondering if it's due to master page somehow, or somehow the jquery-ui is NOT loading before the call to the autocomplete method (since it's "object doesn't support....")
The Cause and Solution:
It seems that the Ajax call was trying to complete before the remote file jQuery-UI was loaded. As RAM suggested in the comments below, I downloaded all remote files and they're part of the project now. Now the scripts load in the correct order and the autocomplete method is available on the input. Thanks RAM.
Here is an example to how to use jquery autocomplete in asp.net
http://www.dotnetlearners.com/blogs/view/102/JQuery-ajax-autocomplete-extender-textbox-using-json-response-type.aspx
The Ajax call was trying to complete before the remote file jQuery-UI was loaded. As RAM suggested in the comments, I downloaded all remote files and they're part of the project. Now the scripts load in the correct order and the autocomplete method is available on the input.
Thanks RAM - that did it.

Dynamic use of g:message in Javascript

is there an easy way to use the g:message functionality in a dynamic way in Javascript, e.g.
function get_i18n( myAttr ) {
return "${message(code:'" + myAttr + "')} ";
}
so that I can perform the function call
pl_get_i18n( "xyz" )
for the predefined i18 attribute xzy ?
Like here, but dynamic: https://stackoverflow.com/a/8296812/1779814
PS: The JS code is included in the GSP file.
The short answer is "no". GSP tags can only be executed on the server-side, not by the browser (i.e. JavaScript).
However, I would expect there is at least one Grails plugin that does the following:
creates a JavaScript object containing the messages defined in your messages*.properties file(s)
provides a JavaScript function that enables you to resolve messages from this object
So although it's not possible to execute GSP tags in the browser, it doesn't seem terribly difficult to provide equivalent functionality in JavaScript. I would be amazed if there isn't already a Grails plugin that does this.
Here is a very simplistic example of how you can use AJAX to fetch a message code from the server.
// AjaxMessageController.groovy
package example
import grails.converters.JSON
class AjaxMessageController {
def index() {
render [message: message(code: param.code)] as JSON
}
}
Then within your page you can just use an ajax call (jQuery based) in this example to look up a message code:
var someMessageCode = 'something.you.want';
$.ajax({
dataType: 'json',
url: '${createLinK(controller: "ajaxMessage", action: "index"}',
data: {code: someMessageCode},
success: function(data) {
window.alert(data.message);
}
});

ASP.NET MVC 3 - After ajax call, redirect to new page or generate page refresh

Scenario:
I have written an MVC wizard that automatically uses ajax if javascript is enabled in the browser. Each step of the wizard is a PartialView (I'm using ASP.NET MVC 3).
All works fine.
The problem is refreshing the page if, for example, the user's status changes as a result of how she fills in the wizard. EG, if the wizard logs the user in, or registers them. As the wizard 'moves' from step to step by getting Partial Views via AJAX, the page doesn't get refreshed to reflect the change in the user's status (eg, an anonymous user is now registered).
What I want to do:
Essentially, when I need a full page refresh, I need to AUTOMATICALLY run the following on the client AFTER delivering the Partial View corresponding to the current step of the wizard via AJAX:
location.reload();
The Problem:
As the DOM has been modified via AJAX, I don't know how to make my javascript (location.reload();) run WITHOUT user intervention (eg, clicking a button).
Any suggestions? I have been off work for a while and am struggling to get back up to speed.
For now, I have solved my problem using the code in the following article:
Redirecting after AJAX call, when using ASP.NET MVC
I like the approach discussed in the article because it results in reusable code, in a very MVC way - I already have a base controller (AjaxController.cs) where I encapsulate all my AJAX aware code and this is a nice addition to it.
However, there are two issues with this approach:
I have to redirect away from my wizard, so it only works for the final step of the wizard. If the user's status changes half way through the wizard, I am still jiggered.
I would still like to know how to refresh my page after an AJAX call, rather than just redirecting like this.
So if anyone has the answer, I will gladly give them the biscuit.
I am not quite sure how your ajax calls are structured, but if you are using the MVC Ajax helper you can just call location.reload(); in the OnComplete method, like so:
#using (Ajax.BeginForm(new AjaxOptions{OnComplete = "javascriptfunction"}))
{
//Data and submit button
}
<script>
function javascriptfunction(){
location.reload();
}
</script>
// C# code
public ActionResult Foo(Bar bar)
{
// code here
return Json(new
{
Success = true,
Value = this.RenderPartialViewToString("PartialViewName", bar),
Callback = "window.location.href = 'http://yourdomainurl.com/';"
});
}
// jQuery Ajax
$.ajax({
type: "POST",
url: "/urlWhereToPost",
data: ("form#id").serialize(),
dataType: 'json',
async: false,
beforeSend: function() {
// some instruction
},
error: function(e) {
alert(e.responseText);
},
success: function(data) {
if (data.Success) {
if (data.Callback != null) {
if (data.Callback.length > 0) {
jQuery.globalEval(data.Callback);
}
}
}
else {
// do something
}
}
});

How to get data returned from Ajax appended to a div? -- JQuery + Rails 3.1

I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.

Categories