Grails: Passing a javascript variable to a template - ajax

I am new to ajax so maybe this is obvious. I've tried many different not-working approaches. I have javascript that when you click on a button:
an ajax call that grabs some data from a controller - returns an object
display that data in a template that I will show on the page
Here is the javascript/ajax:
<script type="text/javascript">
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Here is the key line in grails view template:
<g:each in="${allResults}" status="i" var="result">
How do I get the data from the javascript to the gsp code (ie allResults)?
Do I have to "refresh" this template to display new data?
thanks.

You just can't make your javascript/jquery code populate things in the gsp, since the gsp is processed server-side and javascript is processed client-side, after the gsp rendered all html documents and populated them with your model. You need to be aware that your page was already processed, so things like ${variables} won't be reloaded anymore. So when you do this:
$(".resulttable").show();
It's not gonna show the result you're waiting for. You have to use javascript code to reload your result table.
So if you're using ajax here, you should use the function success to alter your html table via javascript/jquery since you already have the response you wanted. Maybe this read can help you. Oh, and I think it would be better if in your ajax call, you would define a dataType (json works great in your case), like this:
$("#show").click(function () {
$.ajax({ url: '/Myproject/result/index',
type: "POST",
data: { id: id},
dataType: 'json',
success: function(result) {
alert("Success:" + result); // Can see getting object back.
}});
$(".resulttable").show();
});
Just to make clear what kind of response you're getting from the controller.

You do not need to write your ajax calls the hard way. There are some Grails intern tags you can use inside your html:
http://grails.org/doc/latest/ref/Tags/remoteFunction.html
http://grails.org/doc/latest/ref/Tags/submitToRemote.html
http://grails.org/doc/latest/ref/Tags/remoteLink.html
Following the links you will find some nice examples...

Related

get data from ajax as an attribute value for callback function

Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async

Rails allow POST for Ajax on index action without breaking CREATE

I have a simple setup for a resource, currently in routes.rb I have:
resources :leave_requests
This works exactly as expected, on the index view I have a datatable setup using Ajax via a GET, this is also working but the URI is getting very large during the Ajax request. I would prefer this to be a POST action, for this to work I require a POST instead of a GET on the index action in my routes.
However, this will break the CREATE action i.e. will simply load the index page on submitting a new request. i.e. If I do this:
post '/leave_requests', to: 'leave_requests#index'
resources :leave_requests
How can I get these to co-exist happily?
Have you try to do something like in this Rails , Ajax , Post Function , Jquery the code looks something like
$('form').submit(function()
{
var myForm = $('form').serialize();
$.ajax
({
url:'/leave_request/create',
type:"POST",
dataType:'json',
data: myForm,
processData:false,
success: function (msg)
{
alert(msg);
},
error: function (xhr, status)
{
alert(xhr.error);
}
});
});
you can also take a look at jQuery post to Rails

.done attachment not working with ajax update to file, works with read from file

Attaching .done .fail and .always to ajax calls is now doable for me - it is "easy" when the script is at the bottom of the html page.
Now I want to create generalized ajax functions that I can use just by including a js file in the header. I've been successful with ajax functions that read data from server (.done always works). I'm having problems when I just write or update data to the server (no return of data). Here are the specifics-
Standard ajax add/update call that always works - in script tags at bottom of page.
$.ajax({
type: 'POST',
url: 'supdateajaxfunctiontestbackend.php',
data: {localid: localid,
firstname: firstname,
lastname: lastname}
}).done(function(){ alert('Done with Add/Update!'); });
If I create a function at the bottom of the page, or add the function to a js file, this add/update always works.
function generalWriteAjax(filetocall, datatosend) {
$.ajax({
type: 'POST',
url: filetocall,
data: datatosend
}).done(function(){ alert('Done with Add/Update!'); });
}
I would like to detach the .done from the function, and call the .done when attached to a separate function/object. The following code works fine WHEN THERE IS DATA RETURNED FROM THE SERVER. (a separate generalReadAjax function that asks for server data). The done is attached to an object that is returned from the server (This concept I found here on Stackoverflow).
backenddata = generalReadAjax('readtesttablebackend.php');
displayData(backenddata);
backenddata.done(function(){ alert("Done with read!"); });
});
I have tried all of the following with the WRITE/UPDATE only function, and none of them work.
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).when(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update).then(function(){ alert('Done function'); });
generalWriteAjax(filetocall4update, datatosend4update);
createdonealert = generalWriteAjax(filetocall4update, datatosend4update);
createdonealert.done(function(){ alert('Done function'); });
createdonealert.when(function(){ alert('Done function'); });
createdonealert.then(function(){ alert('Done function'); });
So obviously, there is a difference in the way the promise is handled between a "go get me data" and "here is data, please store it".
I even put an echo "Done"; at the bottom of the update php file just to return something, and still no luck.
I've searched this site and google with combinations of:
ajax .done attach add update not working promise
and have found nothing that deals with my specific example.
Can someone give me some guidance?
I thank you in advance.
Well, no one has responded, and I've learned a bit by hacking on this for the last day. Here are some things I THINK I've learned:
If you create a general callable function using ajax, it does not act the same as an "inline" ajax - you do not get the same callback actions as you do when the ajax code is at the bottom of an HTML page between script tags.
If you return something from the server, the ajax function acts similarly to when it is between script tags.
If you DO NOT return data from the server, the ajax function does NOT act the same as when it is inline.
So what I've done is on all php files that are "write/update" only (no data returned), I add a little code to the bottom of each php file that returns a small amount of json "junk". With this "junk" the ajax function acts like a regular ajax call between script tags at the bottom of the page.
It's a kludge, but it works. Here is the code at the bottom of a read/update php file that normally would NOT return anything. It now returns a json array regarding "John":
$json = array('firstname' => 'John');
echo json_encode($json);
Here is the function in the attached js file:
function generalWriteAjax( filetocall, datatosend ) {
return $.ajax({
type: 'POST',
url: filetocall,
data: datatosend,
dataType: 'json'
});
}
Here is the code on the page that calls the .js function:
$("#clicktoupdate").click(function(e) {
var localid = $('#idnumber').val();
var firstname = $('#updatefirstname').val();
var lastname = $('#updatelastname').val();
var filetocall4update = 'supdateajaxfunctiontestbackend.php';
var datatosend4update = {localid: localid, firstname: firstname, lastname: lastname};
generalWriteAjax(filetocall4update, datatosend4update).done(function(){ alert('Done inline'); });
});//end of update click
I wish I understood the details, but this is an empiric solution that works.
Comments from the experts would be nice.
Thanks for looking!

