How to Call a Web Service in a Cross-Browser way - javascript

I want to call a Web Service from Mozilla, Internet Explorer and Chrome.
Bellow is my LaboratoryService.js file which calls the Web Service:
function StringBuffer() {
this.__strings__ = new Array;
}
StringBuffer.prototype.append = function (str) {
this.__strings__.push(str);
};
StringBuffer.prototype.toString = function () {
return this.__strings__.join("");
};
function LaboratoryService() {
this.url = "http://25.48.190.93:8082/labratory?wsdl";
}
LaboratoryService.prototype.buildRequest = function () {
var oBuffer = new StringBuffer();
oBuffer.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ");
oBuffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
oBuffer.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">");
oBuffer.append("<soap:Body>");
oBuffer.append("<getLabratory xmlns=\"http://nano.ito.ir/\" />");
oBuffer.append("</soap:Body>");
oBuffer.append("</soap:Envelope>");
return oBuffer.toString();
};
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, false);
oRequest.setRequestHeader("Content-Type", "text/xml");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
LaboratoryService.prototype.handleResponse = function (sResponse) {
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
return sResponse.substring(start, end);
};
Bellow is my HTML code which uses LaboratoryService.js to show data:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Labratories</title>
<script language="JavaScript" src="LaboratoryService.js"></script>
<script language="JavaScript" src="jquery-1.8.0.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$("#btnGetLaboratories").click(function () {
var oService = new LaboratoryService();
var fResult = oService.send();
var newData = $('<div/>').html(fResult).text();
$("#divResult").html(newData);
});
});
</script>
</head>
<body>
<input id="btnGetLaboratories" type="button" value="Get Laboratories" />
<div id="divResult">
</div>
</body>
</html>
This approach works fine in Internet Explorer.
The problem is that this approach does not work in FireFox and Chrome.
I think that the oRequest.send(this.buildRequest()); does not work in FireFox and Chrome.
Edited Web Service Call Using JQuery
I changed LaboratoryService.prototype.send to use JQuery to call Web Service as bellow:
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml",
headers: { "SOAPAction": this.action },
success: function (msg) {
return this.handleResponse(msg);
},
error: function (e) {
alert('error');
}
});
};
But it alerts error. How do I call Web Service using JQuery?
Again Edited Code
I changed my JQuery AJAX call as bellow. It works fine in Internet Explorer but returns error in Chrome and Firefox.
LaboratoryService.prototype.send = function () {
$.ajax({
type: "POST",
url: this.URL,
contentType: "text/xml; charset=\"utf-8\"",
dataType: "xml",
data: this.buildRequest(),
processData: false,
success: function processSuccess(data, status, req) {
if (status == "success") {
var sResponse = req.responseText;
var start = sResponse.indexOf('div') - 4;
var end = sResponse.lastIndexOf('div') + 7;
var newData = $('<div/>').html(sResponse.substring(start, end)).text();
$("#divResult").html(newData);
}
},
error: function () {
alert('error');
}
});
};

Just change :
LaboratoryService.prototype.send = function () {
var oRequest = new XMLHttpRequest;
oRequest.open("post", this.url, true);
oRequest.setRequestHeader('User-Agent','XMLHTTP/1.0');
oRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
oRequest.setRequestHeader("SOAPAction", this.action);
oRequest.send(this.buildRequest());
if (oRequest.status == 200) {
return this.handleResponse(oRequest.responseText);
} else {
throw new Error("Request did not complete, code " + oRequest.status);
}
};
Please, refer this link.

Related

JS not autopopulating SharePoint User

I've included a snippet of code that doesn't seem to be doing what I want it to. In the past I've been able to use this to autopopulate a name based on the users name within SharePoint. There's no obvious errors, everything else in the script runs fine, and it appears this does to, it just doesn't do what's intended.
function getWebUserData() {
context = new SP.ClientContext.get_current();
web = context.get_web();
currentUser = web.get_currentUser();
currentUser.retrieve();
context.load(web);
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),
Function.createDelegate(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args) {
var userObject = web.get_currentUser();
$("input[Title='Requester']").val(userObject.get_title());
$("input[Title='Requester']").attr('disabled','disabled');
}
Below code works in my local SharePoint 2013. referenced thread
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/currentuser";
var requestHeaders = { "accept": "application/json;odata=verbose" };
$.ajax({
url: requestUri,
contentType: "application/json;odata=verbose",
headers: requestHeaders,
success: onSuccess,
error: onError
});
}
function onSuccess(data, request) {
var userName = data.d.LoginName;
//parse the value.
userName = userName.toString().split("i:0#.w|")[1];
SetUserFieldValue("Requester", userName);
}
function onError(error) {
//alert(error);
}
function SetUserFieldValue(fieldName, userName) {
var _PeoplePicker = $("div[title='" + fieldName + "']");
var _PeoplePickerTopId = _PeoplePicker.attr('id');
var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
_PeoplePickerEditer.val(userName);
var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
_PeoplePickerOject.AddUnresolvedUserFromEditor(true);
}
GetCurrentUser();
});
</script>

JQUERY Ajax Get Method to get properties of data

