I'm using Ajax to call data which is in JSON format from the server and when its successful want to pass it to D3.
$(document).ready(function() {
$.ajax({
url: "{% url 'charts_data' %}",
method: 'GET',
data : {
airline_category: 1,
year_category: 5
},
success: function(data){
console.log(data) // Correctly logs data to console
d3.json(data, function(dataSet){
console.log(dataSet) // Null with error 404
})
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
});
I understand I need to provide URL instead data to d3.json. But I want to use this Ajax called data object to build the chart. Ajax called data is in JSON format, how can I use it with D3?
Here is console.log of data:
console.log(data)
Don't bother with d3.json() if you already have the data from the ajax call. Just do everything in success that you would otherwise have done in the body of d3.json.
Related
I'm trying to capture a list of filters in an ajax request, but although I can capture a single filter, when I try to capture a list, I just get an empty list for some reason.
Below is the relevant part of my view and the ajax (jQuery) function. When I try and send a single filter with $.ajax({ .... 'filters': fixed }) this works but fails with a list.
Update: trying data: {'filters': JSON.stringify([fixed])}, does pass the data through as a string to django '["fixed"]' (which I can handle if I don't use getlist but .get and then json.loads() but I think there must be a simpler method here.
def quotes_results_filter_view(request):
results_filters = request.GET.getlist('filters') or []
quotes_results = request.session['quotes_results']
for results_filter in results_filters:
.......
Ajax function:
$(document).ready(function () {
$('#id_filter').change(function (e) {
var fixed = $(this).val()
console.log(fixed)
$.ajax({
url: '/users/filters/',
data: {
'filters': [fixed]
},
dataType: 'json',
success: function (data) {
console.log(data)
}
})
When you send a list through jQuery it changes the keyword to
so in Django you probably have to get like this:
request.GET.getlist('filters[]')
Am trying to return a json object to render to a grid in my template.
This is how i do it.
views.py
def ajax_up(request):
history_data=Upload_history.objects.all()
history=serializers.serialize("json",history_data)
return HttpResponse( history, mimetype='application/json' )
html
$(".reply").click(function(){
$.ajax({
url: "/ajax_up/",
type: 'GET', //this is the default though, you don't actually need to always mention it
dataType: "json",
success: function(data) {
alert("awasome"+ data)
},
failure: function(data) {
alert('Got an error');
}
});
so i declare an object to hold the data as
var data = {{history|safe}};
where history is returned from the ajax call as in view above
but when i do alert(data), i get [object object],[object object].....
can any one help please?
Sounds like it's working, but alert just displays a string. Since your data is not a string, it'll show [object Object].
Either serialize the data with JSON.stringify or use console.log instead of alert to see the data in your browser javascript console.
I have been picking away at this, though thought I would reach out for some advice, if I may, I am fairly new to AJAX.
Right, I am using the django framework, I post the data to the server, which works great, then receive some data back on the callback function, which works, though I want this to be in JSON format so I can populate a table. Currently it either renders in plain text or the browser asks me to download the json data, meaning somethings not quite catching on the $.get part. My code is:
#views.py
if request.POST:
est_show = login_a.test()
return HttpResponse(est_show, content_type='application/json')
<!--JQUERY/AJAX-->
<script type="text/javascript">
$(document).on("submit","#these_choices",function (event) {
var data_form = $('#these_choices').serialize();
if(data_form) {
$.ajax({
type: "POST",
url: "{% url Create_this %}",
data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'},
cache:false,
success: function(){
jQuery(document).ready(function ($) {
$.get('{% url Create_this %}', function(data) {
alert(data[0]);
});});
},
error: function(){
alert('error !!!!');
}
});}
else {
alert('error elsewhere');
}
event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out...
return false;
});
</script>
It also seems the alert(data[0]) is being ran before the json data is being received in the browser. Any advice will be appreciated?
Many thanks
Try setting the mimetype in the HttpResponse to application/json. When you don't specify a dataType in the ajax request, JQuery automatically tries to infer it based on the mimetype of the response.
return HttpResponse(est_show, mimetype='application/json')
Alternatively, you can set the dataType to json to tell JQuery to expect json.
I have a very basic ajax call to alert the data that was reported from the server
$.ajax({
type: "POST",
url: "/someform/act", //edit utl to url
data: { changed: JSON.stringify(plainData) }, //edit to include
success: function(data) {
alert(data); //data not $data
},
error: function() {
//error condition code
}
});
According to the docs on the jquery website regarding data field on the success callback, it says that data returned is the data from the server. However for some strange reason when I alert $data, I get [object Object]
I was expecting to see something like this, since that is what the server would send back
<status>0</status>
EDIT:
data is also passed along as the POST
You need to use JSON.stringify(data) in the alert to get anything readable.
Also, $data is a completely different variable name than data.
alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better.
If you server send a JSON, you need to put dataType: 'json' to your ajax call. Be aware there's some mistake in your ajax call.
$.ajax({
type: "POST",
url: "/someform/act", // NOT 'UTL',
data: {
key: value,
key2: value2
},
// or data: plaindata, // If 'plaindata' is an object.
dataType: 'json',
success: function(data) {
console.log(data); // As moonwave99 said
},
error: function() {
//error condition code
}
});
EDIT
When sending data, you should send an object. jQuery will handle the array to sned it to the server. So if plain data is an object, it should be like this
data: plainData,
If you're sending data via $.ajax({...}), the Network tab of your browser inspector might be showing [object Object] in the Payload (Chrome) / Request (Firefox) sub-tab, like in the following image (Firefox):
The reason for this might be in the way you're forming your AJAX call. Specifically:
$.ajax({
url: '/ajax/example-endpoint',
data: {'fooKey':fooData,'barKey':barData},
type: 'post',
cache: false,
contentType: false, // this one will turn your data into something like fooKey=fooData&barKey=barData
processData: false, // and this one will make it [object Object]:""
beforeSend: function() {
// whatever it is you need to do
},
success: function(data) {
// do stuff
},
error: function(desc, err) {
// do stuff
}
});
When combined, contentType: false and processData: false turn your data into [object Object], because you're actually telling your AJAX call to ignore the content type of whatever is being sent, and not to process it.
If it's IIS, try creating a site outside of the Default Web Site (for example localhost/ajax1). For example a new site ajax1, place it not in the DefaultAppPool, but in your pool, for example ajax1. Try http://ajax1
Supposing I have the following code which returns a Javascript object which I can read in Firebug's console:
FB.api('/me',function(apiresponse){
console.log(apiresponse);
});
How can I then use the data from apiresponse in an Ajax request on the same page?
Currently my Ajax request looks as follows:
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
I know very little about Javascript, but reading around the subject leads me to think I have to convert the Javascript object to a JSON string. Is that correct? Am I on the right track?
You could put your AJAX call inside the handler for the API call like below..
FB.api('/me', function(apiresponse){
console.log(apiresponse);
$.ajax({
// CodeIgniter URL
url: "<?=site_url?>('login/add_fb_users'); ?>",
type: 'POST',
data: apiresponse,
success: function(data) {
alert(data);
}
});
});
one possible way:
define a global variable in your javascript, e.g. var myVar1;
set apireponse to the global variable in your FB.api callback (i.e. where u call console.log)
reference the var myVar1 in your ajax fcn.