Related
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)
});
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>
I am quite green when it comes to AJAX and am trying to get an email address from an ASP.Net code behind function
When using the below code I am getting the error as per the title of this issue.
This is the code I am using
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
});
which is an adaptation of the code from this site.
ASP.Net Snippets
When changing the line
success: OnSuccess to success: alert(response) or success: alert(data)
I get the error up, but if I use success: alert("ok") I get the message saying ok so I suspect that I am getting into the function as below.
<System.Web.Services.WebMethod()> _
Public Shared Function FindEmailAddress(ByVal id As String) As String
Dim response As String = GetEmail(id)
Return response
End Function
I would be extremely grateful if someone to help me and let me know where I am going wrong on this one.
thanks
I think you have can check the state of failure by using this code below as I think there is wrong syntax used by you.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: JSON.stringify({id: ' + $(".txtRequester").val() + ' }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status, header){
console.log(data);
},
error: function (response) {
alert(response.d);
}
});
}
});
then definitely you will get error response, if your success won't hit.
You have not called the function thats why its never get called.
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
ShowCurrentTime();
});
function ShowCurrentTime() {
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: '{id: "' + $("txtRequester").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Onsuccess(response);
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
This will help :)
use ajax directly ,
$('.txtRequester').focusout(function () {
console.log("textBox has lost focus");
var cond = $(".txtRequester").val();
$.ajax({
type: "POST",
url: "Default.aspx/FindEmailAddress",
data: {id:cond},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response){
alert(response.d);
},
failure: function (response) {
alert(response.d);
}
});
});
Change $('.txtRequester') to $('#txtRequester')
and
Change $("txtRequester").val to $('#txtRequester').val()
Is it possible to make an ajax request inside another ajax request?
because I need some data from first ajax request to make the next ajax request.
First I'm using Google Maps API to get LAT & LNG, after that I use that LAT & LNG to request Instagram API (search based location).
Once again, is this possible, and if so how?
$('input#search').click(function(e) {
e.preventDefault();
var source = $('select[name=state] option:selected').text()+' '+$('select[name=city] option:selected').text()+' '+$('select[name=area] option:selected').text();
var source = source.replace(/ /g, '+');
if(working == false) {
working = true;
$(this).replaceWith('<span id="big_loading"></span>');
$.ajax({
type:'POST',
url:'/killtime_local/ajax/location/maps.json',
dataType:'json',
cache: false,
data:'via=ajax&address='+source,
success:function(results) {
// this is where i get the latlng
}
});
} else {
alert('please, be patient!');
}
});
Here is an example:
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page=' + btn_page,
success: function (data) {
var a = data; // This line shows error.
$.ajax({
type: "post",
url: "example.php",
data: 'page=' + a,
success: function (data) {
}
});
}
});
Call second ajax from 'complete'
Here is the example
var dt='';
$.ajax({
type: "post",
url: "ajax/example.php",
data: 'page='+btn_page,
success: function(data){
dt=data;
/*Do something*/
},
complete:function(){
$.ajax({
var a=dt; // This line shows error.
type: "post",
url: "example.php",
data: 'page='+a,
success: function(data){
/*do some thing in second function*/
},
});
}
});
This is just an example. You may like to customize it as per your requirement.
$.ajax({
url: 'ajax/test1.html',
success: function(data1) {
alert('Request 1 was performed.');
$.ajax({
type: 'POST',
url: url,
data: data1, //pass data1 to second request
success: successHandler, // handler if second request succeeds
dataType: dataType
});
}
});
For more details : see this
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
I have a field on my database that stores a number of clicks, and want to increment that when I click in a link(<a href="#selecoes" data-identity="31" id="clicks" clicks="0">) of my tag cloud. Note that I get the number of clicks throught my webservice. This is I do so far:
index.html
<div id="tags">
<ul id="tagList">
<li>
<img src='.../>Brasil
</li>
</ul>
main.js
$('#tagList a').live('click', function() {
findByIdSelecoes($(this).data('identity'));
});
function findByIdSelecoes(id) {
console.log('findByIdSelecoes: ' + id);
$.ajax({
type: 'GET',
url: rootURLSelecoes + '/id/' + id,
dataType: "json",
success: function(data){
$('#btnDelete').show();
console.log('findByIdSelecoes success: ' + data.nome);
currentWine = data;
renderDetails(currentWine);
findJogadoresBySelecao(id);
addClick(currentWine);
}
});
}
function addClick(selecao) {
console.log('addClick na seleção: ' + selecao.id_selecao);
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: rootURLSelecoes + '/update/' + selecao.id_selecao,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert('clicks updated successfully');
},
error: function(jqXHR, textStatus, errorThrown){
alert('updateWine error: ' + textStatus);
}
});
}
function formToJSON() {
return JSON.stringify({
"clicks": ($('#clicks').val())++ // i dont know what i have to do so i try this(don't work)
});
}
I can't update the dataBase when I click the link in the list. The function formToJSON doesn't increment the value in the database.
Try to do this
Make a var number like global, and do this:
function addClick(selecao) {
console.log('addClick na seleção: ' + selecao.id_selecao);
number = parseInt(selecao.clicks,10);
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: rootURLSelecoes + '/update/' + selecao.id_selecao,
dataType: "json",
data: formToJSON(),
success: function(data, textStatus, jqXHR){
alert("Done: " +number);
},
error: function(jqXHR, textStatus, errorThrown){
alert('updateWine error: ' + textStatus);
}
});
}
function`enter code here` formToJSON() {
var ola = parseInt(number,10);
ola = ola +1;
return JSON.stringify({
"clicks": parseInt(ola,10)
});
}