AJAX call without Java application context - javascript

I have a (Spring-powered) Java application that has a some AJAX calls. The problem is that I'm using the application context (/spring-mvc) to be able to reach the server-side functionality.
var api = '/api/v1';
var context = '/spring-mvc' + api;
$.ajax({
type: 'GET',
url: context + '/users/' + $('#user-id').val()
}).done(function (response) {
callback({ data: response.user, binding: response.binding });
}).fail(function (jqXHR, textStatus, errorThrown) {
callback({ jqXHR: jqXHR });
});
Now, my problem is whenever I have to deploy it somewhere else, and I can't control the application context, the AJAX calls are eventually failing since the application context itself is hard-coded in the JavaScript.
Is there any way to achieve this without having to change the context variable in all JavaScript files? Something like:
$.ajax({
type: 'GET',
url: '/api/v1/users/' + $('#user-id').val()
}).done(function (response) {
callback({ data: response.user, binding: response.binding });
}).fail(function (jqXHR, textStatus, errorThrown) {
callback({ jqXHR: jqXHR });
});
I've seen that several times in many applications, but I can't figure it out how they do that.
Note: The Web application is deployed in the same WAR file; I would like to avoid to try to figure it out by doing URL manipulation in JavaScript.

Deadly simple, you may include the context with a hidden input, such as
<input type="hidden" id="ctx" name="ctx" value="<applciation_context_here>"/>
then in your js
var context = document.getElementById("ctx").value/*getAttribute('value')*/ + api;
or better way acquire the current windows location(path), and some string manipulation to get the context
update0:
FACTS:
Let say you will have /a , /b and /c contexts, I don't know but usually they will be mapped to a.com , b.com and c.com and context will be identified by the server as requested host, such as following
a.com -> local_host/a
b.com -> local_host/b
But if you are not going as above, as you are generating the jsp file, you may set the context path as hidden input approach

Related

Asp.Net Service method Is Not Executing or Calling Inner Method or Statement on BeforeUnload event

I have beforeunload event in js which will hit the .asmx service method as provided below.
.js event
$(window).on("beforeunload", function () {
var d, str;
str = '{Id:"' + $('#hdnId').val() + '"}';
d = str;
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "../POC.asmx/fUpdateTimeInterval",
data: d,
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
async: true,
beforeSend: function () {
// BlockUI();
},
success: function (data, Type, xhr) {//On Successfull service call
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
complete: function () {
},
failure: function () {
}
});
});
.asmx (Web Service)
[WebMethod(true)]
public int fUpdateTimeInterval(String Id)
{
return new MY_POC.DLL.Survey().fUpdateTimeInterval(Id);
}
The above service will then call the below mentioned method defined in DLL class file.
public int fUpdateTimeInterval(Int32 Id)
{
List<SqlParameter> objParam = new List<SqlParameter>()
{
new SqlParameter{ParameterName ="#Id",Direction=ParameterDirection.Input,DbType=DbType.Int32,Value= Id},
};
MY_POC.DLL.SqlHelper.ExecuteNonQuery("MY_UpdateTimeInterval", System.Data.CommandType.StoredProcedure, objParam.ToArray());
return 0;
}
Now problem is when the page gets load on browser for first time I am getting current auto ID of the inserted row. If I refreshes the browser, then beforeunload event gets fired and update the row of received ID only. But if I close the tab or browser then the compiler would hit the service method and stops after opening brace, it does not executing further & not even showing any error.
After execution stops, I am getting the following message at Output screen of vs, but not showing any error.
It sounds like execution of the request is being aborted because the browser is closing the connection.
You should consider using the Beacon API. It's well supported by almost all browsers and it's made for this purpose. From Mozilla's documentation:
The main use case for the Beacon API is to send analytics such as
client-side events or session data to the server. Historically,
websites have used XMLHttpRequest for this, but browsers do not
guarantee to send these asynchronous requests in some circumstances
(for example, if the page is about to be unloaded). To combat this,
websites have resorted to various techniques, such as making the
request synchronous, that have a bad effect on responsiveness. Because
beacon requests are both asynchronous and guaranteed to be sent, they
combine good performance characteristics and reliability.
You can also make your Ajax request synchronous to prevent the connection from closing but that will have an impact on your GUI as it will block until the request completes.

Office Task Pane app ajax call not working

