Retrieving data from AJAX function for another outside function - ajax

I need to get a new file name using an ajax call so I can use it in another function. This is the original call for the new filename I am trying to retrieve from the setup_file function. The file array has all the data I need including the original file name.
var newfilename = setup_file(file);
But when I try to return the data I need from said function, it doesn't work.
function setup_file(file) {
var newfilename;
var newtitle = jQuery("#choosetitle").val();
var aspect = jQuery("#chooseaspect").val();
var uploadlanguage = jQuery("#uploadlanguage").val();
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
type : 'POST',
async: false,
datatype : 'JSON',
data : {action : 'process_uploads',fileinfo: file,filetitle : newtitle, aspect : aspect, uploadlanguage : uploadlanguage},
success : function(data){
var json = JSON.parse(data);
var newfilename = json['filename'];
alert(newfilename);
//this alerts fine.
}
});
return newfilename;
//thisreturnsnothing, however if I change it to return 'Whatever'; it does return Whatever.
}

You created, same variable again in the success block, that cause the outer variable empty. Change the
var newfilename = json['filename'];
to
newfilename=json['filename']
In the success block.

Related

How to load a .csv file into crossfilter with d3?

I am trying to load a .csv file into crossfilter for further use it with dc.js and d3. However, if the ndx = crossfilter(data_) is not inside d3.csv(..., it does not work. Is it possible to load data using d3 inside a global/outside variable (in this case ndx)?
var ndx;
private method(){
var data_;
d3.csv("samples.csv", function(data){
var format = d3.timeParse("%m-%y");
data.forEach(function(d: any) {
d.date = format(d.date);
});
data_ = d3.csvParse(data);
});
ndx = crossfilter(data_);
}
How can I load it into crossfilter?
Am I obligated to use crossfilter inside the d3.csv(.. call?
Solution:
I made my .csv became a .json and I loaded it 'synchronously'. Observe below.
var ndx;
private method(){
var data_ = (function() {
var json: any = null;
$.ajax({
'async': false,
'global': false,
'url': "samples.json",
'dataType': "json",
'success': function (data:any) {
json = data;
}
});
return json;
})();
ndx = crossfilter(data_);
}
Observe:
'async': false
This happens because the callback function is executed asynchronously, once the data is returned. This means that if you put the charting code outside of the callback, you are going to get the empty array that you defined because no data has been returned yet.

Unable to extract the string i want from the ajax post

In my asp mvc project i've got an ajax call that posts the value of a dropdown list and i want the session to be set with this value.
$('#dropDownMenu').on('click', 'li', function () {
var txt = $('#schoolButtons').text();
data = {session: txt};
var requestValue = JSON.stringify(data);
$.ajax({
url: '#Url.Action("SetSession")',
type: 'POST',
data: "requestValue="+requestValue ,
}).success(function (data, textStatus, jqXHR) {
});
});
public ActionResult SetSession(string requestValue)
{
var sessionVal = Convert.ToString(requestValue);
if (sessionVal==null)
{
Debug.WriteLine("session is null");
}
Session["key"] = sessionVal;
return Json(requestValue);
}
When I output the value of the session i'm getting the string {"session":"State School"} when all i want is "State School". I know in the function data is set to {session: txt} but how do i just extract that txt?
Regards,
Mike.
To read the JSON value you need to read it this way
var requestValue = data.session
Since you pass it as a string into the function and want to read it in the function, this is what I sugggest you do. You need to convert the string to JSON and extract the value.
public ActionResult SetSession(string requestValue)
{
var JSONData = JSON.parse(requestValue);
var sessionVal = JSONData.session;
...
...

I want the returned data to be written to the div tag of the html

function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html(reponse);
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});
I am trying to pass variable q to a php file and get back the result . I am getting the result but I am getting an error paramete q is undefined .
You can use JSON.stringify:
function showPrice(data) //pass the data as an object literal instead of a string
{
var $remaining = $('#remaining');
$remaining.empty();
$.ajax({
url: 'getevent.php',
data: data,
success: function(reponse){
$remaining.html( JSON.stringify(reponse) );
}
});
}
$('#events').change(function(){
var pluspoint=$('#events').val();
var data = { q : 1};
showPrice(data);
});

Reduce Repetitiion with AJAX JSON Calls to an API

I have about 15 copies of the following code on my site. The only things changing are the url, longitude, latitude, and the marker variable title. How can I chop this up and reduce the repetition?
$.ajax({
url: "http://api.wunderground.com/api/<api_key>/conditions/q/pws:KCASANFR128.json",
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(37.779806, -122.471895), {icon: iconPic});
markerRichmond.bindPopup("Current temperature in " +location+ " is: " +temp_f+ " and it is " + weather);
map.addLayer(markerRichmond);
}});
You could make a function which takes in those variables and feeds them to the ajax call. Then you would only need one copy of this ajax block, which you could call by calling the getWeather function
function getWeather(url, lat, long, title){
$.ajax({
url: url,
dataType: "jsonp",
success: function(parsed_json) {
var location = parsed_json['current_observation']['observation_location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
var weather = parsed_json['current_observation']['weather'].toLowerCase();
var iconUrl = parsed_json['current_observation']['icon_url'];
var iconPic = new MyIcon(iconUrl);
var markerRichmond = new L.Marker(new L.LatLng(lat, long), {icon: iconPic});
markerRichmond.bindPopup(title);
map.addLayer(markerRichmond);
}
});
}
I am not sure if I handled the title correctly here, but you get the idea. If you give an idea of how the title may change, I can fix the code accordingly.
Hope this helps.
var current_observation = parsed_json['current_observation'];
This also shortens amount of times parsed. Then you can refer to your variable as
current_observation['observation_location']['city'];

Ajax response and anonymous function scope

In the following code
var entryTemplate = document.getElementById('entryTemplate');
entryTemplate = entryTemplate.firstChild;
for (var ipost in posts)
{
var post = posts[ipost];
var clone = entryTemplate.cloneNode(true);
clone = $(clone);
if (post.imageURL)
{
var imgElement = document.createElement('img');
var largeImageURL = post.largeImageURL ? post.largeImageURL : post.imageURL;
imgElement.src = post.thumbPresent ? POST_THUMB_URL + '/' + post.postID : largeImageURL;
imgElement.alt = '';
clone.find('div.BlogImageURL a').attr('href', largeImageURL).text(largeImageURL);
clone.find('div.BlogImage a').attr('href', imgElement.src).append(imgElement);
// get bytesize
var postdata = 'inline_image_url=' + encodeURIComponent(post.imageURL);
postdata += '&linked_image_url=' + encodeURIComponent(post.largeImageURL);
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
success: function(bytesize) {
clone.find('.BlogImageBytesize').html(bytesize);
}
});
}
else
{
clone.find('div.BlogImageURL').text('(This post contains no images)');
clone.find('div.BlogImage').remove();
}
$('#outputDiv').append(clone);
}
clone.find('.BlogImageBytesize').html(bytesize);
All ajax responses (bold line) modify the last clone, probably because the loop is finished when the first response arrives and clone points to the last clone.
How can I fix this?
Thanks.
Perhaps you could set clone as the context of your ajax call. (See docs here.) Then, I think it would work something like this:
$.ajax({
type: 'POST',
url: ASYNC_GET_BYTESIZE_URL,
data: postdata,
context: clone,
success: function(bytesize) {
$(this).find('.BlogImageBytesize').html(bytesize);
}
});
I don't know for sure if the context has to be a plain DOM element or if it can be a jQuery object, but hopefully this gets you on the right track.

Resources