I have a custom function. Inside this function is an $.ajax
call that returns a string that I want to convert to JSON with JSON.parse
and then return.
Now, I figured out how to return the string and then JSON.parse
on other side when the data is returned. However, when I try to convert the string to JSON already in the function and return it – this does not work and I do not understand why.
My guess is that I do not understand how to handle the $.ajax
return-object and how to retrieve the responseText from this object.
Here is my code;
$.plugin.ownfunction = function(options) {
var promised_data = $.ajax({
method: "POST",
url: "plugin/php/somephp.php",
data: opts
})
// this does not work
// promised_data = JSON.parse(promised_data);
// this also does not work
// promised_data = JSON.parse(promised_data.responseText);
return promised_data;
};
on the other side I do this;
$.database.readbehavior({ some options }).done(function(data) {
// this does work – but I would like to do the JSON.parse already in the function
var x = JSON.parse(data);
console.log(x);
});
edit: I am sorry to disagree – but this is not a duplicate of the How to return the response from an asynchronous call? topic. I managed to return a response from an asynchronous call. The Problem is the format of this response that I have trouble with.
solution:
As Hacketo pointed out in the comments; Adding dataType : "json"
to the $.ajax
call returns the data as JSON. Problem solved! Thank You!