Modify ajax response that gets passed to .done() - ajax

this.getFullAddress(id).done(function(data) {
// need to have both the response (data) and the id
});
getFullAddress(id) {
var response = $.ajax({
url: 'http://whatever.com'
}); // modify this (add id)
return response;
}
Does anyone have an idea how to accomplish this ?

Ok, found it:
getFullAddress(id) {
$.ajaxSetup({
dataFilter: function (response) {
response = JSON.parse(response);
response['id'] = id;
response = JSON.stringify(response);
return response;
}
});
return $.ajax({
url: 'http://whatever.com'
});
}

Related

How do I return the response from an ajax call to store in a variable?

I would like to store a response result from an ajax call. This is because the ajax is the main API call used by several functions to extract information from an API.
I call callAPI function more than 8 times in my app.
Of course, I can duplicate the function callAPI 8 times to properly get information but this is not cool way to code.
var result = callAPI("GET",url,'');
$('#status').val(result.success);
$('#output').val(result);
function callAPI(method_input, url_input, body_input){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
});
}
I tried to store the return value using
var result = ajax(value);
but the result is empty
is there any way to store return value of a function to a variable?
EDIT
I Solved this problem by using callback function like below
function callbackResult(result){
$('#status').val(result.success);
$('#output').val(result);
}
function callAPI(method_input, url_input, body_input, callback){
var urli = url_input;
var datai = body_input;
var method = method_input;
$.ajax({
url: urli,
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("some header","some value");
},
type: method,
data: datai,
})
.done(function(data,status) {
console.log("success");
console.log(data);
return JSON.stringify(data);
callback(data);
})
.fail(function(data,status) {
console.log("error");
console.log(data);
return JSON.stringify(data);
callback(data);
});
}
This was my first function to use a callback function and now I know what the callback function is.
Thank you guys all.
You need 'async': false, so:
var result = $.ajax({
url: "https://api.github.com/users",
'async': false,
type: 'GET'
})
.done(function(data,status) {
console.log("success");
})
.fail(function(data,status) {
console.log("error");
});
console.log("result: " + result.responseText);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
A few things to note:
Instead of JSON.stringify() I think you want to use JSON.parse() to parse the JSON string that is probably been returned by your API.
You can use the $.ajax option dataType to automatically parse the JSON string into an object.
$.ajax() returns a promise which can be chained to add as many callbacks as needed.
A more elegant solution would be to return the promise from your function and chain your callbacks. Ex:
function callAPI(method_input, url_input, body_input) {
var urli = url_input;
var datai = body_input;
var method = method_input;
return $.ajax({
url: urli,
// Automatically parses JSON response
dataType: 'json',
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("some header", "some value");
},
type: method,
data: datai,
})
.done(function(data, status) {
console.log("success");
console.log(data);
})
.fail(function(data, status) {
console.log("error");
console.log(data);
});
}
callAPI('GET', '').then(function(result){
// Do something with my API result
});
If you plan on making all request at once, with this solution you can consider aggregating all the request into a single promise with $.when(). Ex:
$.when(
callAPI('GET', ''),
callAPI('GET', 'second'),
callAPI('GET', 'third')
).then(function(firstResult, secondResult, thirdResult){
// Do stuff with the result of all three requests
});

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;
}

Parse.Com - HTTP method in cloud code, how do I wait for the response

In my parse cloud code, the HttpRequest in beforeSave is getting executed successfully but the code blows through before I have had time to parse the response and determine whether I want to return a response.success() or a response.error().
I know I am missing something here, any input, ideas from the community here would be appreciated. Thanks
Parse.Cloud.beforeSave(Parse.User, function (request, response) {
   var user = request.object;
    var key = user.get("recaptcha"); 
Parse.Cloud.httpRequest({
url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
success: function (httpResponse) {
var status = JSON.parse(httpResponse.text).success;
console.log(status);
if (status === false) {
response.error();
} else {
response.success();
}
}
});
});
I got it working...Parse.Cloud.httpRequest() is asynchronous, here is the solution that worked for me, hope it helps someone else.
Parse.Cloud.beforeSave(Parse.User, function (request, response) {
var user = request.object;
var key = user.get("recaptcha");
if (!request.object.existed()) {
return Parse.Cloud.httpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'https://www.google.com/recaptcha/api/siteverify?secret=<ITS A SECRET>&response=' + key,
body: request,
success: function(httpResponse) {
var status = JSON.parse(httpResponse.text).success;
if (status === false) {
response.error();
} else {
response.success();
}
},
error: function(httpResponse) {
response.error(httpResponse);
}
});
}
});

I cannot send data from Angular to Django using $http

I'm trying to set up a form which add a new object to db but first I want to check something and set up the server side for new record, but I'm frozen :(
Here is my code, please give it a try:
ctrl
subtitlesApp.controller('AddSubtitleController',
function($scope, addSubtitle) {
$scope.saveSubtitle = function(subtitle, addSubtitleForm) {
if (addSubtitleForm.$valid) {
var x = addSubtitle.getTitle(subtitle.imdb_id);
}
};
});
service
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
$http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
}
}
}]);
And here's what I'm getting when I print request.POST:
<QueryDict: {}>
You should let the service return a promise
subtitlesApp.factory('addSubtitle', ['$http', function ($http) {
return {
getTitle: function(imdb_id) {
var promise = $http({
method: 'POST',
url:'add_subtitle/',
data: imdb_id,
})
.success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
console.log(imdb_id+'eror')
});
return promise;
}
}
}]);
When consume the service
var x;
if (addSubtitleForm.$valid) {
addSubtitle.getTitle(subtitle.imdb_id).then(function(data){
x = data;
});
}

Resources