How I write java code from javascript that will complete in server. Please help me.
I have long been trying to remake it
It is query to server to will be logged.
this.login = function(options) {
//It is query to server to will be logged.
if (typeof (options.success) == "function" && typeof (options.error) == "function" && options.params != null) {
var successCallback = options.success;
var errorCallback = options.error;
} else {
AV.console.error(LP + 'Invalid number of arguments (min req = 3), Please read API Documentation.');
return;
}
$.ajax({
type: 'POST',
url: _sURL + '/csportal/v1/login',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(options.params),
success: function(response) {
AV.console.debug(LP + "login::Success: " + JSON.stringify(response));
if (response && response.success == true) {
_userLoggedIn = 'true';
_userReturned = 'false';
_userInfo = response.data;
successCallback({"message": response.message,"data": response.data});
} else {
_userLoggedIn = 'false';
errorCallback({message: response.message});
}
},
error: function(e) {
AV.console.warn(LP + "login:: error: " + e.message);
errorCallback({message: e.responseText});
}
});
};
You have two options here.
Option 1 - Corresponding to your _sURL + '/csportal/v1/login, you need to create a class extending HttpServlet class, override the post method and return required response. Or if you are using any frameworks (like Spring MVC or Struts), you just need to override corresponding Action classes.
Option 2 - Corresponding to your _sURL + '/csportal/v1/login, you create a REST api (using Jersey), and write a POST method handling JSON request and return required RESPONSE.
If you don't have server side experience, consider catching a server side engineer from your team for help.
Related
I have the following Jquery code, I'm trying to display information in $('.cbs-List').HTML(divHTML); based on the region value. But in the success function, I can't read the value for the region, it states that
'data is undefined'
What is the correct form of passing parameters or values to the success function in this case?
$(document).ready(function() {
getSearchResultsREST('LA');
});
function getSearchResultsREST(region) {
var querySA = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA';
var queryDR = 'ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM';
if(region == 'LA') {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + querySA + "'";
} else {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText='" + queryDR + "'";
}
$.ajax({
url: searchURL,
method: "GET",
headers: {
"Accept": "application/json; odata=verbose"
},
contentType: "application/json; odata=verbose",
success: SearchResultsOnSuccess(data, region),
error: function(error) {
$('#related-content-results').html(JSON.stringify(error));
}
});
}
function SearchResultsOnSuccess(data, region) {
var results;
var divHTML = '';
if (data.d) {
results = data.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results;
if(results.length == 0) {
$('#related-content-results').html('There is No data for the requested query on ' + _spPageContextInfo.webAbsoluteUrl);
} else {
for (i=0; i<results.length; i++) {
var item = results[i];
var itemCell = item.Cells;
var itemResults = itemCell.results;
// Get values for item result
var _title = getValueByKey("Title", itemResults);
var _path = getValueByKey("Path", itemResults);
divHTML += '<li><a href=' + _path + '>' + _title + '</li>';
}
// Display information based on region.
$('.cbs-List').html(divHTML);
}
}
}
You have 2 problems, and they're both easy to fix.
There's no need to pass region into SearchResultsOnSuccess at all. you can already use it in there because it's defined at a higher scope.
In the object you're passing to $.ajax, you're not setting SearchResultsOnSuccess as a callback, you're calling it.
Change the lines:
success: SearchResultsOnSuccess(data, region) => success: SearchResultsOnSuccess
function SearchResultsOnSuccess(data, region) { => function SearchResultsOnSuccess(data) {
and it should work fine.
Edit:
Here's a basic example of how you need to set this up
function search(region) {
$.ajax({
url: 'example.com',
method: 'GET',
success: successCallback,
});
function successCallback(data) {
console.log(data, region);
}
}
search('LA');
You have to urlencode the value if it contains = or & or whitespace, or non-ASCII characters.
var querySA = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=LA');
var queryDR = encodeURIComponent('ClientSiteType:ClientPortal* contentclass:STS_Site Region=EM');
if(region == 'LA') {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + querySA;
} else {
var searchURL = _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?queryText=" + queryDR;
}
And normally you don't have to put your values between apostrophes.
I updated the answer, I hope you will understand me better.
Your problem is NOT the parameter passing IMHO but your server response.
You should either:
turn on the developer tools and check the XHR requests on the network tab, look for the /_api/search/query... requests and examine the response
double check the server side logs/study your search service API documentation how to assemble a proper call
use your favourite REST client and play around your service: send there queries and check the responses and check that it matches with your expectation
last but not least, you can replace your ajax caller with this quick-and-great one:
$.ajax({
url: searchURL,
success: function (response) {
$('#post').html(response.responseText);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
$('#post').html(msg);
},
});
(of course you should have a <div id="post"><div> somewhere in your page)
Your success function IMHO would get your region if gets called, but it does not, and I hope using one or more of these techniques will help you to see clear.
If you are really sure that you get what you want, you can go furher with passing your second argument, as described here
When I check console in Chrome, the Sharepoint page behaves as it is supposed to when data is Object {d: Object} and d is an Array of the items of want.
When data is #document, the page does not load as I append html based on data.
I understand #document appears because of jQuery's Intelligent Guess, but am not sure why it is getting returned.
function getItems() {
var url = hostWebURL + "_api/web/lists('" + guid + "')/items/";
var items;
$.ajax({
url: url,
type: "GET",
headers: { "Accept": "application/json;odata=verbose "}, // return data format
success: function (data) {
//items is iterable ListItemCollection
console.log(data);
items = data.d.results;
...
},
error: function (error) {
var errorMsg = "";
if (error.status == "403" || error.status == "401") {
errorMsg = "You do not have Authorization to see Site Permissions - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
else {
var errorMsg = "Failed - ErrorCode(" + error.status + ") Error Details: " + error.statusText;
}
reportError(errorMsg);
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json; odata=verbose");
Added this parameter to the call and it's working!
Taken from: http://ratsubsharewall.blogspot.com/2017/02/rest-call-returns-xml-instead-of-json.html
I have been fumbling with AngularJS for weeks now and trying to cobble together the parts of this, that, and the other thing together to create a file serving web application with a Django backend. I thought things were going well until I found myself trying to upload a file with all of my other form data. My HTML form consistently showed up as having no file attached during the validation step before sending the request. Well, that's no good! Anyways, this ended up being some manner of unsupported operation, for one reason or another. I turned to ng-file-upload, a third party file upload service for AngularJS. The most current iteration of ng-file-upload uses AngularJS 1.6 style requests and my third party registration application angular-django-registration-auth uses $http previous to 1.6.
I need to update the third party registration application but it has the following code.
'request': function(args) {
// Let's retrieve the token from the cookie, if available
if($cookies.token){
$http.defaults.headers.common.Authorization = 'Token ' + $cookies.token;
}
// Continue
params = args.params || {}
args = args || {};
var deferred = $q.defer(),
url = this.API_URL + args.url,
method = args.method || "GET",
params = params,
data = args.data || {};
// Fire the request, as configured.
$http({
url: url,
withCredentials: this.use_session,
method: method.toUpperCase(),
headers: {'X-CSRFToken': $cookies['csrftoken']},
params: params,
data: data
})
.success(angular.bind(this,function(data, status, headers, config) {
deferred.resolve(data, status);
}))
.error(angular.bind(this,function(data, status, headers, config) {
console.log("error syncing with: " + url);
// Set request status
if(data){
data.status = status;
}
if(status == 0){
if(data == ""){
data = {};
data['status'] = 0;
data['non_field_errors'] = ["Could not connect. Please try again."];
}
// or if the data is null, then there was a timeout.
if(data == null){
// Inject a non field error alerting the user
// that there's been a timeout error.
data = {};
data['status'] = 0;
data['non_field_errors'] = ["Server timed out. Please try again."];
}
}
deferred.reject(data, status, headers, config);
}));
return deferred.promise;
},
Beginning at var deferred = (this is defining a promise object, right?) I am unclear on what is going on. The assignments are easy to understand for the most part, with exception granted to the promise object (How does data = args.data || {}; end up in the right-handside of one of $http provider's compound assignment?), but what exactly is happening in the success and error cases where angular.bind() is called? I can't seem to find any good examples where angular seems to bind to a promise.
Fixed this with then() calls after finding some decent resources. Here is what my code ended up looking like, I'm including my logging because it may help someone else.
"request": function(args) {
// Let"s retrieve the token from the cookie, if available
if($cookies.get("token")){
$http.defaults.headers.common.Authorization = "Token " + $cookies.get("token");
}
// Continue
params = args.params || {};
args = args || {};
var deferred = $q.defer(),
url = this.API_URL + args.url,
method = args.method || "GET",
params = params,
data = args.data || {};
// Fire the request, as configured.
$http({
url: url,
withCredentials: this.use_session,
method: method.toUpperCase(),
headers: {"X-CSRFToken": $cookies["csrftoken"]},
params: params,
data: data
})
.then(function(response) {
console.log("Success case: " + url);
console.log("Headers: " + JSON.stringify(response.headers(),null, 4));
console.log("Config: " + response.config);
console.log("Status: " + response.status);
console.log('Response: ');
console.log('JSON: ' + JSON.stringify(response.data, null, 4));
deferred.resolve(response.data, response.status);
}, function(response) {
console.log("Error case: " + url);
console.log("Headers: " + JSON.stringify(response.headers(),null, 4));
console.log("Config: " + response.config);
console.log("Status: " + response.status);
console.log('Response: ');
console.log('JSON:' + JSON.stringify(response.data, null, 4));
if(response.data){ response.data.status = status; }
if(status == 0){
if(response.data == ""){
response.data = {};
response.data["status"] = 0;
response.data["non_field_errors"] = ["Could not connect. Please try again."];
}
if(data == null){
response.data = {};
response.data["status"] = 0;
response.data["non_field_errors"] = ["Server timed out. Please try again."];
}
}
deferred.reject(response.data, response.status, response.headers, response.config);
});
return deferred.promise;
},
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.
My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.
Here an example (just a sample code):
var tasks = pdBrowser.EvaluateScriptAsync(#"
(function(){
$.ajax({
type: ""POST"",
dataType: ""json"",
cache: false,
url: ""_resources/php/ajaxRequests.php"",
async: false,
data: {
action: ""insertCrossPlatform"",
type: """",
values: JSON.stringify(""foo bar"")
},
success: function(response) {
if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
{
return response;
}
else
{
//pageReload();
return ""OK"";
}
},
error: function(xhr, textStatus, errorThrown) {
return errorThrown + ""\n"" + xhr.responseText;
},
complete: function() {
return ""COMPLETE"";
}
});
})();", null);
tasks.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success)
{
if (response.Result != null)
{
MessageBox.Show(response.Result.ToString());
}
}
else
{
MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}, TaskScheduler.Default);
Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?
Thanks in advance.
Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.
Most people choose to bind an object, and call a method on their bound object when they wish to communicate with the parent application. See the FAQ for an example. https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript
With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's complex and not well documented, so if your not comfortable digging through reference C++ code then this option isn't for you. Here's a reference https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.
When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.
var myDivElement =document.getElementById('textareaInfo');
if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"
var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
Then later with ajax
var root = 'https://jsonplaceholder.typicode.com';
var _holder = callbackObj;
callbackObj.showMessage(""ajax"");
$.ajax({
url: root + '/posts/1',
contentType: 'application/json; charset=utf-8',
method: 'GET',
complete: function(data){
},
success: function(response) {
$(#'textareaInfo').value(response);
}
}).then(function(data) {
callbackObj.showMessage(data);
});
Then read the texarea from cefsharp in c#
chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result
You can use PostMessage javascript method to notify .NET application:
CefSharp.PostMessage('Your data Here');
Here is .NET code example for headless browser:
var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
{
if ((string)e.Message.notificationid == "notification1")
{
// Your processing code goes here
}
};
browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");
I have been looking into a jQuery Ajax queue system. I have a step by step generator. It generates a pdf and then once the pdf is generated an image is created. Once these 2 processes are complete I then send an email confirmation. It must also be flexible to add additional steps.
However, I have yet to find an example that works. They all use 'COMPLETE' rather than 'success' so if I return an error via jSON then it is ignored. It moves on to the next in the queue
Any ideas?
EDIT
It's quite complex whats happening.
My plugin (copied from another plugin)
$.AjaxQueue = function() {
this.reqs = [];
this.requesting = false;
};
$.AjaxQueue.prototype = {
add: function(req) {
this.reqs.push(req);
this.next();
},
next: function() {
if (this.reqs.length == 0)
return;
if (this.requesting == true)
return;
var req = this.reqs.splice(0, 1)[0];
var complete = req.complete;
var self = this;
if (req._run)
req._run(req);
req.complete = function() {
if (complete)
complete.apply(this, arguments);
self.requesting = false;
self.next();
}
this.requesting = true;
$.ajax(req);
}
};
I have also written a function to speed my code up
function createQueue(file, inputid, step, params) {
var queue = new $.AjaxQueue();
queue.add({
url: file,
type: 'POST',
dataType: "json",
data: params,
complete : function(data, status) {
$('li#step' + step + ' .loading').remove();
// DO SOMETHING. CANT CHECK FOR ERRORS
},
success : function(data, status) {
// DOES NOT WORK
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
},
_run: function(req) {
//special pre-processor to alter the request just before it is finally executed in the queue
//req.url = 'changed_url'
$('li#step' + step).append('<span class="loading"></span>');
}
});
}
Step 1. I am using mpdf to generate a pdf. Now this takes a few seconds to actually build depending on theme, images used etc. So i call this:
createQueue('post_pdf.php', id, 1, { 'filename': filename + '.pdf', 'id': id, 'crop': crop } );
Step 2 - Generate some images
createQueue('ajax_image.php', id, 2, { 'filename': filename + '.pdf' } );
Step 3 - (something else like send email summary)
createQueue('mail.php', id, 3, { 'from': 'newfilename', 'to': 'emavle#pb.com', 'subject': 'This is a subject', 'body': 'Body Copy' } );
If it fails at step 1 I can see it in console but its not returned
As #charlietfl suggested, have each step in PHP on server side. After the AJAX call is done, you can have the response from the server and continue based on that. Example:
// make AJAX request to file.php and send 'data'
var request = $.ajax({
url: "file.php",
type: "POST",
data: { data }
});
// when PHP is done, receive the output and act accordingly
request.done(function( msg ) {
if (msg == "A") {
// plan A
} else if (msg == "B") {
// plan B
}
});