Android parse JavaScript function from web - javascript

My coworker created a website with statistics that now I need to implement on a mobile app.
He used JavaScript and now I'm developing on Android.
I want to show one specific function from the JavaScript according to the Activity on Android.
I've been searching but it is not showing anything. Any ideas? Probably I'm missing something really logical, but I can't figure out.
Code from the web:
function GetUsersLastEventID(userID, labelID) {
var message = { UserID: userID };
$.ajax({
url: "GetData.aspx/GetUsersLastEventID",
type: "POST",
async: true,
data: JSON.stringify(message),
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#label' + labelID).text("UserID: " + userID + " was last seen in event : " + msg.d);
},
failure: function (response) {
$('#label' + labelID).text(eventTitle + ": INFORMATION UNAVAILABLE!");
console.log("Error in: GetUsersLastEventID(), params: " + userID);
}
});
}
Code from the call on Android:
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("javascript:GetUsersLastEventID(userID, labelID);");

may be you should pass userID and labelID as variable if every thing is okay with webservice call in javascript
webView.loadUrl("javascript:getUsersLastEventID("+userID+","+labelID+")");

Related

jQuery's Ajaxnot calling success() neither error()

The user of my Cordova/PhoneGap app has to sign in, so I group all the form's data into a Javascript array, then I JSON.strigify() it and I send it to the server via an Ajax request.
The PHP script has been tested by manually sending the CGI command, it does perfectly works.
Also, I used alert() to check if the function sendDataToServer() is called, it is.
The problem is that Ajax doesn't output success() neither error(). AND there is no difference (exept the command, obviously) with an other working script that I use for checking a login.
Note: I use GET for testing purposes, at the end it will be POST.
Here is the WORKING script:
$("#connectionFormSubmit").click(function () {
$.ajax({
type: "POST",
url: "http://" + host + "/my_app/check_login.php",
data: "login=" + $("#login-conn").val() + "&password=" + $("#password-conn").val(),
success: function (msg) {
navigator.notification.alert(msg, alertDismissed, 'Result', 'OK');
},
error: function (jqXHR, exception) {
navigator.notification.alert(getError(jqXHR, exception), alertDismissed, 'Error', 'OK');
}
});
});
Here is the NOT WORKING script:
function sendDataToServer(dataGuest, dataChild1, dataChild2, dataChild3) {
$.ajax({
type: "GET",
url: "http://" + host + "/my_app/insert_new_user.php",
data: "guest=" + dataGuest + "&child1=" + dataChild1 + "&child2=" + dataChild2 + "&child3=" + dataChild3,
/* async: false, not changing anything */
success: function (msg) {
navigator.notification.alert(msg, alertDismissed, 'Result', 'OK');
},
error: function (jqXHR, exception) {
navigator.notification.alert(getError(jqXHR, exception), alertDismissed, 'Error', 'OK');
}
});
}
(in both cases the server script works perfectly fine).
This is how I call the function:
sendDataToServer( JSON.stringify(dataGuest), JSON.stringify(dataChild1), JSON.stringify(dataChild2), JSON.stringify(dataChild3) );
I didn't find anything simiar to my problem on Google.

External Sharing of Folders in SharePoint Online using REST API

