How to get response from ajax success call - javascript

I want to get response of ajax success call in variable 'response' from where I called function .
Call of function:
var response = ExecuteAction(Id,Entityname,Processname);
Function:
function ExecuteAction(entityId, entityName, requestName) {
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
async:false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function (data, textStatus, XmlHttpRequest) {
debugger;
if (XmlHttpRequest.status === 200) {
var response = $(XmlHttpRequest.responseText).find('b\\:value').text();
return response;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
Please suggest me answer.

This is not how JS asynchronous functions are meant to be used. You should be using callbacks, unless you're using es6 in which you should use promises. But if for some reason you absolutely had to get it to work, you could do something like this (note, i did not test this).
function ExecuteAction(entityId, entityName, requestName) {
var response;
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
async: false,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function(data, textStatus, XmlHttpRequest) {
debugger;
if (XmlHttpRequest.status === 200) {
response = $(XmlHttpRequest.responseText).find('b\\:value').text();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
while (!response);
return response;
}
Here's how to use a callback with the function
function ExecuteAction(entityId, entityName, requestName, callback) {
var response;
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
async: false,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function(data, textStatus, XmlHttpRequest) {
debugger;
if (XmlHttpRequest.status === 200) {
response = $(XmlHttpRequest.responseText).find('b\\:value').text();
callback(null, response);
}
},
error: function(XMLHttpRequest, textStatus, error) {
alert(error);
callback(error);
}
});
}
called as such
var response = ExecuteAction(Id,Entityname,Processname, function(err, result) {
if (err) console.log('whoops, error', err);
console.log('I will print upon completion', result);
});

Your problem is that you are using a sync function when AJAX is async,
you can use a Promise -
return new Promise( (resolve, reject) => {
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function (data, textStatus, XmlHttpRequest) {
if (XmlHttpRequest.status === 200) {
var response = $(XmlHttpRequest.responseText).find('b\\:value').text();
resolve(response);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
reject(errorThrown);
}
});
and then use it like that
var responsePromise = ExecuteAction(Id,Entityname,Processname);
responsePromise.then( (response) => {
console.log(response)
},
(error) => {
console.log(error)
});

Related

Firebase Dynamic Link Creation With JavaScript

var object={
"longDynamicLink": "https://[APP_NAME].page.link/?link=[LINK_HERE]",
"suffix":{
"option":"SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
dataType: "json",
data: object,
success: function(response, textStatus, jqXHR) {
alert(response.shortLink);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
The above code works if the "suffix" is deleted from the request. That makes an "UNGUESSABLE" url, but I want a short URL. As stated in the documentation at https://firebase.google.com/docs/dynamic-links/rest?authuser=0 I added the suffix option parameter, but it results with a 400 response. Any ideas why?
I haven't ever tried this but, ...
POST https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=api_key
var params = {
"longDynamicLink": "https://example.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
"suffix": {
"option": "SHORT"
}
}
$.ajax({
url: 'https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[KEY_HERE]',
type: 'POST',
data: jQuery.param(params) ,
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});

Fetch some data from xml response comes from ajax jquery call

I have ajax call with type post and in success I get xml response as per below .And I want to fetch "This is Response" from the response displayed below.
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function (data, textStatus, XmlHttpRequest) {
debugger;
if (XmlHttpRequest.status === 200) {
var response = XmlHttpRequest.responseXML;
alert(XmlHttpRequest.responseText);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
Response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><ExecuteResponse xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"><ExecuteResult xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:ResponseName>new_PASMcreateProject</a:ResponseName><a:Results xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic"><a:KeyValuePairOfstringanyType><b:key>Response</b:key><b:value i:type="c:string" xmlns:c="http://www.w3.org/2001/XMLSchema">This is response</b:value></a:KeyValuePairOfstringanyType></a:Results></ExecuteResult></ExecuteResponse></s:Body></s:Envelope>
Please suggest me the answer.
Have you checked with data in success method?
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",
url: serverUrl + "/XRMServices/2011/Organization.svc/web",
data: requestXML,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
},
success: function (data, textStatus, XmlHttpRequest) {
alert($(XmlHttpRequest.responseText).find('b\\:value').text()); // check this in console.log
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
You can see in console with object.. you can retrieve data from object easily...
something like
$(data).find('b\\:value').text();
Take a look at XMLHttpRequest. If you want to use raw text, you can use XmlHttpRequest.responseText
If you want to use XML format, use jQuery parseXML to parse the returned XML. For example:
...
success: function (data, textStatus, XmlHttpRequest) {
if (XmlHttpRequest.status === 200) {
var responseXML = $.parseXML(XmlHttpRequest.responseXML),
$responseXML = $(responseXML),
$responseValue = $responseXML.find('b\\:value');
console.log(responseXML);
}
},
...
Or using plain Javascript (from here)
...
success: function (data, textStatus, XmlHttpRequest) {
if (XmlHttpRequest.status === 200) {
parser = new DOMParser();
responseXML = parser.parseFromString(XmlHttpRequest.responseXML, "text/xml");
var response = responseXML.getElementsByTagName('b\\:value')[0].childNodes[0].nodeValue;
console.log(response);
}
},
...

How to post json ajax request to web API

I'm unable to get json data from server side. The script calls the server method but no json data returned.
$(document).ready(function() {
$("#SendMail").click(function() {
$.ajax({
url: "http://localhost:2457/SendMail/SendMail/",
dataType: 'json',
type: 'POST',
data: "{htmlTemplate:" + "ABC" + "}",
//crossDomain: true,
//contentType: "application/json; charset=utf-8",
success: function(data, textStatus, xhr) {
console.log(data);
alert('Successfully called');
},
error: function(xhr, textStatus, errorThrown) {
// console.log(errorThrown);
}
});
});
});
Function SendMail(htmlTemplate As String) As String
Dim fname As String = Request.Form("htmlTemplate1")
Dim lname As String = Request.Form("lname")
Dim cmdSendMail As New SendMailCommand()
Return "A"
End Function
<script>
$(document).ready(function () {
$("#SendMail").click(function() {
$.ajax({
url: '/SendMail/SendMail/',
dataType: 'text',
type: 'POST',
data:JSON.stringify({htmlTemplate: "ABC"}),
//crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus, xhr) {
console.log(data);
alert('Successfully called');
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
});
</script>

Why Unable to get success callback in Jquery/ajax call to RESTful services?

function GET() {
jQuery.support.cors = true;
$.ajax({
url: 'http://localhost:32253/api/UserDetail/GetRoleDetails',
type: 'GET',
async:true,
contentType: "application/json",
dataType: 'json',
xhrFields: {
withCredentials: true
},
error: function (xhr, status)
{
alert(status);
},
success: function (data) {
alert("Success!");
}
});
return false;
}
I am very much new to ajax,I tried a ajax call to my services method which returns value.But the success callback function is never fired .I only get error.What might be the reason?
I tried using dataType to jsonp and other similar solutions which had been found in Stackoverflow regarding this issue.Nothing worked out.I am getting server response as 200 oK.
try this code
$.ajax({
type: "POST",
url: URL,
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
jsonp: "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "false",
beforeSend: function (xhr) {
},
error: function (request, status, error) {
console.log("Error In Web Service...." + request.responseText);
return false;
},
success: ajax_success,
complete: function (xhr, status) {
}
});
create function "ajax_success" in ur page
like below
function ajax_success(parsedJSON) { //you code here
}
this may be help you
try this code
$.ajax({
type: "POST",
url: URL,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
jsonp: "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "false",
beforeSend: function (xhr) {
},
error: function (request, status, error) {
console.log("Error In Web Service...." + request.responseText);
return false;
},
success: function (data) {
Result = data;
},
complete: function (xhr, status) {
}
});

Consuming Webservice in JavaScript

Now, i want to use service from http://www.webservicex.net/globalweather.asmx to get weather by javascript. I try this code:
var wsUrl = "http://www.webservicex.net/globalweather.asmx?op=GetWeather";
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status == "success")
$("#response").text($(req.responseXML).find("GetWeatherResult").text());
}
function processError(data, status, req) {
alert(req.responseText + " " + status);
// alert("Error");
}

Categories

Resources