How to return AJAX response Text? [duplicate] - ajax

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I use prototype to do my AJAX development, and I use the code like this:
somefunction: function(){
var result = "";
myAjax = new Ajax.Request(postUrl, {
method: 'post',
postBody: postData,
contentType: 'application/x-www-form-urlencoded',
onComplete: function(transport){
if (200 == transport.status) {
result = transport.responseText;
}
}
});
return result;
}
And I find that the "result" is an empty string. So, I tried this:
somefunction: function(){
var result = "";
myAjax = new Ajax.Request(postUrl, {
method: 'post',
postBody: postData,
contentType: 'application/x-www-form-urlencoded',
onComplete: function(transport){
if (200 == transport.status) {
result = transport.responseText;
return result;
}
}
});
}
But it didn't work also. How can I get the responseText for other method to use?

remember that onComplete is called long after the someFunction is done working. What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete):
somefunction: function(callback){
var result = "";
myAjax = new Ajax.Request(postUrl, {
method: 'post',
postBody: postData,
contentType: 'application/x-www-form-urlencoded',
onComplete: function(transport){
if (200 == transport.status) {
result = transport.responseText;
callback(result);
}
}
});
}
somefunction(function(result){
alert(result);
});

How about adding "asynchronous: false" in your code? In my case, it worked well :)

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

Ajax call to Webmethod, cross domain

I have two Asp projects. On close of a dialog box in project A I am trying to call a static webmethod in project B using ajax call.
Instead of calling the Webmethod it is calling the PageLoad.
Any ideas what I am doing wrong?
WebMethod
[WebMethod]
public static string UpdateSession()
{
return "Test";
}
$(function () {
$('div#DialogDiv').on('dialogclose', function (event) {
CloseDialog("http://localhost:1330/Application_Default.aspx/UpdateSession");
return false;
});
});
function CloseDialog(URL) {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: URL,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert("success");
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}
Try this with pure javascript
function CloseDialog(URL) {
var request = new XMLHttpRequest();
request.open("GET", URL);
request.onload = function() {
if (request.status === 200) {
alert(request.responseText);
// to convert to JSON object-> JSON.parse(request.responseText);
} else {
alert("Failed to trying to find the method: " + URL );
}
};
request.send();
return false;
}
With jQuery I would just do this, you don't need more. It should work with cross-domain too.
function CloseDialog(URL) {
$.ajax({
url: URL,
success: function (response) {
jQuery.each(result.list, function(i, val) {
// iterate the JSON object
// val.node;
});
},
failure: function (response) {
alert("Failed to trying to find the method: " + URL );
}
});
return false;
}

jQuery.ajax() inside a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
If I call jQuery.ajax() inside a loop, would it cause the call in current iteration overwrite the last call or a new XHR object is assigned for the new request?
I have a loop that do this, while from console log I can see requests done 200 ok but just the result data of the last request in the loop is stored by the request success callback as supposed .
the code:
var Ajax = {
pages: {},
current_request: null,
prefetch: function () {
currentPath = location.pathname.substr(1);
if(this.pages[currentPath])
{
var current = this.pages[currentPath];
delete this.pages[currentPath];
current['name']=currentPath;
current['title']=$("title").text().replace(' - '.SITE_NAME, '');
current['meta_description']=$("meta[name=description]").attr('content');
current['meta_keywords']=$("meta[name=keywords]").attr('content');
}
var _Ajax = this;
//the loop in question *****
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
if(current)
{
this.pages[currentPath] = current;
}
}
};//Ajax Obj
for(var i in pages)
{
Ajax.pages[pages[i]]={};
}
$(function() {
Ajax.prefetch();
});//doc ready
You'll need a closure for key:
for(var k in this.pages){
(function(key){
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
})(k);
}
that way you make sure that key is always the correct on in each ajax success callback.
but other than that it should work
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
http://jsfiddle.net/KS6q5/
You need to use async:false in you ajax request. It will send the ajax request synchronously waiting for the previous request to finish and then sending the next request.
$.ajax({
type: 'POST',
url: 'http://stackoverflow.com',
data: data,
async: false,
success: function(data) {
//do something
},
error: function(jqXHR) {
//do something
}
});
I believe what's happening here has to do with closure. In this loop:
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
The variable key is actually defined outside the for loop. So by the time you get to the callbacks, the value has probably changed. Try something like this instead:
http://jsfiddle.net/VHWvs/
var pages = ["a", "b", "c"];
for (var key in pages) {
console.log('before: ' + key);
(function (thisKey) {
setTimeout(function () {
console.log('after: ' + thisKey);
}, 1000);
})(key);
}
I was facing the same situation, I solved using the ajax call inside a new function then invoke the function into the loop.
It would looks like:
function a(){
for(var key in this.pages)
{
var paramsOut [] = ...
myAjaxCall(key,paramsOut);
.......
}
}
function myAjaxCall(paramsIn,paramsOut)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+paramsIn[0],
success: function(data) {
paramsOut[key] = data;
}
});
}
This is how I always do a ajax loop..
I use a recursive function that gets called after the xhr.readyState == 4
i = 0
process()
function process() {
if (i < 10) {
url = "http://some.." + i
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert(xhr.responseText)
i++
process()
}
}
xhr.send();
} else {
alert("done")
}
}

Send JSON string to a C# method

In my ASP.NET page I have the following method:
public static void UpdatePage(string accessCode, string newURL)
{
HttpContext.Current.Cache[accessCode] = newURL;
}
It actually should receive the accessCode and newURL and update the Cache accordingly. I want to pass the values to that method from JavaScript, using an AJAX request. The code for it is as follows:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var dataToSend = [ {accessCode: code, newURL: url} ];
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {"items":dataToSend},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However this doesn't seem to work. Could anybody help me figure out where the bug is?
UpdatePage is a void method that doesn't return anything, so there is nothing to look at in the response.
You could look at the HTTP return code and check that it was 200 OK or you could modify the web method:
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result
}
Edit:
It looks like your JSON arguments to the WebMethod are incorrect, you don't need the "items" in your JSON. The arguments should match your webmethod exactly.
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}

Resources