I am new to SharePoint Online and REST API.
I am currently working on a SharePoint Add-In which creates folders in a document library residing in the Host Web and share the permission to specified external users. I am currently attempting to do everything using REST API.
I am successfully able to create the folders but I am currently unable to share the folders to external users.
I am having trouble resolving the following endpoints when attempting to use the host web context. The first endpoint below is for resolving the external email, and the second one is for performing the actual sharing of the folder to the external user.
[appUrl]/_api/SP.AppContextSite(#target)/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser?#target='[hostUrl]'
[appUrl]/_api/SP.AppContextSite(#target)/SP.Web.ShareObject?#target='[hostUrl]'
I am getting the error 404 Not Found: Cannot find resource for the request SP.UI.ApplicationPages.ClientPeoplerPickerWebServiceInterface.clientPeoplePickerResoveUser. The same error occurs for SP.Web.ShareObject when I try to force it to run.
Below is the javascript that I am using
var ShareToRecipients = function(folder, recipient, appUrl, hostUrl){
var url = appUrl = "/_api/SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerResolveUser";
url = WebComponents().getTargetUrl(url, hostUrl);
var sharedDocUrl = hostUrl + "/ExternalShareDocLib/" + foldername;
var checkUser = $.ajax({
url: url,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
'queryParams': {
"__metadata": {'type': "SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters"},
"AllowEmailAddresses": true,
"AllowMultipleEntities": false,
"AllUrlZones": false,
"MaximumEntitySuggestions": 50,
"PrincipalSource": 15,
"PrincipalType": 1,
"QueryString": recipient
}
}),
headers:{
"accept": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
error: function(jqXHR, textStatus){
myapp.LogAPIError(jqXHR, textStatus)
}
});
checkUser.success(function(data){
var user = data.d.ClientPeoplePickerResolveUser;
var result = JSON.parse(users);
if(users !== undefined){
var reqUrl = appUrl + "/_api/SP.Web.ShareObject";
reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl);
var shareCall = $.ajax({
url: reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": reqUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify({
"url": sharedDocUrl,
"peoplePickerInput": '[' + user + ']',
"roleValue": "1073741827",
"groupId": 0,
"propagateAcl": false,
"sendEmail": true,
"includeAnonymousLinkInEmail": true,
"emailSubject": "A document folder has been shared to you",
"emailBody": "A document folder has been shared to you. The folder name is " + folder
})
});
});
shareCall.success(function(data){
myApp.LogInformation("Successfully shared " + folder + " to " + recipient);
});
shareCall.error(function(jqXHR, textStatus){
myApp.LogAPIError(jqXHR, textStatus);
});
}
});}
For generating the Host URL Endpoint
var WebComponents = function(){
var getTargeturl = function (url, hostUrl){
if(hostUrl){
var api = "_api/";
var index = url.indexOf(api);
url = url.slice(0, index + api.length)+
"SP.AppContextSite(#target)" +
url.slice(index + api.length);
var connector = "?";
if(url.indexOf("?") > -1 && url.indexOf("$") > -1){
connector = "&";
}
url = url + connector + "#target='" + hostUrl + "'";
}
return url;
}
return{
getTargeturl: getTargeturl
}}
Can you help verify if I am using the endpoints correctly and if what I am trying to do is even possible?
Appreciate the help.
Cheers,
Neil
Adding my resolution just in case anyone else encounters this issue.
I was able to use the API by:
Removing url = WebComponents().getTargetUrl(url, hostUrl)
and reqUrl = WebComponents().getTargetUrl(reqUrl, hostUrl).
Giving the App Full Control in the Tenant via the AppManifest.xml

Failed to load resource: the server responded with a status of 500 using Ajax