DJANGO Jquery/ajax get 'httpresponse' JSON

I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.

How to send and retrieve cross-domain ajax data in userscript

I use this code to store and retrieve ajax data via http://openkeyval.org/
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify([123,456]),
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
$.ajax({ /* retrieve data */
url: "http://api.openkeyval.org/test-key-data",
dataType: "jsonp",
success: function(data){
console.log(data);
}
});
everything work fine in Chrome javascript console but in userscript I get error like this
Uncaught ReferenceError: jQuery110208458673823624849_1375932537303 is
not defined
I try to use GM_xmlhttpRequest to retrieve data like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data",
onload: function(response) {
console.log(response.responseText);
}
});
but it seem like openkeyval doesn't accept data via POST/GET method and log result was like when you access it directly from url of browser like this
{"error":"not_found","documentation_url":"http://openkeyval.org/"}
I include jQuery and it work fine with this code
// #require http://code.jquery.com/jquery-latest.min.js
I try to use Greasemonkey/jQuery XHR bridge with out change other code by like this
// #require http://courses.ischool.berkeley.edu/i290-4/f09/resources/gm_jq_xhr.js
and try use openkeyval official javascript library with code like this
// #require http://cdn.openkeyval.org/statics/openkeyval.packed.js
and retrieve data with code like this
var ourCallback = function(value, key) {
console('The value of ' + key ' + is ' + value);
};
window.remoteStorage.getItem('test-key-data', ourCallback);
still got error ERROR: Unexpected string
Please help, I mess with it more than 10 hours. Thank you so much.
It look like $.ajax always trigger error event function
but GM_xmlhttpRequest can retrieve mistype data, so I try looking for dataType: "jsonp" in GM_xmlhttpRequest and I got that jsonp header content-type is "application/javascript" OR "application/json" and the first one work well.
my new code for retrieve data look like this
GM_xmlhttpRequest({
method: "GET",
url: "http://api.openkeyval.org/test-key-data?nocache=" + new Date(),
headers: {
"Content-Type": "application/javascript"
},
onload: function(response) {
console.log(response.responseText);
}
});
and retrieve data using $.ajax even it always trigger error event function but it still send data.
I try both content-type on GM_xmlhttpRequest and still not work.
my code to store data look like this
$.ajax({ /* send data */
url: "http://api.openkeyval.org/store/",
data: "test-key-data=" + JSON.stringify(myVarObject),
dataType: "jsonp"
});
Add this into $.ajax({...})
crossDomain: true;
It is because by default cross domain ability is disabled. See http://api.jquery.com/jQuery.ajax/
EDIT:
Sometimes there will be a issue with different charset between local script and remote script. Try using:
scriptCharset: "utf-8";
Also look at JQuery AJAX is not sending UTF-8 to my server, only in IE
Elaborating my comment
The reference is to the callback function generated by jquery.
It Sounds to me the way you invoke your userscript unloads the jquery functions before the callback is executed.
Perhaps you use a link and forgot the preventDefault?
If you ajax and have
$("#linkid").on("click"
or
$("#formid").on("submit"
it is MANDATORY to continue like this:
,function(e) {
e.preventDefault();
Otherwise the link is followed or the form is submitted which may not have any visible effect, but the asynchronous scripts have been (partially) unloaded unless the form and link has a target other than the current window

Resources