Reputation: 827
I have two functions. The first sets a variable then the second get's the information needed for the first function. The issue I was first having was that everything was getting returned before the ajax response was happening. Basically what I need to do is get a JSON object and set it to a variable, then uses certain aspects of that object and append them to items. here's what I have...
$(document).ready(function(){
$('#youtube-url').blur(function() {
$info = youtubeInfo($('#youtube-url').val());
console.log($info);
if($info.html){
//alert($info.thumbnail_url);
//$('#preview_video_thumb').attr('src', $info.thumbnail_url);
}
});
});
function youtubeInfo(url){
var odata = '';
var result = jQuery.ajax({
url: '<? echo base_url("videos/getOembed") ?>',
type: 'POST',
dataType: 'json',
async: false,
data: {url: url},
complete: function(xhr, textStatus) {
},
success: function(data, textStatus, xhr) {
return data;
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
}).responseText;
return result;
};
If I return the 'data' object from within the success callback it returns blank. if I do it how it is, the responseText of the AJAX call is a string and not JSON. any ideas? I basically need to set the $info variable in the first function to the AJAX response (JSON) of the second function.
Upvotes: 2
Views: 7896
Reputation: 11152
The return data
statement you have in the success function is not doing what you intend. It is not actually returning out of the ajax call, but rather returning out of the success function. What you probably want is something like this instead:
function youtubeInfo(url){
var odata = '';
var result = jQuery.ajax({
url: '<? echo base_url("videos/getOembed") ?>',
type: 'POST',
dataType: 'json',
async: false,
data: {url: url},
complete: function(xhr, textStatus) {
},
success: function(data, textStatus, xhr) {
odata = data;
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
return odata;
};
Upvotes: 0
Reputation: 95055
Remove .responseText
and use this:
$('#youtube-url').blur(function() {
youtubeInfo($('#youtube-url').val()).done(function($info){
if($info.html){
//alert($info.thumbnail_url);
//$('#preview_video_thumb').attr('src', $info.thumbnail_url);
}
});
});
Upvotes: 3