I know this question has been asked previously, but I cannot find out what is the exact problem with my code.
function viewcalldetails(obj) {
alert("clicked");
var id = $(obj).attr("id");
$(".style-table-tab input[type='text']").val('');
setTimeout(function () {
$('.preloader-circle').show();// or fade, css display however you'd like.
}, 1000);
$.ajax({
type: 'POST',
url: pageUrl+"/LoadCallDetails",
data: '{LeadID: "' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: OnValuecall,
failure: function (response) {
alert(response.d);
}
});
}
function OnValuecall(response) {
$(".preloader-circle").hide();
$("#ctl00_ContentPlaceHolder1_lbrfullname").text(response.d.FirstName);
$("#ctl00_ContentPlaceHolder1_lbrphonenumber").text(response.d.MobileNo);
$("#ctl00_ContentPlaceHolder1_lbraddress").text(response.d.Address1);
$("#ctl00_ContentPlaceHolder1_lbrorganization").text(response.d.OrganizationName);
$("#ctl00_ContentPlaceHolder1_lblremail").text(response.d.PrimaryEmail);
}
Web Method:
public static UserAjax3 LoadCallDetails(string LeadID)
{
//System.Threading.Thread.Sleep(3000);
UserAjax3 oUserAjax = new UserAjax3();
//BD_CommonEmail[] ocall = BD_CommonEmail.GetEmailAll(Convert.ToInt32(LeadID)).ToArray();
BD_Leads[] ocall = BD_Leads.getCallDetails(Convert.ToInt32(LeadID)).ToArray();
if (ocall.Length == 1)
{
// oUserAjax.LeadID = oLeads.LeadID.ToString();
oUserAjax.LeadID = ocall[0].LeadID.ToString();
oUserAjax.FirstName = ocall[0].FirstName;
oUserAjax.MobileNo = ocall[0].MobileNo;
oUserAjax.OrganizationName = ocall[0].OrganizationName;
oUserAjax.Address1 = ocall[0].Address1;
oUserAjax.PrimaryEmail = ocall[0].PrimaryEmail;
}
return oUserAjax;
There are many things in question:
Where does "pageUrl" comes from?
You're awaiting a JSON result, but your method seems to return a normal object. Where do you convert to JSON?
Did you try running with a debugger in single-step mode trhough your web method?
Why is your web method static?

Saving the Popup data using Javascript

I am having a drop down with "Create New" option. If User clicks "Create New" option then Popup window will display with Save button. In that Popup window, User will enter data and after User will save this data on server. To achieve this what approach I should follow. Any Help Please..??
use for example from javascript:
$(function () {
$("#btnSave").click(function () {
var person = { Name: 'MrX', Age: 25 };
$.ajax({
type: "POST",
url: "/AddUser",
data: car,
datatype: "html",
success: function (data) {
/*
done
*/
}
});
});
});
and then into your controller:
[HttpPost]
public JsonResult AddUser(string data)
{
/* deserilize and insert */
or if you are using web forms you need to decorate your method like:
[WebMethod]
public static void AddUser(string data)
{
/* deserialize, add */
Note: out there are so many options you can do this. it depends in what conditions you are or what you like
JavaScript function to call C# Web Method from Ajax.
<script>
function savefile()
{
var person = 'test',
returnEmail = 'test#test.com';
var dataValue = { "name": person, "returnAddress": returnEmail };
var url = "WebForm1.aspx/OnSubmit";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(dataValue),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
if (msg.d != null) {
alert("We returned: " + msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
};
</script>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="savefile()" />
Web Method to receive Ajax Request and Process it.
using System.Web.Services;
[WebMethod]
public static string OnSubmit(string name, string returnAddress)
{
return "it worked";
//Code for writing your data to text file.
}

Javascript 'Namespaces' and jQuery AJAX

I'm using the recommendations laid down here (http://www.odetocode.com/articles/473.aspx) to write a JavaScript AJAX webchat system using simulated Namespacing and prototyping.
In one of my prototype methods I'm calling the $.ajax method in jQuery. What I then want to do is pass the returned JSON data into a method inside my JavaScript webchat namespace.
The problem seems to be because I've created an instance of my JavaScript webchat, I can't directly call a method inside it because I need to address it through the instance.
The key part in the code below is
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
I'm thinking because we're inside the $.ajax() method, that this no longer refers to our WebchatV3 object.
The full JavaScript code is shown below:
/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />
// Simulated 'namespace'
var AvonAndSomerset = {}
// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
this.Members = new Array(); // Members in the chatroom
this.Questions = new Array(); // The questions queue in the chatroom
// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);
// Set-up AJAX defaults
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
AvonAndSomerset.WebchatV3.prototype = {
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
$.ajax({
url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
// Callback - on success of GetUpdate()
GetUpdate_Success: function(data) {
alert('The AJAX call was successful!');
},
// Does the MemberID exist in the local array?
Members_DoesExist: function(MemberID) {
alert('Searching for ' + MemberID);
alert(this.Members.length);
}
The easiest way to fix this is to create a variable that references this at the proper scope required. this and scope work differently in javascript then most languages, in this case it is referring to the object being passed into the function.
// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
//here
var self = this;
$.ajax({ url: "JSON.aspx/Members_GetChanges",
data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
success: function(data, textStatus) {
self.GetUpdate_Success(data)
},
error: function(result) {
alert('Members_GetChanges() failed: ' + result.responseText);
}
});
},
Try
success: function(data, textStatus) {
AvonAndSomerset.WebchatV3.GetUpdate_Success(data)
},
That may work.

Categories