For rendering a dialog, i have two jQuery ajax calls. One to load the buttons and another to load the body of the dialog. I first call the function that loads the buttons (asychronous ajax call)
$.ajax({
type: "POST",
//async: false,
url: action,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('#dialogButtons').html(result);
},
error: function (req, status, error) {
alert(req + " " + error + " " + status);
}
Then i call another similar ajax call to load the body of the dialog in asychronous fashion.
The buttons doesn't always show up. So I made
$.ajaxSetup({ async: false });
$.ajax({
asyc: false,
url: action
})
$.ajaxSetup({ async: true });
as per other stack overflow experts. i am seeing mixed opinions on this approach.
Please help me with the standard way to achieve this.
Do the second AJAX call in the success function of the first.
$.ajax({
type: "POST",
url: action,
dataType: "html",
success: function(result) {
$('#dialogButtons').html(result).hide(); // Will show it after 2nd AJAX call
$.ajax({
type: "POST",
dataType: "html",
url: otheraction,
success: function(result) {
if (result) {
$("#dialog").html(result);
$("#dialogButtons").show();
}
}
});
},
error: function(req, status, error) {
alert(req + " " + error + " " + status);
}
});
You also shouldn't have contentType: "application/json". You're not sending any post data, and $.ajax doesn't send JSON; if you had post data, it would be URL-encoded.
Related
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()
In the code, .moneychoose is the div in moneychoose.jsp. $(".moneychoose") can not be selected in the ajax call.
$("input[name='money']").on("click", function() {
if ($("#money").find(".moneychoose")) {
$(".moneychoose").remove();
}
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
});
But if i add console.log($(".moneychoose")) after "append external html",
$(".moneychoose") in ajax call can be selected. why? however, the $(".moneychoose") after "append external html" still can not be selected.
$("input[name='money']").on("click", function() {
if ($("#money").find(".moneychoose")) {
$(".moneychoose").remove();
}
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
console.log($(".moneychoose"));
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
});
Your confusion is because console.log is not synchronous.
Your error is because you have a race condition between two AJAX requests.
//append external html
$.get("moneychoose.jsp", function (data) {
$("#money").append(data);
});
And
$.ajax({
type: "POST",
url: "src/province_price.json",
data: '',
dataType: "json",
async: "false",
success: function(response) {
console.log($(".moneychoose"));
},
error: function(qXhr, status, error) {
alert(status + ':' + error + ':' + qXhr.responseText);
}
});
In order to ensure that .moneychoose is available in the success callback of $.ajax, you will either need to use a Promise that resolves once both requests have succeeded, or you will need to wait to execute one of the requests until the other has finished.
I have a html/javascript application. When user refreshes the page or close the page i need to make a ajax request and then close the application.
I am using page unload event for this purpose.
I am calling
window.onbeforeunload=beforeFunction;
beforeFunction will make the ajax request. But when i check in fiddler i dont see the ajax request. However if i debug the application and execute each line with f10 then i see the ajax request in fiddler.
thats how my ajax request is formed:
$.ajax({
url: url,
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
dataType: 'jsonp',
success: function(json){
alert("success: " + json);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
$(window).on('beforeunload' function() {
$.ajax({
url: url,
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
dataType: 'jsonp',
success: function(json){
alert("success: " + json);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
});
Try this....
I'm trying to get some information from a different domain, the domain allows only jsonp call - others get rejected. How can I get the content instead of execution? Because I get an error in response. I don't need to execute it, I just need it in my script. In any format (the response is json but js doesn't understand it).
I can't affect on that domain so it's impossible to change something on that side.
Here's my code:
$.ajax({
url: url + '?callback=?',
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
window.jsonpCallback = function(response) {
console.log('callback success');
};
There are a few issues with your $.ajax call.
$.ajax({
url: url + '?callback=?',
// this is not needed for JSONP. What this does, is force a local
// AJAX call to accessed as if it were cross domain
crossDomain: true,
// JSONP can only be GET
type: "POST",
data: {key: key},
// contentType is for the request body, it is incorrect here
contentType: "application/json; charset=utf-8;",
// This does not work with JSONP, nor should you be using it anyway.
// It will lock up the browser
async: false,
dataType: 'jsonp',
// This changes the parameter that jQuery will add to the URL
jsonp: 'callback',
// This overrides the callback value that jQuery will add to the URL
// useful to help with caching
// or if the URL has a hard-coded callback (you need to set jsonp: false)
jsonpCallback: 'jsonpCallback',
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You should be calling your url like this:
$.ajax({
url: url,
data: {key: key},
dataType: 'jsonp',
success: function(response) {
console.log('callback success');
},
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
JSONP is not JSON. JSONP is actually just adding a script tag to your <head>. The response needs to be a JavaScript file containing a function call with the JSON data as a parameter.
JSONP is something the server needs to support. If the server doesn't respond correctly, you can't use JSONP.
Please read the docs: http://api.jquery.com/jquery.ajax/
var url = "https://status.github.com/api/status.json?callback=apiStatus";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'apiStatus',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Try this code.
Also try calling this url directly in ur browser and see what it exactly returns, by this way You can understand better what actually happens :).
The jsonpCallback parameter is used for specifying the name of the function in the JSONP response, not the name of the function in your code. You can likely remove this; jQuery will handle this automatically on your behalf.
Instead, you're looking for the success parameter (to retrieve the response data). For example:
$.ajax({
url: url,
crossDomain: true,
type: "POST",
data: {key: key},
contentType: "application/json; charset=utf-8;",
async: false,
dataType: 'jsonp',
success: function(data){
console.log('callback success');
console.log(data);
}
error: function(xhr, status, error) {
console.log(status + '; ' + error);
}
});
You can also likely remove the other JSONP-releated parameters, which were set to jQuery defaults. See jQuery.ajax for more information.
I have a javascript function which makes a JSON call to a web service using jQuery.
In the success function I need to evaluate the JSON response and if necessary make another call to a different method in the same web service.
Here is how I do it:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
end = endFunction(aid);
if (end) {
// do some other stuff
}
}
},
failure: function (errorMsg) { alert(errorMsg.toString()); }
});
}
and the endFunction which is being called from within the ajax success function:
function endFunction(aid) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return hasEnded;
}
Here is the weird stuff. The ajax-call is made all right. The code on the server is running according to plan. However, if I try to set a firebug breakpoint in the success function of endFunction(aid) is is not hit, but the alert box is shown displaying the word true. This is somewhat good since it seems that we are actually reaching the success function. The hasEnded variable however is never set to true so it always returns false.
Calling endFunction(1) from the Firebug console displays an alert box with the word true and returns value false.
What's going wrong?
AJAX is asynchronous — the $.ajax call will not wait for the server to reply.
Therefore, the return hasEnded; line runs before the AJAX callback.
You need to make your endFunction take a callback parameter, like $.ajax does.
http://api.jquery.com/jQuery.ajax/
It looks like you're using "failure" in the documentation you have "error":
error(XMLHttpRequest, textStatus, errorThrown)
also you should do something like this:
function firstAjaxCall(aid, tid) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method1",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (response) {
var respData = response.d;
//do some stuff
if (respData.HasEnded == true) {
clearInterval(tid);
var end = false;
endFunction(aid,function(endv){
if (endv) {
// do some other stuff
}
});
}
},
error: function (errorMsg) { alert(errorMsg.toString()); }
});
}
function endFunction(aid,endcallback) {
var hasEnded = false;
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "/webservices/Webservice.asmx/Method2",
data: "{ auctionId: '" + aid + "'}",
dataType: "json",
success: function (callbackData) {
var endRespData = callbackData.d;
hasEnded = endRespData.Success;
alert(hasEnded.toString());
endcallback(hasEnded);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
endcallback("?");
}
});
//return hasEnded;
}