I'm working on this TaskPane app for office, and I would like to get some data from a php function that resides on our domain.
We're using the same php function in other apps, where I can just call it with some parameters passed to it in the URL, and it returns a simple answer.
Example: https://www.ourdomain.com/phpfunction.php?message=HELLO
The problem is, that I cannot seem to call this function via AJAX, from the TaskPane app, while debugging.
I added our domain to the App Domains in the application manifest, but it didn't help
Here is my AJAX call
function httpGET(theUrl, callback) {
var dataToReturn;
$.ajax({
type: 'GET',
url: theUrl,
cache: false,
async: true,
data: "",
success: function(data, textStatus, result) {
callback(data)
},
error: function (result, textStatus, errorThrown) {
//ALLWAYS GOES HERE
}
});
};
I want to do it in pure javascript, so if it's possible, I don't want to use the custom .NET web service fix for this.
PS: I want to specify, that this exact same call is working perfectly from a mobile app or a browser based app. It's Office who's doing something here...

Extend Facebook Access Token javascript

I've already had a look around and i can't seem to find an answer to this, I'm needing my access token to last longer than the 2 hours that it currently does. unless you are able to suggest another method of getting a json result. Thanks
Heres my code
//first define a function
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'https://graph.facebook.com/v2.3/147733805246675?fields=posts&access_token=CAACEdEose0cBALZA1JuPZCO5MW3WZAX2ERa3RJ7PA5QKawTRGH9Yg0tdv4ENVJeZAqFchh9mNJuHu75gKv6QkHj63ezAZBGUm1OnpHWurJM4Aa0J71hFsCr27ZCSz43IuYs7QoBomtHVJCiex6ZBRZAovNybDf5XhfyaPNt5CHhvAhnoSZAXFO8q8c2na1ndztlp1zY2ftvsc9QVZCboEwdLAQnZA4zejYvM7kZD',
success: function(json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.posts.data.length; i++) {
var section = json.posts.data[i].message;
$("#tableid").append("<tr><td style='width:70px'><img id='theImg' src='img/fb.png'/></td><td><b>" + section +
"</b></td></tr>");
}
},
error: function(error) {
console.log(error);
}
});
The Javascript SDK will handle all token-related logic for you. Why do you want to have a long-lived token in the browser?
You should use the Javascript SDK and the features it provides. The only use-case to generate long-lived tokens yourself is if you want to make API calls from your server.
Since extending and token involves sending over your App Secret, you should not do that in the browser; your app secret should only be on your server.

jQuery and Ajax - cannot POST

I am trying to login to a website using a known username and password and to get some data displayed from the site for a specific user account on that website. I am using jQuery and Ajax for this purpose. This is my code:
$.ajax({
async: false,
cache: false,
type: 'POST',
dataType: 'json', // json...just for example sake
data: ({
'login_username': username,
'secretkey': password
}),
url: 'https://mail.someserver.com/src/redirect.php',
success: function (data) {
alert("SUCCESS!")
if (data === '1') { // server returns a "1" for success
// success!
// do whatever you need to do
} else {
// fail!
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// something went wrong with the request
alert("Failed!");
}
});
I've already made my search around the web and I know that browsers do not permit cross server ajax calls to prevent security issues, but I've already tried to use "jsonp" as dataType to no avail :(
So, what am I doing wrong?
Be sure that your url is not breaking the same origin policy -- that is, the request coming from the client cannot request data from a server from a different domain (there are exceptions to this rule, namingly CORS, but that requires that you make changes to the server/application you're talking to).
The solution to your problem would be to make the request from some server-side script, then in turn having your client application query that script, based on the same machine that's serving the application to the web.
My fault isn't at the code above, my fault was that in my manifest file (I am building a Google Chrome extension) I didn't have set proper permissions (https://*).
Sorry for the frustration!

.Next To remove limitation on data send using JSONP

Can we remove the limitation on data send using JSONP. Below is my code. What i am trying to do is to pass 3000 characters(actuallly a image which is converted to base64 data) at a time to service(serviceCall.ashx). As my data is large up to 30,000-40,000 characters i am dividing it in packets(3000 each ) and then sending it. Is there any way i can send this complete data in one go. Reason for switching to JSONP is to avoid the pop up on IE which says 'This page is accessing info that is not.....'. I know as JSONP uses GET method there would obviously a data limitation but is there any way to work around this problem.
$.ajax({
type: "GET",
url: 'http://sys108/restnew1/serviceCall.ashx',
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
async: false,
data: {
datachunk: imgdatachunk,
packetlen: imgdatachunk.length,
imagekey: imageid
},
success: function (data) {},
error: function (jqXHR, textStatus, errorThrown) {
if (window.console)
console.log("Error... " + textStatus + " " + errorThrown);
}
});
No, it's not possible to send a GET request of that length in a more-or-less reliable way: actually, it depends both on how the web server is set up and what client (= browser) is used by someone who works with your application.
So I'd suggest looking for alternative (to JSONP) solutions - like CORS, for example.

Categories