I have this assignment of using JQUERY Ajax method in Javascript to get the data of the get request of a Gateway URL and send some of it's property values to the properties of an existing object. I believe there's a simple way to go about it. Below is code and i hope someone out there can help out.
<!DOCTYPE html>
<html>
<head>
<title>Gateway Object</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<script src="jquery-2.1.4.js"></script>
<script>
gateway = {
ip: "",
hwv: "",
setIpAddress: function (ip) {
var self = this;
self.ip = ip;
},
getHardwareVersion: function () {
var self = this;
$.ajax({
type: "GET",
url: "http://" + self.ip + "/command?XC_FNC=GetSI",
timeout: 2000,
error: function (err) {
console.log("gateway error: check ip address and
try again");
},
success: function (data) {
if (data) {
if (data.substr(0, 8) === "{XC_SUC}") {
var jString = (data.slice(8));
var obj;
try {
obj = JSON.parse(jString);
} catch (e) {
}
self.hwv = obj.HWV;
//console.log(self.hwv);
}
else {
console.log("Error:" + "" + data);
}
}
else {
console.log("error with the gateway");
}
}
});
}
};
gateway.setIpAddress("200.201.51.126");
gateway.getHardwareVersion();
console.log(gateway);
</script>
</head>
<body></body>
</html>
This seems to work fine but "gateway.hwv" can't receive the property of the data object after the ajax request. Is it possible to do this over Ajax-Asynchronous method?
Using console.log(gateway); directly after gateway.getHardwareVersion(); is not going to work as you're expecting as the log will run before your ajax query has finished processing.
You are going to either need to change your ajax function to by synchronous or run whatever logic you need to run after the ajax call from its success function.
You can add the complete function to the Ajax and call the console.log inside it. So it'll show the gateway object to you only when the async Ajax request completes.
A sample (I setted the self.hwv to 1 just to fill it):
<script>
gateway = {
ip: "",
hwv: "",
setIpAddress: function (ip) {
var self = this;
self.ip = ip;
},
getHardwareVersion: function () {
var self = this;
$.ajax({
type: "GET",
url: "http://" + self.ip + "/command?XC_FNC=GetSI",
timeout: 2000,
error: function (err) {
console.log("gateway error: check ip address and try again");
},
success: function (data) {
if (data) {
if (data.substr(0, 8) === "{XC_SUC}") {
var jString = (data.slice(8));
var obj;
try {
obj = JSON.parse(jString);
} catch (e) {
}
self.hwv = obj.HWV;
//console.log(self.hwv);
}
else {
console.log("Error:" + "" + data);
}
}
else {
console.log("error with the gateway");
}
},
complete: function() {
self.hwv = "1";
console.log(gateway);
}
});
}
};
gateway.setIpAddress("localhost");
gateway.getHardwareVersion();
</script>

Weird behavior under chrome and $.ajax after chrome update

I've an asp.net mvc5 application that on a loginpage does the following Ajax call
$(document).ready(function () {
var formObj = $(".login-form");
$("form input[name=username]").val("user");
$("form input[name=password]").val("password1!");
formObj.submit(function (event) {
event.preventDefault();
console.log("test");
validator = formObj.validate();
if (validator.checkForm()) {
var form = formObj.get();
var rememberMe = $("input:checkbox[name=remember]:checked").val() ? true : false;
$(form.rememberMe).val(rememberMe);
args = {
form: form,
userName: $(form.username).val(),
password: $(form.password).val(),
remember: rememberMe
}
var url = #Url.Content("~/api/auth");
func = $.ajax({
url: url,
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
#if(Request.Params.Get("redirect") != null) {
<text>
window.location = "#Request.Params.Get("redirect")";
</text>
}
else
{
<text>
window.location = "#Url.Content("~/Home")";
</text>
}
}
}
});
}
});
});
If I put this piece of code
var url = #Url.Content("~/api/auth");
it works, otherwise if I quote the url string (as it should be correct)
var url = "#Url.Content("~/api/auth")";
it hangs the browser.
This only happens under chrome as first iussue was reported with Chrome Version 43.0.2357.65 m
What is wrong?
Thanks
UPDATE #1
I've noticed that the problem is there
$.ajax({
url: "/someurl",
data: args,
success: function (data) {
console.log("success")
if (data["ResponseStatus"]["ErrorCode"] == null) {
window.location = "/someotherurl/";
}
}
});
If I sue ajax it breaks...if I use $.post or $.get it works...

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

jQuery AJAX works on mobile safari, but not a UIWebView?

I have a basic jQuery ajax function to log the user in via a UIWebView. However, for some reason it returns blank when it's in a UIWebView. It works fine in mobile safari, and chrome and firefox on my computer.
Here's my code:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});
The theRetrievedData just returns blank on the alert.
Please help!
PS: The app is called "Dudles" in the app store (it's free) if you want to try to login. You will get a blank message from the alert.
Can you post your PHP code as well?
I refactored the code you wrote into how I would write it just to see if I could spot any bugs, and nothing seemed glaringly incorrect. Here is what I have so far:
$(document.body).on('click', '#login_button', function () {
$.ajax({
type: "POST",
url: "http://domain/location/process_login.php",
data: $(this).closest('form').serialize(),
success: function (response) {
var delimiter = "?!?success?!?";
var isSuccessful = response.indexOf(delimiter) !== -1;
if (!isSuccessful) {
// handle error
return;
}
$('#content').fadeOut(500, function () {
location = response.split(delimiter)[1];
});
}
});
});
try to send ajax request with async:true, like this:
$("#login_button").live('click',function() {
var serializeme = $("#login_form").serialize();
alert(serializeme);
$.ajax({
type: "POST",
async:true,
url: "http://domain/location/process_login.php",
data: serializeme,
success: function(theRetrievedData) {
var thePlace = theRetrievedData.indexOf("?!?success?!?");
if (thePlace != -1) {
var theArray = theRetrievedData.split("?!?success?!?");
var theUrl = theArray[1];
$('#content').fadeOut(500);
setTimeout( function() {window.location = theUrl;}, 500 );
} else {
alert(theRetrievedData);
alert("no bueno");
}
}
});
});

Categories

Resources