how to call ajax method recursively - ajax

I have a problem in my ajax call.
In the below code, pageReload() function is automatically called when the page gets loaded which in-turn calls the ajaxCall() function for every 10 seconds.
I'm calling a method in grails controller through ajax by passing the parameters needed in the url. The controller method returns an array that contains 3 elements which are the Name of the book, the Author of the book and the year published.
<htmL>
<head>
<script type="text/javascript">
function pageReload() {
var timeInterval = setInterval('ajaxCall()',10000);
}
function ajaxCall() {
jQuery.ajax({
url: '/getBook?rowName=${row}&columnName=${column}',
success: function(data){
bookReturned(data);
},
error: function() {
alert('Error occured in AJAX call');
}
});
}
function bookReturned(values){
alert("Values are : "+values);
}
window.onload=pageReload;
</script>
<head>
</html>
For every 10 seconds I'm getting the alert for Values which are returned from the controller method. But the controller method is getting executed only for the first call by ajax (I have given println in controller method which gets displayed in console only one time).
How to make the ajax call to execute the controller method every time when it is called.
Please help me in this as I'm new to Grails and ajax.
Thanks in advance.

Your requests are being cached. Set the cache option to false.
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
See jQuery documentation on cache here
jQuery.ajax({
cache: false,
url: '/getBook?rowName=${row}&columnName=${column}',
success: function(data){
bookReturned(data);
},
error: function() {
alert('Error occured in AJAX call');
}
});

Related

browser performance after some ajax calls

I use jquery to make an ajax request every 15 seconds to update a <DIV> Element with information. That works generally fine but after some minutes, when the ajax request runs a few times, I got browser performance issues. I only need to run the page in firefox, but here is the problem most of all.
This is the way I call the function every 15 sec.:
setInterval(syncdiv, 15000);
This is my ajax request:
function syncdiv() {
$.ajax({
url: 'code_get_msg_sync.php?',
cache: false, // The problem exist with cache true even with false
success: function(data) {
$('#msgdiv').html(data);
}
});
}
Try using
e.preventDefault();
before you submit or click to send a ajax request ..Just a try
Also there are few links for reference
Link 1
Link 2
Link 3

How to perform ajax call to doaction in ofbiz

I would like to use Ajax to perform an action in OFBiz without the page refreshing. The task will be like filters. When I choose any Checkbox it should perform some action and display the result in the very same page.
What are all the steps i need to do?
I would appreciate some sample code for controller.xml,javascript calling Ajax ..etc
Thanks.
You can use form submission through ajax on an event in your ftl's. Here's a sample code for ajax call from say an ExampleCreateParty.ftl:
$.ajax({
url: '<#ofbizUrl>addSecurityPermissionToSecurityGroup</#ofbizUrl>',
type: 'POST',
accepts: 'xml',
data: $("form#Permissions").serialize(),
success: function(e) { console.log(e);
var xmlDoc;
try {
xmlDoc = $.parseXML(e);
var error = $(xmlDoc).find("Message").find("Error").find("ErrorCode").text();
var errorMsg = $(xmlDoc).find("Message").find("Error").find("ErrorMessage").text();
if (error=='0'){alert(errorMsg);}
console.log(xmlDoc);
} catch (err) {
alert('Saved Successfully!');
}
},
error: function(e) { console.log(e); }
})
Here in response to the service called i.e. addSecurityPermissionToSecurityGroup you can specify the response in the controller.xml which you can get within the success key in the ajax call itself.
To see a full end-to-end example have a look at this OFBiz page
As you can see whenever you change the product configuration, the product price is updated with Ajax call. Then you can find out for yourself the freemarker file containing javascript and the controller doing calculations and returning it back.

jQuery Ajax request failed for get request to other domain

I want to send a request to other domain like
http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX
I have used Ajax request as below:
$.ajax({
type: "GET",
url:'http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX',
success:function(data){
alert(data);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
but it does not go to success function and the alert erro is:
XMLHttpRequest=
textStatus=error
errorThrown=
if I write same url address bar it display message not in Ajax request.
Is this the correct way to send request or is there another way or something I am missing?
You can not perform a cross domain ajax call.
Work around for this
Method 1
JavaScript
Create a function
function getMyData(data) {
alert(data);
//Do the magic with your data
}
Server side
On server end wrap your data inside function syntax
getMyData("Enter your data here");
JavaScript
Then create a script tag and add a link to your cross-domain page
<script type="text/javascript"
src="cross ref url">
</script>
For reference: wikipedia
Method 2
Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

How can I manipulate an Ajax response before it's injected into the DOM?

Here is what I have so far:
$(function () {
dataValModify('body');
$('body').bind('ajaxSuccess', function (e, xhr, settings) {
dataValModify(xhr.responseText);
});
});
function dataValModify(elem) {
// Code to modify elements within the response.
}
How can I take the Ajax response and modify it before it is injected into the DOM? Previously, I was binding ajaxComplete and modifying the DOM directly after injection, but I would like to modify the response instead. I don't think it makes a lot of sense to find elements in the Ajax response and use them to modify the DOM. I send the xhr.responseText into my function so that I don't reapply the modifications to the rest of the body, which will have already been modified by the time of an Ajax call. Also, is there something better than xhr.responseText to use for this? I couldn't get xhr.responseHTML to work.
EDIT: Right now I'm just using a simple test Ajax call to return an MVC partial view:
$('#ajaxTest').load('<MVC Route>')
If I'm understanding your requirements correctly, they are as follows:
Make an asynchronous HTTP request to get some HTML
Modify the returned HTML using the dataValModify() function
Insert the modified HTML into your element with the ID: 'ajaxTest'
If so then it sounds to me like you need to make a lower level ajax call than what you're using at present i.e. $(elem).load()
Essentially the call to .load() is a wrapper for $.get() followed by a call to $(elem).html(someContent) where "someContent" is the responseText from the HTTP request.
Therefore if you want to modify the response before it's injected into the DOM, then you can do something similar to the following:
$.ajax({
type: "GET",
url: "<MVC Route>",
dataType: "html",
success: function(jqXHR, textStatus, errorThrown){
// Your HTTP call was successful but nothing else has happened with the response yet
// Therefore you can now do whatever you want with the it...
// First modify the HTML using the dataValModify function
// Assumption being that your function returns the modified HTML string
var myModifiedHTML = dataValModify(jqXHR.responseText);
// Inject the modified HTML
$('#ajaxTest').html(myModifiedHTML);
}
});
You can use ajaxComplete to modify the responseHTML itself.
$('body').ajaxComplete(function(e, xhr, settings) {
dataValModify(xhr.responseHTML);
});
Update: I haven't tried it, but it might help:
$.ajaxSetup({
converters: {
"text html": function( textValue ) {
if ( valid( textValue ) ) {
// Some parsing logic here
return dataValModify(textValue );
} else {
// This will notify a parsererror for current request
throw exceptionObject;
}
}
}
});
More info here: http://api.jquery.com/extending-ajax/

Resources